blob: b5b7a314f000156ec24f2c527efc1f21d2b43d85 [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"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith7a614d82011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Sean Hunt001cad92011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith7a614d82011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssoned961f92009-08-25 02:29:20 +0000210bool
John McCall9ae2f072010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssoned961f92009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000233 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000235
John McCallb4eb64d2010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson9351c172009-08-25 03:18:48 +0000254 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000255}
256
Chris Lattner8123a952008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260void
John McCalld226f652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000264 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
John McCalld226f652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6f526752010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlsson66e30672009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall9ae2f072010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000291}
292
Douglas Gregor61366e92008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000308}
309
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Anders Carlsson5e300d12009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000321}
322
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000388
Francois Pichet8d051e02011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
395 if (getLangOptions().Microsoft) {
396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000409
Francois Pichet8cf90492011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCall3d6c1782010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000501 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregore13ad832010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000507
Douglas Gregorcda9c672009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000509}
510
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551}
552
Chris Lattner3d1cee32008-04-08 05:04:30 +0000553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000583 else
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604
Douglas Gregorb48fe382008-10-31 09:07:45 +0000605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000680 return 0;
John McCall572fc622010-08-17 07:23:57 +0000681 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000682
Eli Friedman1d954f62009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000690
Anders Carlsson1d209272011-03-25 14:55:14 +0000691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
John McCall572fc622010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000709}
710
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000716BaseResult
John McCalld226f652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregor40808ce2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky56062202010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000731
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000736
Douglas Gregor2943aed2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregor2943aed2009-03-03 04:44:36 +0000742 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000743}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000744
Douglas Gregor2943aed2009-03-03 04:44:36 +0000745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
John McCalld226f652010-08-21 09:40:31 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000809
John McCall3cb0ebd2010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregora8f32e02009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 return false;
828
John McCall3cb0ebd2010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000831 return false;
832
John McCall86ff3082010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCall3cb0ebd2010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 return false;
846
John McCall3cb0ebd2010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregora8f32e02009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000875}
876
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregora8f32e02009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000926 }
John McCall6b2accb2010-02-10 09:31:12 +0000927 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnara6206d532010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +00001016}
1017
Anders Carlsson9e682d92011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001020 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlsson9e682d92011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +00001063 ExprTy *BW, const VirtSpecifiers &VS,
Richard Smith7a614d82011-06-11 17:19:42 +00001064 ExprTy *InitExpr, bool HasDeferredInit,
1065 bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001077
John McCall4bde1e12010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith7a614d82011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall67d1a672009-08-06 02:15:43 +00001081
Richard Smith1ab0d902011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001083
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001099 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Sebastian Redla11f42f2008-11-17 23:24:37 +00001102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
Sebastian Redl669d5d72008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregor922fff22010-10-13 22:19:53 +00001124 if (SS.isSet() && !SS.isInvalid()) {
1125 // The user provided a superfluous scope specifier inside a class
1126 // definition:
1127 //
1128 // class X {
1129 // int X::member;
1130 // };
1131 DeclContext *DC = 0;
1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134 << Name << FixItHint::CreateRemoval(SS.getRange());
1135 else
1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137 << Name << SS.getRange();
1138
1139 SS.clear();
1140 }
1141
Douglas Gregor37b372b2009-08-20 22:52:58 +00001142 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001143 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001145 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001146 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001147 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001148 assert(!HasDeferredInit);
1149
Sean Hunte4246a62011-05-12 06:15:49 +00001150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001151 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001152 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001153 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001154
1155 // Non-instance-fields can't have a bitfield.
1156 if (BitWidth) {
1157 if (Member->isInvalidDecl()) {
1158 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001159 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001160 // C++ 9.6p3: A bit-field shall not be a static member.
1161 // "static member 'A' cannot be a bit-field"
1162 Diag(Loc, diag::err_static_not_bitfield)
1163 << Name << BitWidth->getSourceRange();
1164 } else if (isa<TypedefDecl>(Member)) {
1165 // "typedef member 'x' cannot be a bit-field"
1166 Diag(Loc, diag::err_typedef_not_bitfield)
1167 << Name << BitWidth->getSourceRange();
1168 } else {
1169 // A function typedef ("typedef int f(); f a;").
1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001172 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001173 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner8b963ef2009-03-05 23:01:03 +00001176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001179
1180 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Douglas Gregor37b372b2009-08-20 22:52:58 +00001182 // If we have declared a member function template, set the access of the
1183 // templated declaration as well.
1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001186 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001187
Anders Carlssonaae5af22011-01-20 04:34:22 +00001188 if (VS.isOverrideSpecified()) {
1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190 if (!MD || !MD->isVirtual()) {
1191 Diag(Member->getLocStart(),
1192 diag::override_keyword_only_allowed_on_virtual_member_functions)
1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001194 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001196 }
1197 if (VS.isFinalSpecified()) {
1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199 if (!MD || !MD->isVirtual()) {
1200 Diag(Member->getLocStart(),
1201 diag::override_keyword_only_allowed_on_virtual_member_functions)
1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001203 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001205 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001206
Douglas Gregorf5251602011-03-08 17:10:18 +00001207 if (VS.getLastLocation().isValid()) {
1208 // Update the end location of a method that has a virt-specifiers.
1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210 MD->setRangeEnd(VS.getLastLocation());
1211 }
1212
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001213 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001214
Douglas Gregor10bd3682008-11-17 22:58:34 +00001215 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001216
Douglas Gregor021c3b32009-03-11 23:00:04 +00001217 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith7a614d82011-06-11 17:19:42 +00001220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223 // data member if a brace-or-equal-initializer is provided.
1224 Diag(Loc, diag::err_auto_var_requires_init)
1225 << Name << cast<ValueDecl>(Member)->getType();
1226 Member->setInvalidDecl();
1227 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001228
Richard Smith483b9f32011-02-21 20:05:19 +00001229 FinalizeDeclaration(Member);
1230
John McCallb25b2952011-02-15 07:12:36 +00001231 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001232 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001233 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001234}
1235
Richard Smith7a614d82011-06-11 17:19:42 +00001236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001237/// in-class initializer for a non-static C++ class member, and after
1238/// instantiating an in-class initializer in a class template. Such actions
1239/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001240void
1241Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1242 Expr *InitExpr) {
1243 FieldDecl *FD = cast<FieldDecl>(D);
1244
1245 if (!InitExpr) {
1246 FD->setInvalidDecl();
1247 FD->removeInClassInitializer();
1248 return;
1249 }
1250
1251 ExprResult Init = InitExpr;
1252 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1253 // FIXME: if there is no EqualLoc, this is list-initialization.
1254 Init = PerformCopyInitialization(
1255 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1256 if (Init.isInvalid()) {
1257 FD->setInvalidDecl();
1258 return;
1259 }
1260
1261 CheckImplicitConversions(Init.get(), EqualLoc);
1262 }
1263
1264 // C++0x [class.base.init]p7:
1265 // The initialization of each base and member constitutes a
1266 // full-expression.
1267 Init = MaybeCreateExprWithCleanups(Init);
1268 if (Init.isInvalid()) {
1269 FD->setInvalidDecl();
1270 return;
1271 }
1272
1273 InitExpr = Init.release();
1274
1275 FD->setInClassInitializer(InitExpr);
1276}
1277
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001278/// \brief Find the direct and/or virtual base specifiers that
1279/// correspond to the given base type, for use in base initialization
1280/// within a constructor.
1281static bool FindBaseInitializer(Sema &SemaRef,
1282 CXXRecordDecl *ClassDecl,
1283 QualType BaseType,
1284 const CXXBaseSpecifier *&DirectBaseSpec,
1285 const CXXBaseSpecifier *&VirtualBaseSpec) {
1286 // First, check for a direct base class.
1287 DirectBaseSpec = 0;
1288 for (CXXRecordDecl::base_class_const_iterator Base
1289 = ClassDecl->bases_begin();
1290 Base != ClassDecl->bases_end(); ++Base) {
1291 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1292 // We found a direct base of this type. That's what we're
1293 // initializing.
1294 DirectBaseSpec = &*Base;
1295 break;
1296 }
1297 }
1298
1299 // Check for a virtual base class.
1300 // FIXME: We might be able to short-circuit this if we know in advance that
1301 // there are no virtual bases.
1302 VirtualBaseSpec = 0;
1303 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1304 // We haven't found a base yet; search the class hierarchy for a
1305 // virtual base class.
1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307 /*DetectVirtual=*/false);
1308 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1309 BaseType, Paths)) {
1310 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1311 Path != Paths.end(); ++Path) {
1312 if (Path->back().Base->isVirtual()) {
1313 VirtualBaseSpec = Path->back().Base;
1314 break;
1315 }
1316 }
1317 }
1318 }
1319
1320 return DirectBaseSpec || VirtualBaseSpec;
1321}
1322
Douglas Gregor7ad83902008-11-05 04:29:56 +00001323/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001324MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001325Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001326 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001327 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001328 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001329 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001330 SourceLocation IdLoc,
1331 SourceLocation LParenLoc,
1332 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001333 SourceLocation RParenLoc,
1334 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001335 if (!ConstructorD)
1336 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001338 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001339
1340 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001341 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001342 if (!Constructor) {
1343 // The user wrote a constructor initializer on a function that is
1344 // not a C++ constructor. Ignore the error for now, because we may
1345 // have more member initializers coming; we'll diagnose it just
1346 // once in ActOnMemInitializers.
1347 return true;
1348 }
1349
1350 CXXRecordDecl *ClassDecl = Constructor->getParent();
1351
1352 // C++ [class.base.init]p2:
1353 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001354 // constructor's class and, if not found in that scope, are looked
1355 // up in the scope containing the constructor's definition.
1356 // [Note: if the constructor's class contains a member with the
1357 // same name as a direct or virtual base class of the class, a
1358 // mem-initializer-id naming the member or base class and composed
1359 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001360 // mem-initializer-id for the hidden base class may be specified
1361 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001362 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001363 // Look for a member, first.
1364 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001365 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001366 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001367 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001368 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001369
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001370 if (Member) {
1371 if (EllipsisLoc.isValid())
1372 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1373 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1374
Francois Pichet00eb3f92010-12-04 09:14:42 +00001375 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001376 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001377 }
1378
Francois Pichet00eb3f92010-12-04 09:14:42 +00001379 // Handle anonymous union case.
1380 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001381 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1382 if (EllipsisLoc.isValid())
1383 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1384 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1385
Francois Pichet00eb3f92010-12-04 09:14:42 +00001386 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1387 NumArgs, IdLoc,
1388 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001389 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001390 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001391 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001392 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001393 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001394 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001395
1396 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001397 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001398 } else {
1399 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1400 LookupParsedName(R, S, &SS);
1401
1402 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1403 if (!TyD) {
1404 if (R.isAmbiguous()) return true;
1405
John McCallfd225442010-04-09 19:01:14 +00001406 // We don't want access-control diagnostics here.
1407 R.suppressDiagnostics();
1408
Douglas Gregor7a886e12010-01-19 06:46:48 +00001409 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1410 bool NotUnknownSpecialization = false;
1411 DeclContext *DC = computeDeclContext(SS, false);
1412 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1413 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1414
1415 if (!NotUnknownSpecialization) {
1416 // When the scope specifier can refer to a member of an unknown
1417 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001418 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1419 SS.getWithLocInContext(Context),
1420 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001421 if (BaseType.isNull())
1422 return true;
1423
Douglas Gregor7a886e12010-01-19 06:46:48 +00001424 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001425 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001426 }
1427 }
1428
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001429 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001430 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00001431 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001432 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1433 ClassDecl, false, CTC_NoKeywords))) {
1434 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1435 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1436 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001437 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001438 // We have found a non-static data member with a similar
1439 // name to what was typed; complain and initialize that
1440 // member.
1441 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001442 << MemberOrBase << true << CorrectedQuotedStr
1443 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001444 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001445 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001446
1447 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1448 LParenLoc, RParenLoc);
1449 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001450 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001451 const CXXBaseSpecifier *DirectBaseSpec;
1452 const CXXBaseSpecifier *VirtualBaseSpec;
1453 if (FindBaseInitializer(*this, ClassDecl,
1454 Context.getTypeDeclType(Type),
1455 DirectBaseSpec, VirtualBaseSpec)) {
1456 // We have found a direct or virtual base class with a
1457 // similar name to what was typed; complain and initialize
1458 // that base class.
1459 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001460 << MemberOrBase << false << CorrectedQuotedStr
1461 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001462
1463 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1464 : VirtualBaseSpec;
1465 Diag(BaseSpec->getSourceRange().getBegin(),
1466 diag::note_base_class_specified_here)
1467 << BaseSpec->getType()
1468 << BaseSpec->getSourceRange();
1469
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001470 TyD = Type;
1471 }
1472 }
1473 }
1474
Douglas Gregor7a886e12010-01-19 06:46:48 +00001475 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001476 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1477 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1478 return true;
1479 }
John McCall2b194412009-12-21 10:41:20 +00001480 }
1481
Douglas Gregor7a886e12010-01-19 06:46:48 +00001482 if (BaseType.isNull()) {
1483 BaseType = Context.getTypeDeclType(TyD);
1484 if (SS.isSet()) {
1485 NestedNameSpecifier *Qualifier =
1486 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001487
Douglas Gregor7a886e12010-01-19 06:46:48 +00001488 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001489 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001490 }
John McCall2b194412009-12-21 10:41:20 +00001491 }
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
John McCalla93c9342009-12-07 02:54:59 +00001494 if (!TInfo)
1495 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001496
John McCalla93c9342009-12-07 02:54:59 +00001497 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001498 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001499}
1500
John McCallb4190042009-11-04 23:02:40 +00001501/// Checks an initializer expression for use of uninitialized fields, such as
1502/// containing the field that is being initialized. Returns true if there is an
1503/// uninitialized field was used an updates the SourceLocation parameter; false
1504/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001505static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001506 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001507 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001508 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1509
Nick Lewycky43ad1822010-06-15 07:32:55 +00001510 if (isa<CallExpr>(S)) {
1511 // Do not descend into function calls or constructors, as the use
1512 // of an uninitialized field may be valid. One would have to inspect
1513 // the contents of the function/ctor to determine if it is safe or not.
1514 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1515 // may be safe, depending on what the function/ctor does.
1516 return false;
1517 }
1518 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1519 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001520
1521 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1522 // The member expression points to a static data member.
1523 assert(VD->isStaticDataMember() &&
1524 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001525 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001526 return false;
1527 }
1528
1529 if (isa<EnumConstantDecl>(RhsField)) {
1530 // The member expression points to an enum.
1531 return false;
1532 }
1533
John McCallb4190042009-11-04 23:02:40 +00001534 if (RhsField == LhsField) {
1535 // Initializing a field with itself. Throw a warning.
1536 // But wait; there are exceptions!
1537 // Exception #1: The field may not belong to this record.
1538 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001539 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001540 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1541 // Even though the field matches, it does not belong to this record.
1542 return false;
1543 }
1544 // None of the exceptions triggered; return true to indicate an
1545 // uninitialized field was used.
1546 *L = ME->getMemberLoc();
1547 return true;
1548 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001549 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001550 // sizeof/alignof doesn't reference contents, do not warn.
1551 return false;
1552 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1553 // address-of doesn't reference contents (the pointer may be dereferenced
1554 // in the same expression but it would be rare; and weird).
1555 if (UOE->getOpcode() == UO_AddrOf)
1556 return false;
John McCallb4190042009-11-04 23:02:40 +00001557 }
John McCall7502c1d2011-02-13 04:07:26 +00001558 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001559 if (!*it) {
1560 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001561 continue;
1562 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001563 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1564 return true;
John McCallb4190042009-11-04 23:02:40 +00001565 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001566 return false;
John McCallb4190042009-11-04 23:02:40 +00001567}
1568
John McCallf312b1e2010-08-26 23:41:50 +00001569MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001570Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001571 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001572 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001573 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001574 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1575 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1576 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001577 "Member must be a FieldDecl or IndirectFieldDecl");
1578
Douglas Gregor464b2f02010-11-05 22:21:31 +00001579 if (Member->isInvalidDecl())
1580 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001581
John McCallb4190042009-11-04 23:02:40 +00001582 // Diagnose value-uses of fields to initialize themselves, e.g.
1583 // foo(foo)
1584 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001585 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001586 for (unsigned i = 0; i < NumArgs; ++i) {
1587 SourceLocation L;
1588 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1589 // FIXME: Return true in the case when other fields are used before being
1590 // uninitialized. For example, let this field be the i'th field. When
1591 // initializing the i'th field, throw a warning if any of the >= i'th
1592 // fields are used, as they are not yet initialized.
1593 // Right now we are only handling the case where the i'th field uses
1594 // itself in its initializer.
1595 Diag(L, diag::warn_field_is_uninit);
1596 }
1597 }
1598
Eli Friedman59c04372009-07-29 19:44:27 +00001599 bool HasDependentArg = false;
1600 for (unsigned i = 0; i < NumArgs; i++)
1601 HasDependentArg |= Args[i]->isTypeDependent();
1602
Chandler Carruth894aed92010-12-06 09:23:57 +00001603 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001604 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001605 // Can't check initialization for a member of dependent type or when
1606 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001607 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001608 RParenLoc,
1609 Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610
John McCallf85e1932011-06-15 23:02:42 +00001611 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001612 } else {
1613 // Initialize the member.
1614 InitializedEntity MemberEntity =
1615 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1616 : InitializedEntity::InitializeMember(IndirectMember, 0);
1617 InitializationKind Kind =
1618 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001619
Chandler Carruth894aed92010-12-06 09:23:57 +00001620 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1621
1622 ExprResult MemberInit =
1623 InitSeq.Perform(*this, MemberEntity, Kind,
1624 MultiExprArg(*this, Args, NumArgs), 0);
1625 if (MemberInit.isInvalid())
1626 return true;
1627
1628 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1629
1630 // C++0x [class.base.init]p7:
1631 // The initialization of each base and member constitutes a
1632 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001633 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001634 if (MemberInit.isInvalid())
1635 return true;
1636
1637 // If we are in a dependent context, template instantiation will
1638 // perform this type-checking again. Just save the arguments that we
1639 // received in a ParenListExpr.
1640 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1641 // of the information that we have about the member
1642 // initializer. However, deconstructing the ASTs is a dicey process,
1643 // and this approach is far more likely to get the corner cases right.
1644 if (CurContext->isDependentContext())
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001645 Init = new (Context) ParenListExpr(
1646 Context, LParenLoc, Args, NumArgs, RParenLoc,
1647 Member->getType().getNonReferenceType());
Chandler Carruth894aed92010-12-06 09:23:57 +00001648 else
1649 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001650 }
1651
Chandler Carruth894aed92010-12-06 09:23:57 +00001652 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001653 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001654 IdLoc, LParenLoc, Init,
1655 RParenLoc);
1656 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001657 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001658 IdLoc, LParenLoc, Init,
1659 RParenLoc);
1660 }
Eli Friedman59c04372009-07-29 19:44:27 +00001661}
1662
John McCallf312b1e2010-08-26 23:41:50 +00001663MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001664Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1665 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001666 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001667 SourceLocation LParenLoc,
1668 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001669 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001670 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1671 if (!LangOpts.CPlusPlus0x)
1672 return Diag(Loc, diag::err_delegation_0x_only)
1673 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001674
Sean Hunt41717662011-02-26 19:13:13 +00001675 // Initialize the object.
1676 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1677 QualType(ClassDecl->getTypeForDecl(), 0));
1678 InitializationKind Kind =
1679 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1680
1681 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1682
1683 ExprResult DelegationInit =
1684 InitSeq.Perform(*this, DelegationEntity, Kind,
1685 MultiExprArg(*this, Args, NumArgs), 0);
1686 if (DelegationInit.isInvalid())
1687 return true;
1688
1689 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001690 CXXConstructorDecl *Constructor
1691 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001692 assert(Constructor && "Delegating constructor with no target?");
1693
1694 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1695
1696 // C++0x [class.base.init]p7:
1697 // The initialization of each base and member constitutes a
1698 // full-expression.
1699 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1700 if (DelegationInit.isInvalid())
1701 return true;
1702
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001703 assert(!CurContext->isDependentContext());
Sean Hunt41717662011-02-26 19:13:13 +00001704 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1705 DelegationInit.takeAs<Expr>(),
1706 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001707}
1708
1709MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001710Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001711 Expr **Args, unsigned NumArgs,
1712 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001713 CXXRecordDecl *ClassDecl,
1714 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001715 bool HasDependentArg = false;
1716 for (unsigned i = 0; i < NumArgs; i++)
1717 HasDependentArg |= Args[i]->isTypeDependent();
1718
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001719 SourceLocation BaseLoc
1720 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1721
1722 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1723 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1724 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1725
1726 // C++ [class.base.init]p2:
1727 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001728 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001729 // of that class, the mem-initializer is ill-formed. A
1730 // mem-initializer-list can initialize a base class using any
1731 // name that denotes that base class type.
1732 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1733
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001734 if (EllipsisLoc.isValid()) {
1735 // This is a pack expansion.
1736 if (!BaseType->containsUnexpandedParameterPack()) {
1737 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1738 << SourceRange(BaseLoc, RParenLoc);
1739
1740 EllipsisLoc = SourceLocation();
1741 }
1742 } else {
1743 // Check for any unexpanded parameter packs.
1744 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1745 return true;
1746
1747 for (unsigned I = 0; I != NumArgs; ++I)
1748 if (DiagnoseUnexpandedParameterPack(Args[I]))
1749 return true;
1750 }
1751
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001752 // Check for direct and virtual base classes.
1753 const CXXBaseSpecifier *DirectBaseSpec = 0;
1754 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1755 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001756 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1757 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001758 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1759 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001760
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001761 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1762 VirtualBaseSpec);
1763
1764 // C++ [base.class.init]p2:
1765 // Unless the mem-initializer-id names a nonstatic data member of the
1766 // constructor's class or a direct or virtual base of that class, the
1767 // mem-initializer is ill-formed.
1768 if (!DirectBaseSpec && !VirtualBaseSpec) {
1769 // If the class has any dependent bases, then it's possible that
1770 // one of those types will resolve to the same type as
1771 // BaseType. Therefore, just treat this as a dependent base
1772 // class initialization. FIXME: Should we try to check the
1773 // initialization anyway? It seems odd.
1774 if (ClassDecl->hasAnyDependentBases())
1775 Dependent = true;
1776 else
1777 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1778 << BaseType << Context.getTypeDeclType(ClassDecl)
1779 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1780 }
1781 }
1782
1783 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001784 // Can't check initialization for a base of dependent type or when
1785 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001786 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001787 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001788 RParenLoc, BaseType));
Eli Friedman59c04372009-07-29 19:44:27 +00001789
John McCallf85e1932011-06-15 23:02:42 +00001790 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Sean Huntcbb67482011-01-08 20:30:50 +00001792 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001793 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001794 LParenLoc,
1795 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001796 RParenLoc,
1797 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001798 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001799
1800 // C++ [base.class.init]p2:
1801 // If a mem-initializer-id is ambiguous because it designates both
1802 // a direct non-virtual base class and an inherited virtual base
1803 // class, the mem-initializer is ill-formed.
1804 if (DirectBaseSpec && VirtualBaseSpec)
1805 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001806 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001807
1808 CXXBaseSpecifier *BaseSpec
1809 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1810 if (!BaseSpec)
1811 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1812
1813 // Initialize the base.
1814 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001815 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001816 InitializationKind Kind =
1817 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1818
1819 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1820
John McCall60d7b3a2010-08-24 06:29:42 +00001821 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001822 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001823 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001824 if (BaseInit.isInvalid())
1825 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001826
1827 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001828
1829 // C++0x [class.base.init]p7:
1830 // The initialization of each base and member constitutes a
1831 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001832 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001833 if (BaseInit.isInvalid())
1834 return true;
1835
1836 // If we are in a dependent context, template instantiation will
1837 // perform this type-checking again. Just save the arguments that we
1838 // received in a ParenListExpr.
1839 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1840 // of the information that we have about the base
1841 // initializer. However, deconstructing the ASTs is a dicey process,
1842 // and this approach is far more likely to get the corner cases right.
1843 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001844 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001845 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001846 RParenLoc, BaseType));
Sean Huntcbb67482011-01-08 20:30:50 +00001847 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001848 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001849 LParenLoc,
1850 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001851 RParenLoc,
1852 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001853 }
1854
Sean Huntcbb67482011-01-08 20:30:50 +00001855 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001856 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001857 LParenLoc,
1858 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001859 RParenLoc,
1860 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001861}
1862
Anders Carlssone5ef7402010-04-23 03:10:23 +00001863/// ImplicitInitializerKind - How an implicit base or member initializer should
1864/// initialize its base or member.
1865enum ImplicitInitializerKind {
1866 IIK_Default,
1867 IIK_Copy,
1868 IIK_Move
1869};
1870
Anders Carlssondefefd22010-04-23 02:00:02 +00001871static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001872BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001873 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001874 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001875 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001876 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001877 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001878 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1879 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001880
John McCall60d7b3a2010-08-24 06:29:42 +00001881 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001882
1883 switch (ImplicitInitKind) {
1884 case IIK_Default: {
1885 InitializationKind InitKind
1886 = InitializationKind::CreateDefault(Constructor->getLocation());
1887 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1888 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001889 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001890 break;
1891 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001892
Anders Carlssone5ef7402010-04-23 03:10:23 +00001893 case IIK_Copy: {
1894 ParmVarDecl *Param = Constructor->getParamDecl(0);
1895 QualType ParamType = Param->getType().getNonReferenceType();
1896
1897 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001898 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001899 Constructor->getLocation(), ParamType,
1900 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001901
Anders Carlssonc7957502010-04-24 22:02:54 +00001902 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001903 QualType ArgTy =
1904 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1905 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001906
1907 CXXCastPath BasePath;
1908 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001909 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1910 CK_UncheckedDerivedToBase,
1911 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001912
Anders Carlssone5ef7402010-04-23 03:10:23 +00001913 InitializationKind InitKind
1914 = InitializationKind::CreateDirect(Constructor->getLocation(),
1915 SourceLocation(), SourceLocation());
1916 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1917 &CopyCtorArg, 1);
1918 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001919 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001920 break;
1921 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001922
Anders Carlssone5ef7402010-04-23 03:10:23 +00001923 case IIK_Move:
1924 assert(false && "Unhandled initializer kind!");
1925 }
John McCall9ae2f072010-08-23 23:25:46 +00001926
Douglas Gregor53c374f2010-12-07 00:41:46 +00001927 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001928 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001929 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001930
Anders Carlssondefefd22010-04-23 02:00:02 +00001931 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001932 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001933 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1934 SourceLocation()),
1935 BaseSpec->isVirtual(),
1936 SourceLocation(),
1937 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001938 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001939 SourceLocation());
1940
Anders Carlssondefefd22010-04-23 02:00:02 +00001941 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001942}
1943
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001944static bool
1945BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001946 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00001947 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00001948 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001949 if (Field->isInvalidDecl())
1950 return true;
1951
Chandler Carruthf186b542010-06-29 23:50:44 +00001952 SourceLocation Loc = Constructor->getLocation();
1953
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001954 if (ImplicitInitKind == IIK_Copy) {
1955 ParmVarDecl *Param = Constructor->getParamDecl(0);
1956 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00001957
1958 // Suppress copying zero-width bitfields.
1959 if (const Expr *Width = Field->getBitWidth())
1960 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1961 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001962
1963 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001964 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001965 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001966
1967 // Build a reference to this field within the parameter.
1968 CXXScopeSpec SS;
1969 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1970 Sema::LookupMemberName);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00001971 MemberLookup.addDecl(Indirect? cast<ValueDecl>(Indirect) : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001972 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001973 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001974 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001975 ParamType, Loc,
1976 /*IsArrow=*/false,
1977 SS,
1978 /*FirstQualifierInScope=*/0,
1979 MemberLookup,
1980 /*TemplateArgs=*/0);
1981 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001982 return true;
1983
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001984 // When the field we are copying is an array, create index variables for
1985 // each dimension of the array. We use these index variables to subscript
1986 // the source array, and other clients (e.g., CodeGen) will perform the
1987 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001988 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001989 QualType BaseType = Field->getType();
1990 QualType SizeType = SemaRef.Context.getSizeType();
1991 while (const ConstantArrayType *Array
1992 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1993 // Create the iteration variable for this array index.
1994 IdentifierInfo *IterationVarName = 0;
1995 {
1996 llvm::SmallString<8> Str;
1997 llvm::raw_svector_ostream OS(Str);
1998 OS << "__i" << IndexVariables.size();
1999 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2000 }
2001 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002002 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002003 IterationVarName, SizeType,
2004 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002005 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002006 IndexVariables.push_back(IterationVar);
2007
2008 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002009 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002010 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002011 assert(!IterationVarRef.isInvalid() &&
2012 "Reference to invented variable cannot fail!");
2013
2014 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00002015 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002016 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002017 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002018 Loc);
2019 if (CopyCtorArg.isInvalid())
2020 return true;
2021
2022 BaseType = Array->getElementType();
2023 }
2024
2025 // Construct the entity that we will be initializing. For an array, this
2026 // will be first element in the array, which may require several levels
2027 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002028 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002029 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002030 if (Indirect)
2031 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2032 else
2033 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002034 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2035 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2036 0,
2037 Entities.back()));
2038
2039 // Direct-initialize to use the copy constructor.
2040 InitializationKind InitKind =
2041 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2042
2043 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2044 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2045 &CopyCtorArgE, 1);
2046
John McCall60d7b3a2010-08-24 06:29:42 +00002047 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002048 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002049 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002050 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002051 if (MemberInit.isInvalid())
2052 return true;
2053
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002054 if (Indirect) {
2055 assert(IndexVariables.size() == 0 &&
2056 "Indirect field improperly initialized");
2057 CXXMemberInit
2058 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2059 Loc, Loc,
2060 MemberInit.takeAs<Expr>(),
2061 Loc);
2062 } else
2063 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2064 Loc, MemberInit.takeAs<Expr>(),
2065 Loc,
2066 IndexVariables.data(),
2067 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002068 return false;
2069 }
2070
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002071 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2072
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002073 QualType FieldBaseElementType =
2074 SemaRef.Context.getBaseElementType(Field->getType());
2075
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002076 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002077 InitializedEntity InitEntity
2078 = Indirect? InitializedEntity::InitializeMember(Indirect)
2079 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002080 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002081 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002082
2083 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002084 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002085 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002086
Douglas Gregor53c374f2010-12-07 00:41:46 +00002087 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002088 if (MemberInit.isInvalid())
2089 return true;
2090
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002091 if (Indirect)
2092 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2093 Indirect, Loc,
2094 Loc,
2095 MemberInit.get(),
2096 Loc);
2097 else
2098 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2099 Field, Loc, Loc,
2100 MemberInit.get(),
2101 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002102 return false;
2103 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002104
Sean Hunt1f2f3842011-05-17 00:19:05 +00002105 if (!Field->getParent()->isUnion()) {
2106 if (FieldBaseElementType->isReferenceType()) {
2107 SemaRef.Diag(Constructor->getLocation(),
2108 diag::err_uninitialized_member_in_ctor)
2109 << (int)Constructor->isImplicit()
2110 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2111 << 0 << Field->getDeclName();
2112 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2113 return true;
2114 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002115
Sean Hunt1f2f3842011-05-17 00:19:05 +00002116 if (FieldBaseElementType.isConstQualified()) {
2117 SemaRef.Diag(Constructor->getLocation(),
2118 diag::err_uninitialized_member_in_ctor)
2119 << (int)Constructor->isImplicit()
2120 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2121 << 1 << Field->getDeclName();
2122 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2123 return true;
2124 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002125 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002126
John McCallf85e1932011-06-15 23:02:42 +00002127 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2128 FieldBaseElementType->isObjCRetainableType() &&
2129 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2130 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2131 // Instant objects:
2132 // Default-initialize Objective-C pointers to NULL.
2133 CXXMemberInit
2134 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2135 Loc, Loc,
2136 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2137 Loc);
2138 return false;
2139 }
2140
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002141 // Nothing to initialize.
2142 CXXMemberInit = 0;
2143 return false;
2144}
John McCallf1860e52010-05-20 23:23:51 +00002145
2146namespace {
2147struct BaseAndFieldInfo {
2148 Sema &S;
2149 CXXConstructorDecl *Ctor;
2150 bool AnyErrorsInInits;
2151 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002152 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002153 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002154
2155 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2156 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2157 // FIXME: Handle implicit move constructors.
2158 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2159 IIK = IIK_Copy;
2160 else
2161 IIK = IIK_Default;
2162 }
2163};
2164}
2165
Richard Smith7a614d82011-06-11 17:19:42 +00002166static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002167 FieldDecl *Field,
2168 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002169
Chandler Carruthe861c602010-06-30 02:59:29 +00002170 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002171 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002172 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002173 return false;
2174 }
2175
Richard Smith7a614d82011-06-11 17:19:42 +00002176 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2177 // has a brace-or-equal-initializer, the entity is initialized as specified
2178 // in [dcl.init].
2179 if (Field->hasInClassInitializer()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002180 CXXCtorInitializer *Init;
2181 if (Indirect)
2182 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2183 SourceLocation(),
2184 SourceLocation(), 0,
2185 SourceLocation());
2186 else
2187 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2188 SourceLocation(),
2189 SourceLocation(), 0,
2190 SourceLocation());
2191 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002192 return false;
2193 }
2194
John McCallf1860e52010-05-20 23:23:51 +00002195 // Don't try to build an implicit initializer if there were semantic
2196 // errors in any of the initializers (and therefore we might be
2197 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002198 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002199 return false;
2200
Sean Huntcbb67482011-01-08 20:30:50 +00002201 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002202 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2203 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002204 return true;
John McCallf1860e52010-05-20 23:23:51 +00002205
Francois Pichet00eb3f92010-12-04 09:14:42 +00002206 if (Init)
2207 Info.AllToInit.push_back(Init);
2208
John McCallf1860e52010-05-20 23:23:51 +00002209 return false;
2210}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002211
2212bool
2213Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2214 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002215 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002216 Constructor->setNumCtorInitializers(1);
2217 CXXCtorInitializer **initializer =
2218 new (Context) CXXCtorInitializer*[1];
2219 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2220 Constructor->setCtorInitializers(initializer);
2221
Sean Huntb76af9c2011-05-03 23:05:34 +00002222 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2223 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2224 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2225 }
2226
Sean Huntc1598702011-05-05 00:05:47 +00002227 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002228
Sean Hunt059ce0d2011-05-01 07:04:31 +00002229 return false;
2230}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002231
2232/// \brief Determine whether the given indirect field declaration is somewhere
2233/// within an anonymous union.
2234static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2235 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2236 CEnd = F->chain_end();
2237 C != CEnd; ++C)
2238 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2239 if (Record->isUnion())
2240 return true;
2241
2242 return false;
2243}
2244
John McCallb77115d2011-06-17 00:18:42 +00002245bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2246 CXXCtorInitializer **Initializers,
2247 unsigned NumInitializers,
2248 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002249 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002250 // Just store the initializers as written, they will be checked during
2251 // instantiation.
2252 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002253 Constructor->setNumCtorInitializers(NumInitializers);
2254 CXXCtorInitializer **baseOrMemberInitializers =
2255 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002256 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002257 NumInitializers * sizeof(CXXCtorInitializer*));
2258 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002259 }
2260
2261 return false;
2262 }
2263
John McCallf1860e52010-05-20 23:23:51 +00002264 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002265
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002266 // We need to build the initializer AST according to order of construction
2267 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002268 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002269 if (!ClassDecl)
2270 return true;
2271
Eli Friedman80c30da2009-11-09 19:20:36 +00002272 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002274 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002275 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002276
2277 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002278 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002279 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002280 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002281 }
2282
Anders Carlsson711f34a2010-04-21 19:52:01 +00002283 // Keep track of the direct virtual bases.
2284 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2285 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2286 E = ClassDecl->bases_end(); I != E; ++I) {
2287 if (I->isVirtual())
2288 DirectVBases.insert(I);
2289 }
2290
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002291 // Push virtual bases before others.
2292 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2293 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2294
Sean Huntcbb67482011-01-08 20:30:50 +00002295 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002296 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2297 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002298 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002299 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002300 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002301 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002302 VBase, IsInheritedVirtualBase,
2303 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002304 HadError = true;
2305 continue;
2306 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002307
John McCallf1860e52010-05-20 23:23:51 +00002308 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002309 }
2310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
John McCallf1860e52010-05-20 23:23:51 +00002312 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002313 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2314 E = ClassDecl->bases_end(); Base != E; ++Base) {
2315 // Virtuals are in the virtual base list and already constructed.
2316 if (Base->isVirtual())
2317 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Sean Huntcbb67482011-01-08 20:30:50 +00002319 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002320 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2321 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002322 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002323 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002324 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002325 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002326 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002327 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002328 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002329 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002330
John McCallf1860e52010-05-20 23:23:51 +00002331 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002332 }
2333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
John McCallf1860e52010-05-20 23:23:51 +00002335 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002336 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2337 MemEnd = ClassDecl->decls_end();
2338 Mem != MemEnd; ++Mem) {
2339 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2340 if (F->getType()->isIncompleteArrayType()) {
2341 assert(ClassDecl->hasFlexibleArrayMember() &&
2342 "Incomplete array type is not valid");
2343 continue;
2344 }
2345
2346 // If we're not generating the implicit copy constructor, then we'll
2347 // handle anonymous struct/union fields based on their individual
2348 // indirect fields.
2349 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2350 continue;
2351
2352 if (CollectFieldInitializer(*this, Info, F))
2353 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002354 continue;
2355 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002356
2357 // Beyond this point, we only consider default initialization.
2358 if (Info.IIK != IIK_Default)
2359 continue;
2360
2361 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2362 if (F->getType()->isIncompleteArrayType()) {
2363 assert(ClassDecl->hasFlexibleArrayMember() &&
2364 "Incomplete array type is not valid");
2365 continue;
2366 }
2367
2368 // If this field is somewhere within an anonymous union, we only
2369 // initialize it if there's an explicit initializer.
2370 if (isWithinAnonymousUnion(F)) {
2371 if (CXXCtorInitializer *Init
2372 = Info.AllBaseFields.lookup(F->getAnonField())) {
2373 Info.AllToInit.push_back(Init);
2374 }
2375
2376 continue;
2377 }
2378
2379 // Initialize each field of an anonymous struct individually.
2380 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2381 HadError = true;
2382
2383 continue;
2384 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002385 }
Mike Stump1eb44332009-09-09 15:08:12 +00002386
John McCallf1860e52010-05-20 23:23:51 +00002387 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002388 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002389 Constructor->setNumCtorInitializers(NumInitializers);
2390 CXXCtorInitializer **baseOrMemberInitializers =
2391 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002392 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002393 NumInitializers * sizeof(CXXCtorInitializer*));
2394 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002395
John McCallef027fe2010-03-16 21:39:52 +00002396 // Constructors implicitly reference the base and member
2397 // destructors.
2398 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2399 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002400 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002401
2402 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002403}
2404
Eli Friedman6347f422009-07-21 19:28:10 +00002405static void *GetKeyForTopLevelField(FieldDecl *Field) {
2406 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002407 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002408 if (RT->getDecl()->isAnonymousStructOrUnion())
2409 return static_cast<void *>(RT->getDecl());
2410 }
2411 return static_cast<void *>(Field);
2412}
2413
Anders Carlssonea356fb2010-04-02 05:42:15 +00002414static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002415 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002416}
2417
Anders Carlssonea356fb2010-04-02 05:42:15 +00002418static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002419 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002420 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002421 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002422
Eli Friedman6347f422009-07-21 19:28:10 +00002423 // For fields injected into the class via declaration of an anonymous union,
2424 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002425 FieldDecl *Field = Member->getAnyMember();
2426
John McCall3c3ccdb2010-04-10 09:28:51 +00002427 // If the field is a member of an anonymous struct or union, our key
2428 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002429 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002430 if (RD->isAnonymousStructOrUnion()) {
2431 while (true) {
2432 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2433 if (Parent->isAnonymousStructOrUnion())
2434 RD = Parent;
2435 else
2436 break;
2437 }
2438
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002439 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002440 }
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002442 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002443}
2444
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002445static void
2446DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002447 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002448 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002449 unsigned NumInits) {
2450 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002451 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002453 // Don't check initializers order unless the warning is enabled at the
2454 // location of at least one initializer.
2455 bool ShouldCheckOrder = false;
2456 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002457 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002458 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2459 Init->getSourceLocation())
2460 != Diagnostic::Ignored) {
2461 ShouldCheckOrder = true;
2462 break;
2463 }
2464 }
2465 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002466 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002467
John McCalld6ca8da2010-04-10 07:37:23 +00002468 // Build the list of bases and members in the order that they'll
2469 // actually be initialized. The explicit initializers should be in
2470 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002471 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Anders Carlsson071d6102010-04-02 03:38:04 +00002473 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2474
John McCalld6ca8da2010-04-10 07:37:23 +00002475 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002476 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002477 ClassDecl->vbases_begin(),
2478 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002479 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002480
John McCalld6ca8da2010-04-10 07:37:23 +00002481 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002482 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002483 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002484 if (Base->isVirtual())
2485 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002486 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002487 }
Mike Stump1eb44332009-09-09 15:08:12 +00002488
John McCalld6ca8da2010-04-10 07:37:23 +00002489 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002490 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2491 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002492 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002493
John McCalld6ca8da2010-04-10 07:37:23 +00002494 unsigned NumIdealInits = IdealInitKeys.size();
2495 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002496
Sean Huntcbb67482011-01-08 20:30:50 +00002497 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002498 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002499 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002500 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002501
2502 // Scan forward to try to find this initializer in the idealized
2503 // initializers list.
2504 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2505 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002506 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002507
2508 // If we didn't find this initializer, it must be because we
2509 // scanned past it on a previous iteration. That can only
2510 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002511 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002512 Sema::SemaDiagnosticBuilder D =
2513 SemaRef.Diag(PrevInit->getSourceLocation(),
2514 diag::warn_initializer_out_of_order);
2515
Francois Pichet00eb3f92010-12-04 09:14:42 +00002516 if (PrevInit->isAnyMemberInitializer())
2517 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002518 else
2519 D << 1 << PrevInit->getBaseClassInfo()->getType();
2520
Francois Pichet00eb3f92010-12-04 09:14:42 +00002521 if (Init->isAnyMemberInitializer())
2522 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002523 else
2524 D << 1 << Init->getBaseClassInfo()->getType();
2525
2526 // Move back to the initializer's location in the ideal list.
2527 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2528 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002529 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002530
2531 assert(IdealIndex != NumIdealInits &&
2532 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002533 }
John McCalld6ca8da2010-04-10 07:37:23 +00002534
2535 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002536 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002537}
2538
John McCall3c3ccdb2010-04-10 09:28:51 +00002539namespace {
2540bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002541 CXXCtorInitializer *Init,
2542 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002543 if (!PrevInit) {
2544 PrevInit = Init;
2545 return false;
2546 }
2547
2548 if (FieldDecl *Field = Init->getMember())
2549 S.Diag(Init->getSourceLocation(),
2550 diag::err_multiple_mem_initialization)
2551 << Field->getDeclName()
2552 << Init->getSourceRange();
2553 else {
John McCallf4c73712011-01-19 06:33:43 +00002554 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002555 assert(BaseClass && "neither field nor base");
2556 S.Diag(Init->getSourceLocation(),
2557 diag::err_multiple_base_initialization)
2558 << QualType(BaseClass, 0)
2559 << Init->getSourceRange();
2560 }
2561 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2562 << 0 << PrevInit->getSourceRange();
2563
2564 return true;
2565}
2566
Sean Huntcbb67482011-01-08 20:30:50 +00002567typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002568typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2569
2570bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002571 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002572 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002573 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002574 RecordDecl *Parent = Field->getParent();
2575 if (!Parent->isAnonymousStructOrUnion())
2576 return false;
2577
2578 NamedDecl *Child = Field;
2579 do {
2580 if (Parent->isUnion()) {
2581 UnionEntry &En = Unions[Parent];
2582 if (En.first && En.first != Child) {
2583 S.Diag(Init->getSourceLocation(),
2584 diag::err_multiple_mem_union_initialization)
2585 << Field->getDeclName()
2586 << Init->getSourceRange();
2587 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2588 << 0 << En.second->getSourceRange();
2589 return true;
2590 } else if (!En.first) {
2591 En.first = Child;
2592 En.second = Init;
2593 }
2594 }
2595
2596 Child = Parent;
2597 Parent = cast<RecordDecl>(Parent->getDeclContext());
2598 } while (Parent->isAnonymousStructOrUnion());
2599
2600 return false;
2601}
2602}
2603
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002604/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002605void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002606 SourceLocation ColonLoc,
2607 MemInitTy **meminits, unsigned NumMemInits,
2608 bool AnyErrors) {
2609 if (!ConstructorDecl)
2610 return;
2611
2612 AdjustDeclIfTemplate(ConstructorDecl);
2613
2614 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002615 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002616
2617 if (!Constructor) {
2618 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2619 return;
2620 }
2621
Sean Huntcbb67482011-01-08 20:30:50 +00002622 CXXCtorInitializer **MemInits =
2623 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002624
2625 // Mapping for the duplicate initializers check.
2626 // For member initializers, this is keyed with a FieldDecl*.
2627 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002628 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002629
2630 // Mapping for the inconsistent anonymous-union initializers check.
2631 RedundantUnionMap MemberUnions;
2632
Anders Carlssonea356fb2010-04-02 05:42:15 +00002633 bool HadError = false;
2634 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002635 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002636
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002637 // Set the source order index.
2638 Init->setSourceOrder(i);
2639
Francois Pichet00eb3f92010-12-04 09:14:42 +00002640 if (Init->isAnyMemberInitializer()) {
2641 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002642 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2643 CheckRedundantUnionInit(*this, Init, MemberUnions))
2644 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002645 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002646 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2647 if (CheckRedundantInit(*this, Init, Members[Key]))
2648 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002649 } else {
2650 assert(Init->isDelegatingInitializer());
2651 // This must be the only initializer
2652 if (i != 0 || NumMemInits > 1) {
2653 Diag(MemInits[0]->getSourceLocation(),
2654 diag::err_delegating_initializer_alone)
2655 << MemInits[0]->getSourceRange();
2656 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002657 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002658 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002659 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002660 // Return immediately as the initializer is set.
2661 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002662 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002663 }
2664
Anders Carlssonea356fb2010-04-02 05:42:15 +00002665 if (HadError)
2666 return;
2667
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002668 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002669
Sean Huntcbb67482011-01-08 20:30:50 +00002670 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002671}
2672
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002673void
John McCallef027fe2010-03-16 21:39:52 +00002674Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2675 CXXRecordDecl *ClassDecl) {
2676 // Ignore dependent contexts.
2677 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002678 return;
John McCall58e6f342010-03-16 05:22:47 +00002679
2680 // FIXME: all the access-control diagnostics are positioned on the
2681 // field/base declaration. That's probably good; that said, the
2682 // user might reasonably want to know why the destructor is being
2683 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002684
Anders Carlsson9f853df2009-11-17 04:44:12 +00002685 // Non-static data members.
2686 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2687 E = ClassDecl->field_end(); I != E; ++I) {
2688 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002689 if (Field->isInvalidDecl())
2690 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002691 QualType FieldType = Context.getBaseElementType(Field->getType());
2692
2693 const RecordType* RT = FieldType->getAs<RecordType>();
2694 if (!RT)
2695 continue;
2696
2697 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002698 if (FieldClassDecl->isInvalidDecl())
2699 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002700 if (FieldClassDecl->hasTrivialDestructor())
2701 continue;
2702
Douglas Gregordb89f282010-07-01 22:47:18 +00002703 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002704 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002705 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002706 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002707 << Field->getDeclName()
2708 << FieldType);
2709
John McCallef027fe2010-03-16 21:39:52 +00002710 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002711 }
2712
John McCall58e6f342010-03-16 05:22:47 +00002713 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2714
Anders Carlsson9f853df2009-11-17 04:44:12 +00002715 // Bases.
2716 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2717 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002718 // Bases are always records in a well-formed non-dependent class.
2719 const RecordType *RT = Base->getType()->getAs<RecordType>();
2720
2721 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002722 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002723 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002724
John McCall58e6f342010-03-16 05:22:47 +00002725 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002726 // If our base class is invalid, we probably can't get its dtor anyway.
2727 if (BaseClassDecl->isInvalidDecl())
2728 continue;
2729 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002730 if (BaseClassDecl->hasTrivialDestructor())
2731 continue;
John McCall58e6f342010-03-16 05:22:47 +00002732
Douglas Gregordb89f282010-07-01 22:47:18 +00002733 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002734 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002735
2736 // FIXME: caret should be on the start of the class name
2737 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002738 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002739 << Base->getType()
2740 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002741
John McCallef027fe2010-03-16 21:39:52 +00002742 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002743 }
2744
2745 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002746 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2747 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002748
2749 // Bases are always records in a well-formed non-dependent class.
2750 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2751
2752 // Ignore direct virtual bases.
2753 if (DirectVirtualBases.count(RT))
2754 continue;
2755
John McCall58e6f342010-03-16 05:22:47 +00002756 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002757 // If our base class is invalid, we probably can't get its dtor anyway.
2758 if (BaseClassDecl->isInvalidDecl())
2759 continue;
2760 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002761 if (BaseClassDecl->hasTrivialDestructor())
2762 continue;
John McCall58e6f342010-03-16 05:22:47 +00002763
Douglas Gregordb89f282010-07-01 22:47:18 +00002764 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002765 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002766 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002767 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002768 << VBase->getType());
2769
John McCallef027fe2010-03-16 21:39:52 +00002770 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002771 }
2772}
2773
John McCalld226f652010-08-21 09:40:31 +00002774void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002775 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002776 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Mike Stump1eb44332009-09-09 15:08:12 +00002778 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002779 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002780 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002781}
2782
Mike Stump1eb44332009-09-09 15:08:12 +00002783bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002784 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002785 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002786 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002787 else
John McCall94c3b562010-08-18 09:41:07 +00002788 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002789}
2790
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002791bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002792 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002793 if (!getLangOptions().CPlusPlus)
2794 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Anders Carlsson11f21a02009-03-23 19:10:31 +00002796 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002797 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Ted Kremenek6217b802009-07-29 21:53:49 +00002799 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002800 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002801 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002802 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002803
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002804 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002805 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002806 }
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Ted Kremenek6217b802009-07-29 21:53:49 +00002808 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002809 if (!RT)
2810 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002811
John McCall86ff3082010-02-04 22:26:26 +00002812 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002813
John McCall94c3b562010-08-18 09:41:07 +00002814 // We can't answer whether something is abstract until it has a
2815 // definition. If it's currently being defined, we'll walk back
2816 // over all the declarations when we have a full definition.
2817 const CXXRecordDecl *Def = RD->getDefinition();
2818 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002819 return false;
2820
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002821 if (!RD->isAbstract())
2822 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002824 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002825 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002826
John McCall94c3b562010-08-18 09:41:07 +00002827 return true;
2828}
2829
2830void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2831 // Check if we've already emitted the list of pure virtual functions
2832 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002833 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002834 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002836 CXXFinalOverriderMap FinalOverriders;
2837 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002839 // Keep a set of seen pure methods so we won't diagnose the same method
2840 // more than once.
2841 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2842
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002843 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2844 MEnd = FinalOverriders.end();
2845 M != MEnd;
2846 ++M) {
2847 for (OverridingMethods::iterator SO = M->second.begin(),
2848 SOEnd = M->second.end();
2849 SO != SOEnd; ++SO) {
2850 // C++ [class.abstract]p4:
2851 // A class is abstract if it contains or inherits at least one
2852 // pure virtual function for which the final overrider is pure
2853 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002855 //
2856 if (SO->second.size() != 1)
2857 continue;
2858
2859 if (!SO->second.front().Method->isPure())
2860 continue;
2861
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002862 if (!SeenPureMethods.insert(SO->second.front().Method))
2863 continue;
2864
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002865 Diag(SO->second.front().Method->getLocation(),
2866 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002867 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002868 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002869 }
2870
2871 if (!PureVirtualClassDiagSet)
2872 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2873 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002874}
2875
Anders Carlsson8211eff2009-03-24 01:19:16 +00002876namespace {
John McCall94c3b562010-08-18 09:41:07 +00002877struct AbstractUsageInfo {
2878 Sema &S;
2879 CXXRecordDecl *Record;
2880 CanQualType AbstractType;
2881 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002882
John McCall94c3b562010-08-18 09:41:07 +00002883 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2884 : S(S), Record(Record),
2885 AbstractType(S.Context.getCanonicalType(
2886 S.Context.getTypeDeclType(Record))),
2887 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002888
John McCall94c3b562010-08-18 09:41:07 +00002889 void DiagnoseAbstractType() {
2890 if (Invalid) return;
2891 S.DiagnoseAbstractType(Record);
2892 Invalid = true;
2893 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002894
John McCall94c3b562010-08-18 09:41:07 +00002895 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2896};
2897
2898struct CheckAbstractUsage {
2899 AbstractUsageInfo &Info;
2900 const NamedDecl *Ctx;
2901
2902 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2903 : Info(Info), Ctx(Ctx) {}
2904
2905 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2906 switch (TL.getTypeLocClass()) {
2907#define ABSTRACT_TYPELOC(CLASS, PARENT)
2908#define TYPELOC(CLASS, PARENT) \
2909 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2910#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002911 }
John McCall94c3b562010-08-18 09:41:07 +00002912 }
Mike Stump1eb44332009-09-09 15:08:12 +00002913
John McCall94c3b562010-08-18 09:41:07 +00002914 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2915 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2916 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002917 if (!TL.getArg(I))
2918 continue;
2919
John McCall94c3b562010-08-18 09:41:07 +00002920 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2921 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002922 }
John McCall94c3b562010-08-18 09:41:07 +00002923 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002924
John McCall94c3b562010-08-18 09:41:07 +00002925 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2926 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2927 }
Mike Stump1eb44332009-09-09 15:08:12 +00002928
John McCall94c3b562010-08-18 09:41:07 +00002929 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2930 // Visit the type parameters from a permissive context.
2931 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2932 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2933 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2934 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2935 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2936 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002937 }
John McCall94c3b562010-08-18 09:41:07 +00002938 }
Mike Stump1eb44332009-09-09 15:08:12 +00002939
John McCall94c3b562010-08-18 09:41:07 +00002940 // Visit pointee types from a permissive context.
2941#define CheckPolymorphic(Type) \
2942 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2943 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2944 }
2945 CheckPolymorphic(PointerTypeLoc)
2946 CheckPolymorphic(ReferenceTypeLoc)
2947 CheckPolymorphic(MemberPointerTypeLoc)
2948 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002949
John McCall94c3b562010-08-18 09:41:07 +00002950 /// Handle all the types we haven't given a more specific
2951 /// implementation for above.
2952 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2953 // Every other kind of type that we haven't called out already
2954 // that has an inner type is either (1) sugar or (2) contains that
2955 // inner type in some way as a subobject.
2956 if (TypeLoc Next = TL.getNextTypeLoc())
2957 return Visit(Next, Sel);
2958
2959 // If there's no inner type and we're in a permissive context,
2960 // don't diagnose.
2961 if (Sel == Sema::AbstractNone) return;
2962
2963 // Check whether the type matches the abstract type.
2964 QualType T = TL.getType();
2965 if (T->isArrayType()) {
2966 Sel = Sema::AbstractArrayType;
2967 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002968 }
John McCall94c3b562010-08-18 09:41:07 +00002969 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2970 if (CT != Info.AbstractType) return;
2971
2972 // It matched; do some magic.
2973 if (Sel == Sema::AbstractArrayType) {
2974 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2975 << T << TL.getSourceRange();
2976 } else {
2977 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2978 << Sel << T << TL.getSourceRange();
2979 }
2980 Info.DiagnoseAbstractType();
2981 }
2982};
2983
2984void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2985 Sema::AbstractDiagSelID Sel) {
2986 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2987}
2988
2989}
2990
2991/// Check for invalid uses of an abstract type in a method declaration.
2992static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2993 CXXMethodDecl *MD) {
2994 // No need to do the check on definitions, which require that
2995 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00002996 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00002997 return;
2998
2999 // For safety's sake, just ignore it if we don't have type source
3000 // information. This should never happen for non-implicit methods,
3001 // but...
3002 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3003 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3004}
3005
3006/// Check for invalid uses of an abstract type within a class definition.
3007static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3008 CXXRecordDecl *RD) {
3009 for (CXXRecordDecl::decl_iterator
3010 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3011 Decl *D = *I;
3012 if (D->isImplicit()) continue;
3013
3014 // Methods and method templates.
3015 if (isa<CXXMethodDecl>(D)) {
3016 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3017 } else if (isa<FunctionTemplateDecl>(D)) {
3018 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3019 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3020
3021 // Fields and static variables.
3022 } else if (isa<FieldDecl>(D)) {
3023 FieldDecl *FD = cast<FieldDecl>(D);
3024 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3025 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3026 } else if (isa<VarDecl>(D)) {
3027 VarDecl *VD = cast<VarDecl>(D);
3028 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3029 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3030
3031 // Nested classes and class templates.
3032 } else if (isa<CXXRecordDecl>(D)) {
3033 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3034 } else if (isa<ClassTemplateDecl>(D)) {
3035 CheckAbstractClassUsage(Info,
3036 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3037 }
3038 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003039}
3040
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003041/// \brief Perform semantic checks on a class definition that has been
3042/// completing, introducing implicitly-declared members, checking for
3043/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003044void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003045 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003046 return;
3047
John McCall94c3b562010-08-18 09:41:07 +00003048 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3049 AbstractUsageInfo Info(*this, Record);
3050 CheckAbstractClassUsage(Info, Record);
3051 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003052
3053 // If this is not an aggregate type and has no user-declared constructor,
3054 // complain about any non-static data members of reference or const scalar
3055 // type, since they will never get initializers.
3056 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3057 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3058 bool Complained = false;
3059 for (RecordDecl::field_iterator F = Record->field_begin(),
3060 FEnd = Record->field_end();
3061 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003062 if (F->hasInClassInitializer())
3063 continue;
3064
Douglas Gregor325e5932010-04-15 00:00:53 +00003065 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003066 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003067 if (!Complained) {
3068 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3069 << Record->getTagKind() << Record;
3070 Complained = true;
3071 }
3072
3073 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3074 << F->getType()->isReferenceType()
3075 << F->getDeclName();
3076 }
3077 }
3078 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003079
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003080 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003081 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003082
3083 if (Record->getIdentifier()) {
3084 // C++ [class.mem]p13:
3085 // If T is the name of a class, then each of the following shall have a
3086 // name different from T:
3087 // - every member of every anonymous union that is a member of class T.
3088 //
3089 // C++ [class.mem]p14:
3090 // In addition, if class T has a user-declared constructor (12.1), every
3091 // non-static data member of class T shall have a name different from T.
3092 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003093 R.first != R.second; ++R.first) {
3094 NamedDecl *D = *R.first;
3095 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3096 isa<IndirectFieldDecl>(D)) {
3097 Diag(D->getLocation(), diag::err_member_name_of_class)
3098 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003099 break;
3100 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003101 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003102 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003103
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003104 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003105 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003106 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003107 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003108 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3109 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3110 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003111
3112 // See if a method overloads virtual methods in a base
3113 /// class without overriding any.
3114 if (!Record->isDependentType()) {
3115 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3116 MEnd = Record->method_end();
3117 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003118 if (!(*M)->isStatic())
3119 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003120 }
3121 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003122
3123 // Declare inherited constructors. We do this eagerly here because:
3124 // - The standard requires an eager diagnostic for conflicting inherited
3125 // constructors from different classes.
3126 // - The lazy declaration of the other implicit constructors is so as to not
3127 // waste space and performance on classes that are not meant to be
3128 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3129 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003130 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003131
Sean Hunteb88ae52011-05-23 21:07:59 +00003132 if (!Record->isDependentType())
3133 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003134}
3135
3136void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003137 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3138 ME = Record->method_end();
3139 MI != ME; ++MI) {
3140 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3141 switch (getSpecialMember(*MI)) {
3142 case CXXDefaultConstructor:
3143 CheckExplicitlyDefaultedDefaultConstructor(
3144 cast<CXXConstructorDecl>(*MI));
3145 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003146
Sean Huntcb45a0f2011-05-12 22:46:25 +00003147 case CXXDestructor:
3148 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3149 break;
3150
3151 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003152 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3153 break;
3154
Sean Huntcb45a0f2011-05-12 22:46:25 +00003155 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003156 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003157 break;
3158
Sean Hunt82713172011-05-25 23:16:36 +00003159 case CXXMoveConstructor:
3160 case CXXMoveAssignment:
3161 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3162 break;
3163
Sean Huntcb45a0f2011-05-12 22:46:25 +00003164 default:
Sean Hunt2b188082011-05-14 05:23:28 +00003165 // FIXME: Do moves once they exist
Sean Huntcb45a0f2011-05-12 22:46:25 +00003166 llvm_unreachable("non-special member explicitly defaulted!");
3167 }
Sean Hunt001cad92011-05-10 00:49:42 +00003168 }
3169 }
3170
Sean Hunt001cad92011-05-10 00:49:42 +00003171}
3172
3173void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3174 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3175
3176 // Whether this was the first-declared instance of the constructor.
3177 // This affects whether we implicitly add an exception spec (and, eventually,
3178 // constexpr). It is also ill-formed to explicitly default a constructor such
3179 // that it would be deleted. (C++0x [decl.fct.def.default])
3180 bool First = CD == CD->getCanonicalDecl();
3181
Sean Hunt49634cf2011-05-13 06:10:58 +00003182 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003183 if (CD->getNumParams() != 0) {
3184 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3185 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003186 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003187 }
3188
3189 ImplicitExceptionSpecification Spec
3190 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3191 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003192 if (EPI.ExceptionSpecType == EST_Delayed) {
3193 // Exception specification depends on some deferred part of the class. We'll
3194 // try again when the class's definition has been fully processed.
3195 return;
3196 }
Sean Hunt001cad92011-05-10 00:49:42 +00003197 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3198 *ExceptionType = Context.getFunctionType(
3199 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3200
3201 if (CtorType->hasExceptionSpec()) {
3202 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003203 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003204 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003205 PDiag(),
3206 ExceptionType, SourceLocation(),
3207 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003208 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003209 }
3210 } else if (First) {
3211 // We set the declaration to have the computed exception spec here.
3212 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003213 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003214 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3215 }
Sean Huntca46d132011-05-12 03:51:48 +00003216
Sean Hunt49634cf2011-05-13 06:10:58 +00003217 if (HadError) {
3218 CD->setInvalidDecl();
3219 return;
3220 }
3221
Sean Huntca46d132011-05-12 03:51:48 +00003222 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003223 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003224 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003225 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003226 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003227 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003228 CD->setInvalidDecl();
3229 }
3230 }
3231}
3232
3233void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3234 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3235
3236 // Whether this was the first-declared instance of the constructor.
3237 bool First = CD == CD->getCanonicalDecl();
3238
3239 bool HadError = false;
3240 if (CD->getNumParams() != 1) {
3241 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3242 << CD->getSourceRange();
3243 HadError = true;
3244 }
3245
3246 ImplicitExceptionSpecification Spec(Context);
3247 bool Const;
3248 llvm::tie(Spec, Const) =
3249 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3250
3251 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3252 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3253 *ExceptionType = Context.getFunctionType(
3254 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3255
3256 // Check for parameter type matching.
3257 // This is a copy ctor so we know it's a cv-qualified reference to T.
3258 QualType ArgType = CtorType->getArgType(0);
3259 if (ArgType->getPointeeType().isVolatileQualified()) {
3260 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3261 HadError = true;
3262 }
3263 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3264 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3265 HadError = true;
3266 }
3267
3268 if (CtorType->hasExceptionSpec()) {
3269 if (CheckEquivalentExceptionSpec(
3270 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003271 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003272 PDiag(),
3273 ExceptionType, SourceLocation(),
3274 CtorType, CD->getLocation())) {
3275 HadError = true;
3276 }
3277 } else if (First) {
3278 // We set the declaration to have the computed exception spec here.
3279 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003280 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003281 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3282 }
3283
3284 if (HadError) {
3285 CD->setInvalidDecl();
3286 return;
3287 }
3288
3289 if (ShouldDeleteCopyConstructor(CD)) {
3290 if (First) {
3291 CD->setDeletedAsWritten();
3292 } else {
3293 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003294 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003295 CD->setInvalidDecl();
3296 }
Sean Huntca46d132011-05-12 03:51:48 +00003297 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003298}
Sean Hunt001cad92011-05-10 00:49:42 +00003299
Sean Hunt2b188082011-05-14 05:23:28 +00003300void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3301 assert(MD->isExplicitlyDefaulted());
3302
3303 // Whether this was the first-declared instance of the operator
3304 bool First = MD == MD->getCanonicalDecl();
3305
3306 bool HadError = false;
3307 if (MD->getNumParams() != 1) {
3308 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3309 << MD->getSourceRange();
3310 HadError = true;
3311 }
3312
3313 QualType ReturnType =
3314 MD->getType()->getAs<FunctionType>()->getResultType();
3315 if (!ReturnType->isLValueReferenceType() ||
3316 !Context.hasSameType(
3317 Context.getCanonicalType(ReturnType->getPointeeType()),
3318 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3319 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3320 HadError = true;
3321 }
3322
3323 ImplicitExceptionSpecification Spec(Context);
3324 bool Const;
3325 llvm::tie(Spec, Const) =
3326 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3327
3328 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3329 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3330 *ExceptionType = Context.getFunctionType(
3331 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3332
Sean Hunt2b188082011-05-14 05:23:28 +00003333 QualType ArgType = OperType->getArgType(0);
Sean Huntbe631222011-05-17 20:44:43 +00003334 if (!ArgType->isReferenceType()) {
3335 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003336 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003337 } else {
3338 if (ArgType->getPointeeType().isVolatileQualified()) {
3339 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3340 HadError = true;
3341 }
3342 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3343 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3344 HadError = true;
3345 }
Sean Hunt2b188082011-05-14 05:23:28 +00003346 }
Sean Huntbe631222011-05-17 20:44:43 +00003347
Sean Hunt2b188082011-05-14 05:23:28 +00003348 if (OperType->getTypeQuals()) {
3349 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3350 HadError = true;
3351 }
3352
3353 if (OperType->hasExceptionSpec()) {
3354 if (CheckEquivalentExceptionSpec(
3355 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003356 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003357 PDiag(),
3358 ExceptionType, SourceLocation(),
3359 OperType, MD->getLocation())) {
3360 HadError = true;
3361 }
3362 } else if (First) {
3363 // We set the declaration to have the computed exception spec here.
3364 // We duplicate the one parameter type.
3365 EPI.RefQualifier = OperType->getRefQualifier();
3366 EPI.ExtInfo = OperType->getExtInfo();
3367 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3368 }
3369
3370 if (HadError) {
3371 MD->setInvalidDecl();
3372 return;
3373 }
3374
3375 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3376 if (First) {
3377 MD->setDeletedAsWritten();
3378 } else {
3379 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003380 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003381 MD->setInvalidDecl();
3382 }
3383 }
3384}
3385
Sean Huntcb45a0f2011-05-12 22:46:25 +00003386void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3387 assert(DD->isExplicitlyDefaulted());
3388
3389 // Whether this was the first-declared instance of the destructor.
3390 bool First = DD == DD->getCanonicalDecl();
3391
3392 ImplicitExceptionSpecification Spec
3393 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3394 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3395 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3396 *ExceptionType = Context.getFunctionType(
3397 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3398
3399 if (DtorType->hasExceptionSpec()) {
3400 if (CheckEquivalentExceptionSpec(
3401 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003402 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003403 PDiag(),
3404 ExceptionType, SourceLocation(),
3405 DtorType, DD->getLocation())) {
3406 DD->setInvalidDecl();
3407 return;
3408 }
3409 } else if (First) {
3410 // We set the declaration to have the computed exception spec here.
3411 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003412 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003413 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3414 }
3415
3416 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003417 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003418 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003419 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003420 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003421 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003422 DD->setInvalidDecl();
3423 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003424 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003425}
3426
Sean Huntcdee3fe2011-05-11 22:34:38 +00003427bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3428 CXXRecordDecl *RD = CD->getParent();
3429 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003430 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003431 return false;
3432
Sean Hunt71a682f2011-05-18 03:41:58 +00003433 SourceLocation Loc = CD->getLocation();
3434
Sean Huntcdee3fe2011-05-11 22:34:38 +00003435 // Do access control from the constructor
3436 ContextRAII CtorContext(*this, CD);
3437
3438 bool Union = RD->isUnion();
3439 bool AllConst = true;
3440
Sean Huntcdee3fe2011-05-11 22:34:38 +00003441 // We do this because we should never actually use an anonymous
3442 // union's constructor.
3443 if (Union && RD->isAnonymousStructOrUnion())
3444 return false;
3445
3446 // FIXME: We should put some diagnostic logic right into this function.
3447
3448 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003449 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003450
3451 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3452 BE = RD->bases_end();
3453 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003454 // We'll handle this one later
3455 if (BI->isVirtual())
3456 continue;
3457
Sean Huntcdee3fe2011-05-11 22:34:38 +00003458 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3459 assert(BaseDecl && "base isn't a CXXRecordDecl");
3460
3461 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003462 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003463 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3464 if (BaseDtor->isDeleted())
3465 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003466 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003467 AR_accessible)
3468 return true;
3469
Sean Huntcdee3fe2011-05-11 22:34:38 +00003470 // -- any [direct base class either] has no default constructor or
3471 // overload resolution as applied to [its] default constructor
3472 // results in an ambiguity or in a function that is deleted or
3473 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003474 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3475 if (!BaseDefault || BaseDefault->isDeleted())
3476 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003477
Sean Huntb320e0c2011-06-10 03:50:41 +00003478 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3479 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003480 return true;
3481 }
3482
3483 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3484 BE = RD->vbases_end();
3485 BI != BE; ++BI) {
3486 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3487 assert(BaseDecl && "base isn't a CXXRecordDecl");
3488
3489 // -- any [virtual base class] has a type with a destructor that is
3490 // delete or inaccessible from the defaulted default constructor
3491 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3492 if (BaseDtor->isDeleted())
3493 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003494 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003495 AR_accessible)
3496 return true;
3497
3498 // -- any [virtual base class either] has no default constructor or
3499 // overload resolution as applied to [its] default constructor
3500 // results in an ambiguity or in a function that is deleted or
3501 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003502 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3503 if (!BaseDefault || BaseDefault->isDeleted())
3504 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003505
Sean Huntb320e0c2011-06-10 03:50:41 +00003506 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3507 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003508 return true;
3509 }
3510
3511 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3512 FE = RD->field_end();
3513 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003514 if (FI->isInvalidDecl())
3515 continue;
3516
Sean Huntcdee3fe2011-05-11 22:34:38 +00003517 QualType FieldType = Context.getBaseElementType(FI->getType());
3518 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003519
Sean Huntcdee3fe2011-05-11 22:34:38 +00003520 // -- any non-static data member with no brace-or-equal-initializer is of
3521 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003522 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003523 return true;
3524
3525 // -- X is a union and all its variant members are of const-qualified type
3526 // (or array thereof)
3527 if (Union && !FieldType.isConstQualified())
3528 AllConst = false;
3529
3530 if (FieldRecord) {
3531 // -- X is a union-like class that has a variant member with a non-trivial
3532 // default constructor
3533 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3534 return true;
3535
3536 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3537 if (FieldDtor->isDeleted())
3538 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003539 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003540 AR_accessible)
3541 return true;
3542
3543 // -- any non-variant non-static data member of const-qualified type (or
3544 // array thereof) with no brace-or-equal-initializer does not have a
3545 // user-provided default constructor
3546 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003547 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003548 !FieldRecord->hasUserProvidedDefaultConstructor())
3549 return true;
3550
3551 if (!Union && FieldRecord->isUnion() &&
3552 FieldRecord->isAnonymousStructOrUnion()) {
3553 // We're okay to reuse AllConst here since we only care about the
3554 // value otherwise if we're in a union.
3555 AllConst = true;
3556
3557 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3558 UE = FieldRecord->field_end();
3559 UI != UE; ++UI) {
3560 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3561 CXXRecordDecl *UnionFieldRecord =
3562 UnionFieldType->getAsCXXRecordDecl();
3563
3564 if (!UnionFieldType.isConstQualified())
3565 AllConst = false;
3566
3567 if (UnionFieldRecord &&
3568 !UnionFieldRecord->hasTrivialDefaultConstructor())
3569 return true;
3570 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003571
Sean Huntcdee3fe2011-05-11 22:34:38 +00003572 if (AllConst)
3573 return true;
3574
3575 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003576 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003577 continue;
3578 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003579
Richard Smith7a614d82011-06-11 17:19:42 +00003580 // -- any non-static data member with no brace-or-equal-initializer has
3581 // class type M (or array thereof) and either M has no default
3582 // constructor or overload resolution as applied to M's default
3583 // constructor results in an ambiguity or in a function that is deleted
3584 // or inaccessible from the defaulted default constructor.
3585 if (!FI->hasInClassInitializer()) {
3586 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3587 if (!FieldDefault || FieldDefault->isDeleted())
3588 return true;
3589 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3590 PDiag()) != AR_accessible)
3591 return true;
3592 }
3593 } else if (!Union && FieldType.isConstQualified() &&
3594 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003595 // -- any non-variant non-static data member of const-qualified type (or
3596 // array thereof) with no brace-or-equal-initializer does not have a
3597 // user-provided default constructor
3598 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003599 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003600 }
3601
3602 if (Union && AllConst)
3603 return true;
3604
3605 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003606}
3607
Sean Hunt49634cf2011-05-13 06:10:58 +00003608bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003609 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003610 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003611 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003612 return false;
3613
Sean Hunt71a682f2011-05-18 03:41:58 +00003614 SourceLocation Loc = CD->getLocation();
3615
Sean Hunt49634cf2011-05-13 06:10:58 +00003616 // Do access control from the constructor
3617 ContextRAII CtorContext(*this, CD);
3618
Sean Huntc530d172011-06-10 04:44:37 +00003619 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003620
Sean Hunt2b188082011-05-14 05:23:28 +00003621 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3622 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003623 unsigned ArgQuals =
3624 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3625 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003626
3627 // We do this because we should never actually use an anonymous
3628 // union's constructor.
3629 if (Union && RD->isAnonymousStructOrUnion())
3630 return false;
3631
3632 // FIXME: We should put some diagnostic logic right into this function.
3633
3634 // C++0x [class.copy]/11
3635 // A defaulted [copy] constructor for class X is defined as delete if X has:
3636
3637 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3638 BE = RD->bases_end();
3639 BI != BE; ++BI) {
3640 // We'll handle this one later
3641 if (BI->isVirtual())
3642 continue;
3643
3644 QualType BaseType = BI->getType();
3645 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3646 assert(BaseDecl && "base isn't a CXXRecordDecl");
3647
3648 // -- any [direct base class] of a type with a destructor that is deleted or
3649 // inaccessible from the defaulted constructor
3650 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3651 if (BaseDtor->isDeleted())
3652 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003653 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003654 AR_accessible)
3655 return true;
3656
3657 // -- a [direct base class] B that cannot be [copied] because overload
3658 // resolution, as applied to B's [copy] constructor, results in an
3659 // ambiguity or a function that is deleted or inaccessible from the
3660 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003661 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003662 if (!BaseCtor || BaseCtor->isDeleted())
3663 return true;
3664 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3665 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003666 return true;
3667 }
3668
3669 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3670 BE = RD->vbases_end();
3671 BI != BE; ++BI) {
3672 QualType BaseType = BI->getType();
3673 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3674 assert(BaseDecl && "base isn't a CXXRecordDecl");
3675
Sean Huntb320e0c2011-06-10 03:50:41 +00003676 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003677 // inaccessible from the defaulted constructor
3678 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3679 if (BaseDtor->isDeleted())
3680 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003681 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003682 AR_accessible)
3683 return true;
3684
3685 // -- a [virtual base class] B that cannot be [copied] because overload
3686 // resolution, as applied to B's [copy] constructor, results in an
3687 // ambiguity or a function that is deleted or inaccessible from the
3688 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003689 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003690 if (!BaseCtor || BaseCtor->isDeleted())
3691 return true;
3692 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3693 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003694 return true;
3695 }
3696
3697 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3698 FE = RD->field_end();
3699 FI != FE; ++FI) {
3700 QualType FieldType = Context.getBaseElementType(FI->getType());
3701
3702 // -- for a copy constructor, a non-static data member of rvalue reference
3703 // type
3704 if (FieldType->isRValueReferenceType())
3705 return true;
3706
3707 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3708
3709 if (FieldRecord) {
3710 // This is an anonymous union
3711 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3712 // Anonymous unions inside unions do not variant members create
3713 if (!Union) {
3714 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3715 UE = FieldRecord->field_end();
3716 UI != UE; ++UI) {
3717 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3718 CXXRecordDecl *UnionFieldRecord =
3719 UnionFieldType->getAsCXXRecordDecl();
3720
3721 // -- a variant member with a non-trivial [copy] constructor and X
3722 // is a union-like class
3723 if (UnionFieldRecord &&
3724 !UnionFieldRecord->hasTrivialCopyConstructor())
3725 return true;
3726 }
3727 }
3728
3729 // Don't try to initalize an anonymous union
3730 continue;
3731 } else {
3732 // -- a variant member with a non-trivial [copy] constructor and X is a
3733 // union-like class
3734 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3735 return true;
3736
3737 // -- any [non-static data member] of a type with a destructor that is
3738 // deleted or inaccessible from the defaulted constructor
3739 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3740 if (FieldDtor->isDeleted())
3741 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003742 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003743 AR_accessible)
3744 return true;
3745 }
Sean Huntc530d172011-06-10 04:44:37 +00003746
3747 // -- a [non-static data member of class type (or array thereof)] B that
3748 // cannot be [copied] because overload resolution, as applied to B's
3749 // [copy] constructor, results in an ambiguity or a function that is
3750 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003751 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3752 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003753 if (!FieldCtor || FieldCtor->isDeleted())
3754 return true;
3755 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3756 PDiag()) != AR_accessible)
3757 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00003758 }
Sean Hunt49634cf2011-05-13 06:10:58 +00003759 }
3760
3761 return false;
3762}
3763
Sean Hunt7f410192011-05-14 05:23:24 +00003764bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3765 CXXRecordDecl *RD = MD->getParent();
3766 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003767 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00003768 return false;
3769
Sean Hunt71a682f2011-05-18 03:41:58 +00003770 SourceLocation Loc = MD->getLocation();
3771
Sean Hunt7f410192011-05-14 05:23:24 +00003772 // Do access control from the constructor
3773 ContextRAII MethodContext(*this, MD);
3774
3775 bool Union = RD->isUnion();
3776
Sean Hunt661c67a2011-06-21 23:42:56 +00003777 unsigned ArgQuals =
3778 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3779 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00003780
3781 // We do this because we should never actually use an anonymous
3782 // union's constructor.
3783 if (Union && RD->isAnonymousStructOrUnion())
3784 return false;
3785
Sean Hunt7f410192011-05-14 05:23:24 +00003786 // FIXME: We should put some diagnostic logic right into this function.
3787
3788 // C++0x [class.copy]/11
3789 // A defaulted [copy] assignment operator for class X is defined as deleted
3790 // if X has:
3791
3792 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3793 BE = RD->bases_end();
3794 BI != BE; ++BI) {
3795 // We'll handle this one later
3796 if (BI->isVirtual())
3797 continue;
3798
3799 QualType BaseType = BI->getType();
3800 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3801 assert(BaseDecl && "base isn't a CXXRecordDecl");
3802
3803 // -- a [direct base class] B that cannot be [copied] because overload
3804 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00003805 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00003806 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00003807 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3808 0);
3809 if (!CopyOper || CopyOper->isDeleted())
3810 return true;
3811 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00003812 return true;
3813 }
3814
3815 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3816 BE = RD->vbases_end();
3817 BI != BE; ++BI) {
3818 QualType BaseType = BI->getType();
3819 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3820 assert(BaseDecl && "base isn't a CXXRecordDecl");
3821
Sean Hunt7f410192011-05-14 05:23:24 +00003822 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00003823 // resolution, as applied to B's [copy] assignment operator, results in
3824 // an ambiguity or a function that is deleted or inaccessible from the
3825 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00003826 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3827 0);
3828 if (!CopyOper || CopyOper->isDeleted())
3829 return true;
3830 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00003831 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00003832 }
3833
3834 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3835 FE = RD->field_end();
3836 FI != FE; ++FI) {
3837 QualType FieldType = Context.getBaseElementType(FI->getType());
3838
3839 // -- a non-static data member of reference type
3840 if (FieldType->isReferenceType())
3841 return true;
3842
3843 // -- a non-static data member of const non-class type (or array thereof)
3844 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3845 return true;
3846
3847 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3848
3849 if (FieldRecord) {
3850 // This is an anonymous union
3851 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3852 // Anonymous unions inside unions do not variant members create
3853 if (!Union) {
3854 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3855 UE = FieldRecord->field_end();
3856 UI != UE; ++UI) {
3857 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3858 CXXRecordDecl *UnionFieldRecord =
3859 UnionFieldType->getAsCXXRecordDecl();
3860
3861 // -- a variant member with a non-trivial [copy] assignment operator
3862 // and X is a union-like class
3863 if (UnionFieldRecord &&
3864 !UnionFieldRecord->hasTrivialCopyAssignment())
3865 return true;
3866 }
3867 }
3868
3869 // Don't try to initalize an anonymous union
3870 continue;
3871 // -- a variant member with a non-trivial [copy] assignment operator
3872 // and X is a union-like class
3873 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3874 return true;
3875 }
Sean Hunt7f410192011-05-14 05:23:24 +00003876
Sean Hunt661c67a2011-06-21 23:42:56 +00003877 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
3878 false, 0);
3879 if (!CopyOper || CopyOper->isDeleted())
3880 return false;
3881 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3882 return false;
Sean Hunt2b188082011-05-14 05:23:28 +00003883 }
Sean Hunt7f410192011-05-14 05:23:24 +00003884 }
3885
3886 return false;
3887}
3888
Sean Huntcb45a0f2011-05-12 22:46:25 +00003889bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3890 CXXRecordDecl *RD = DD->getParent();
3891 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003892 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00003893 return false;
3894
Sean Hunt71a682f2011-05-18 03:41:58 +00003895 SourceLocation Loc = DD->getLocation();
3896
Sean Huntcb45a0f2011-05-12 22:46:25 +00003897 // Do access control from the destructor
3898 ContextRAII CtorContext(*this, DD);
3899
3900 bool Union = RD->isUnion();
3901
Sean Hunt49634cf2011-05-13 06:10:58 +00003902 // We do this because we should never actually use an anonymous
3903 // union's destructor.
3904 if (Union && RD->isAnonymousStructOrUnion())
3905 return false;
3906
Sean Huntcb45a0f2011-05-12 22:46:25 +00003907 // C++0x [class.dtor]p5
3908 // A defaulted destructor for a class X is defined as deleted if:
3909 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3910 BE = RD->bases_end();
3911 BI != BE; ++BI) {
3912 // We'll handle this one later
3913 if (BI->isVirtual())
3914 continue;
3915
3916 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3917 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3918 assert(BaseDtor && "base has no destructor");
3919
3920 // -- any direct or virtual base class has a deleted destructor or
3921 // a destructor that is inaccessible from the defaulted destructor
3922 if (BaseDtor->isDeleted())
3923 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003924 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003925 AR_accessible)
3926 return true;
3927 }
3928
3929 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3930 BE = RD->vbases_end();
3931 BI != BE; ++BI) {
3932 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3933 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3934 assert(BaseDtor && "base has no destructor");
3935
3936 // -- any direct or virtual base class has a deleted destructor or
3937 // a destructor that is inaccessible from the defaulted destructor
3938 if (BaseDtor->isDeleted())
3939 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003940 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003941 AR_accessible)
3942 return true;
3943 }
3944
3945 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3946 FE = RD->field_end();
3947 FI != FE; ++FI) {
3948 QualType FieldType = Context.getBaseElementType(FI->getType());
3949 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3950 if (FieldRecord) {
3951 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3952 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3953 UE = FieldRecord->field_end();
3954 UI != UE; ++UI) {
3955 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3956 CXXRecordDecl *UnionFieldRecord =
3957 UnionFieldType->getAsCXXRecordDecl();
3958
3959 // -- X is a union-like class that has a variant member with a non-
3960 // trivial destructor.
3961 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3962 return true;
3963 }
3964 // Technically we are supposed to do this next check unconditionally.
3965 // But that makes absolutely no sense.
3966 } else {
3967 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3968
3969 // -- any of the non-static data members has class type M (or array
3970 // thereof) and M has a deleted destructor or a destructor that is
3971 // inaccessible from the defaulted destructor
3972 if (FieldDtor->isDeleted())
3973 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003974 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003975 AR_accessible)
3976 return true;
3977
3978 // -- X is a union-like class that has a variant member with a non-
3979 // trivial destructor.
3980 if (Union && !FieldDtor->isTrivial())
3981 return true;
3982 }
3983 }
3984 }
3985
3986 if (DD->isVirtual()) {
3987 FunctionDecl *OperatorDelete = 0;
3988 DeclarationName Name =
3989 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00003990 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003991 false))
3992 return true;
3993 }
3994
3995
3996 return false;
3997}
3998
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003999/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004000namespace {
4001 struct FindHiddenVirtualMethodData {
4002 Sema *S;
4003 CXXMethodDecl *Method;
4004 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004005 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004006 };
4007}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004008
4009/// \brief Member lookup function that determines whether a given C++
4010/// method overloads virtual methods in a base class without overriding any,
4011/// to be used with CXXRecordDecl::lookupInBases().
4012static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4013 CXXBasePath &Path,
4014 void *UserData) {
4015 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4016
4017 FindHiddenVirtualMethodData &Data
4018 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4019
4020 DeclarationName Name = Data.Method->getDeclName();
4021 assert(Name.getNameKind() == DeclarationName::Identifier);
4022
4023 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004024 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004025 for (Path.Decls = BaseRecord->lookup(Name);
4026 Path.Decls.first != Path.Decls.second;
4027 ++Path.Decls.first) {
4028 NamedDecl *D = *Path.Decls.first;
4029 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004030 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004031 foundSameNameMethod = true;
4032 // Interested only in hidden virtual methods.
4033 if (!MD->isVirtual())
4034 continue;
4035 // If the method we are checking overrides a method from its base
4036 // don't warn about the other overloaded methods.
4037 if (!Data.S->IsOverload(Data.Method, MD, false))
4038 return true;
4039 // Collect the overload only if its hidden.
4040 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4041 overloadedMethods.push_back(MD);
4042 }
4043 }
4044
4045 if (foundSameNameMethod)
4046 Data.OverloadedMethods.append(overloadedMethods.begin(),
4047 overloadedMethods.end());
4048 return foundSameNameMethod;
4049}
4050
4051/// \brief See if a method overloads virtual methods in a base class without
4052/// overriding any.
4053void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4054 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4055 MD->getLocation()) == Diagnostic::Ignored)
4056 return;
4057 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4058 return;
4059
4060 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4061 /*bool RecordPaths=*/false,
4062 /*bool DetectVirtual=*/false);
4063 FindHiddenVirtualMethodData Data;
4064 Data.Method = MD;
4065 Data.S = this;
4066
4067 // Keep the base methods that were overriden or introduced in the subclass
4068 // by 'using' in a set. A base method not in this set is hidden.
4069 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4070 res.first != res.second; ++res.first) {
4071 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4072 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4073 E = MD->end_overridden_methods();
4074 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004075 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004076 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4077 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004078 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004079 }
4080
4081 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4082 !Data.OverloadedMethods.empty()) {
4083 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4084 << MD << (Data.OverloadedMethods.size() > 1);
4085
4086 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4087 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4088 Diag(overloadedMD->getLocation(),
4089 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4090 }
4091 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004092}
4093
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004094void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004095 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004096 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004097 SourceLocation RBrac,
4098 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004099 if (!TagDecl)
4100 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004101
Douglas Gregor42af25f2009-05-11 19:58:34 +00004102 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004103
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004104 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004105 // strict aliasing violation!
4106 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004107 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004108
Douglas Gregor23c94db2010-07-02 17:43:08 +00004109 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004110 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004111}
4112
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004113/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4114/// special functions, such as the default constructor, copy
4115/// constructor, or destructor, to the given C++ class (C++
4116/// [special]p1). This routine can only be executed just before the
4117/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004118void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004119 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004120 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004121
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004122 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004123 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004124
Douglas Gregora376d102010-07-02 21:50:04 +00004125 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4126 ++ASTContext::NumImplicitCopyAssignmentOperators;
4127
4128 // If we have a dynamic class, then the copy assignment operator may be
4129 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4130 // it shows up in the right place in the vtable and that we diagnose
4131 // problems with the implicit exception specification.
4132 if (ClassDecl->isDynamicClass())
4133 DeclareImplicitCopyAssignment(ClassDecl);
4134 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004135
Douglas Gregor4923aa22010-07-02 20:37:36 +00004136 if (!ClassDecl->hasUserDeclaredDestructor()) {
4137 ++ASTContext::NumImplicitDestructors;
4138
4139 // If we have a dynamic class, then the destructor may be virtual, so we
4140 // have to declare the destructor immediately. This ensures that, e.g., it
4141 // shows up in the right place in the vtable and that we diagnose problems
4142 // with the implicit exception specification.
4143 if (ClassDecl->isDynamicClass())
4144 DeclareImplicitDestructor(ClassDecl);
4145 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004146}
4147
Francois Pichet8387e2a2011-04-22 22:18:13 +00004148void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4149 if (!D)
4150 return;
4151
4152 int NumParamList = D->getNumTemplateParameterLists();
4153 for (int i = 0; i < NumParamList; i++) {
4154 TemplateParameterList* Params = D->getTemplateParameterList(i);
4155 for (TemplateParameterList::iterator Param = Params->begin(),
4156 ParamEnd = Params->end();
4157 Param != ParamEnd; ++Param) {
4158 NamedDecl *Named = cast<NamedDecl>(*Param);
4159 if (Named->getDeclName()) {
4160 S->AddDecl(Named);
4161 IdResolver.AddDecl(Named);
4162 }
4163 }
4164 }
4165}
4166
John McCalld226f652010-08-21 09:40:31 +00004167void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004168 if (!D)
4169 return;
4170
4171 TemplateParameterList *Params = 0;
4172 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4173 Params = Template->getTemplateParameters();
4174 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4175 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4176 Params = PartialSpec->getTemplateParameters();
4177 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004178 return;
4179
Douglas Gregor6569d682009-05-27 23:11:45 +00004180 for (TemplateParameterList::iterator Param = Params->begin(),
4181 ParamEnd = Params->end();
4182 Param != ParamEnd; ++Param) {
4183 NamedDecl *Named = cast<NamedDecl>(*Param);
4184 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004185 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004186 IdResolver.AddDecl(Named);
4187 }
4188 }
4189}
4190
John McCalld226f652010-08-21 09:40:31 +00004191void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004192 if (!RecordD) return;
4193 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004194 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004195 PushDeclContext(S, Record);
4196}
4197
John McCalld226f652010-08-21 09:40:31 +00004198void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004199 if (!RecordD) return;
4200 PopDeclContext();
4201}
4202
Douglas Gregor72b505b2008-12-16 21:30:33 +00004203/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4204/// parsing a top-level (non-nested) C++ class, and we are now
4205/// parsing those parts of the given Method declaration that could
4206/// not be parsed earlier (C++ [class.mem]p2), such as default
4207/// arguments. This action should enter the scope of the given
4208/// Method declaration as if we had just parsed the qualified method
4209/// name. However, it should not bring the parameters into scope;
4210/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004211void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004212}
4213
4214/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4215/// C++ method declaration. We're (re-)introducing the given
4216/// function parameter into scope for use in parsing later parts of
4217/// the method declaration. For example, we could see an
4218/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004219void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004220 if (!ParamD)
4221 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004222
John McCalld226f652010-08-21 09:40:31 +00004223 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004224
4225 // If this parameter has an unparsed default argument, clear it out
4226 // to make way for the parsed default argument.
4227 if (Param->hasUnparsedDefaultArg())
4228 Param->setDefaultArg(0);
4229
John McCalld226f652010-08-21 09:40:31 +00004230 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004231 if (Param->getDeclName())
4232 IdResolver.AddDecl(Param);
4233}
4234
4235/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4236/// processing the delayed method declaration for Method. The method
4237/// declaration is now considered finished. There may be a separate
4238/// ActOnStartOfFunctionDef action later (not necessarily
4239/// immediately!) for this method, if it was also defined inside the
4240/// class body.
John McCalld226f652010-08-21 09:40:31 +00004241void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004242 if (!MethodD)
4243 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004244
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004245 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004246
John McCalld226f652010-08-21 09:40:31 +00004247 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004248
4249 // Now that we have our default arguments, check the constructor
4250 // again. It could produce additional diagnostics or affect whether
4251 // the class has implicitly-declared destructors, among other
4252 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004253 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4254 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004255
4256 // Check the default arguments, which we may have added.
4257 if (!Method->isInvalidDecl())
4258 CheckCXXDefaultArguments(Method);
4259}
4260
Douglas Gregor42a552f2008-11-05 20:51:48 +00004261/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004262/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004263/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004264/// emit diagnostics and set the invalid bit to true. In any case, the type
4265/// will be updated to reflect a well-formed type for the constructor and
4266/// returned.
4267QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004268 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004269 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004270
4271 // C++ [class.ctor]p3:
4272 // A constructor shall not be virtual (10.3) or static (9.4). A
4273 // constructor can be invoked for a const, volatile or const
4274 // volatile object. A constructor shall not be declared const,
4275 // volatile, or const volatile (9.3.2).
4276 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004277 if (!D.isInvalidType())
4278 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4279 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4280 << SourceRange(D.getIdentifierLoc());
4281 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004282 }
John McCalld931b082010-08-26 03:08:43 +00004283 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004284 if (!D.isInvalidType())
4285 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4286 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4287 << SourceRange(D.getIdentifierLoc());
4288 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004289 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004290 }
Mike Stump1eb44332009-09-09 15:08:12 +00004291
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004292 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004293 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004294 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004295 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4296 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004297 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004298 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4299 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004300 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004301 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4302 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004303 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004304 }
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Douglas Gregorc938c162011-01-26 05:01:58 +00004306 // C++0x [class.ctor]p4:
4307 // A constructor shall not be declared with a ref-qualifier.
4308 if (FTI.hasRefQualifier()) {
4309 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4310 << FTI.RefQualifierIsLValueRef
4311 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4312 D.setInvalidType();
4313 }
4314
Douglas Gregor42a552f2008-11-05 20:51:48 +00004315 // Rebuild the function type "R" without any type qualifiers (in
4316 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004317 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004318 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004319 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4320 return R;
4321
4322 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4323 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004324 EPI.RefQualifier = RQ_None;
4325
Chris Lattner65401802009-04-25 08:28:21 +00004326 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004327 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004328}
4329
Douglas Gregor72b505b2008-12-16 21:30:33 +00004330/// CheckConstructor - Checks a fully-formed constructor for
4331/// well-formedness, issuing any diagnostics required. Returns true if
4332/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004333void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004334 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004335 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4336 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004337 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004338
4339 // C++ [class.copy]p3:
4340 // A declaration of a constructor for a class X is ill-formed if
4341 // its first parameter is of type (optionally cv-qualified) X and
4342 // either there are no other parameters or else all other
4343 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004344 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004345 ((Constructor->getNumParams() == 1) ||
4346 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004347 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4348 Constructor->getTemplateSpecializationKind()
4349 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004350 QualType ParamType = Constructor->getParamDecl(0)->getType();
4351 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4352 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004353 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004354 const char *ConstRef
4355 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4356 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004357 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004358 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004359
4360 // FIXME: Rather that making the constructor invalid, we should endeavor
4361 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004362 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004363 }
4364 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004365}
4366
John McCall15442822010-08-04 01:04:25 +00004367/// CheckDestructor - Checks a fully-formed destructor definition for
4368/// well-formedness, issuing any diagnostics required. Returns true
4369/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004370bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004371 CXXRecordDecl *RD = Destructor->getParent();
4372
4373 if (Destructor->isVirtual()) {
4374 SourceLocation Loc;
4375
4376 if (!Destructor->isImplicit())
4377 Loc = Destructor->getLocation();
4378 else
4379 Loc = RD->getLocation();
4380
4381 // If we have a virtual destructor, look up the deallocation function
4382 FunctionDecl *OperatorDelete = 0;
4383 DeclarationName Name =
4384 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004385 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004386 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004387
4388 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004389
4390 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004391 }
Anders Carlsson37909802009-11-30 21:24:50 +00004392
4393 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004394}
4395
Mike Stump1eb44332009-09-09 15:08:12 +00004396static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004397FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4398 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4399 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004400 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004401}
4402
Douglas Gregor42a552f2008-11-05 20:51:48 +00004403/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4404/// the well-formednes of the destructor declarator @p D with type @p
4405/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004406/// emit diagnostics and set the declarator to invalid. Even if this happens,
4407/// will be updated to reflect a well-formed type for the destructor and
4408/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004409QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004410 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004411 // C++ [class.dtor]p1:
4412 // [...] A typedef-name that names a class is a class-name
4413 // (7.1.3); however, a typedef-name that names a class shall not
4414 // be used as the identifier in the declarator for a destructor
4415 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004416 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004417 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004418 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004419 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004420 else if (const TemplateSpecializationType *TST =
4421 DeclaratorType->getAs<TemplateSpecializationType>())
4422 if (TST->isTypeAlias())
4423 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4424 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004425
4426 // C++ [class.dtor]p2:
4427 // A destructor is used to destroy objects of its class type. A
4428 // destructor takes no parameters, and no return type can be
4429 // specified for it (not even void). The address of a destructor
4430 // shall not be taken. A destructor shall not be static. A
4431 // destructor can be invoked for a const, volatile or const
4432 // volatile object. A destructor shall not be declared const,
4433 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004434 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004435 if (!D.isInvalidType())
4436 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4437 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004438 << SourceRange(D.getIdentifierLoc())
4439 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4440
John McCalld931b082010-08-26 03:08:43 +00004441 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004442 }
Chris Lattner65401802009-04-25 08:28:21 +00004443 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004444 // Destructors don't have return types, but the parser will
4445 // happily parse something like:
4446 //
4447 // class X {
4448 // float ~X();
4449 // };
4450 //
4451 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004452 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4453 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4454 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004455 }
Mike Stump1eb44332009-09-09 15:08:12 +00004456
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004457 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004458 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004459 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004460 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4461 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004462 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004463 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4464 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004465 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004466 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4467 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004468 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004469 }
4470
Douglas Gregorc938c162011-01-26 05:01:58 +00004471 // C++0x [class.dtor]p2:
4472 // A destructor shall not be declared with a ref-qualifier.
4473 if (FTI.hasRefQualifier()) {
4474 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4475 << FTI.RefQualifierIsLValueRef
4476 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4477 D.setInvalidType();
4478 }
4479
Douglas Gregor42a552f2008-11-05 20:51:48 +00004480 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004481 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004482 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4483
4484 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004485 FTI.freeArgs();
4486 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004487 }
4488
Mike Stump1eb44332009-09-09 15:08:12 +00004489 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004490 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004491 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004492 D.setInvalidType();
4493 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004494
4495 // Rebuild the function type "R" without any type qualifiers or
4496 // parameters (in case any of the errors above fired) and with
4497 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004498 // types.
John McCalle23cf432010-12-14 08:05:40 +00004499 if (!D.isInvalidType())
4500 return R;
4501
Douglas Gregord92ec472010-07-01 05:10:53 +00004502 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004503 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4504 EPI.Variadic = false;
4505 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004506 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004507 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004508}
4509
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004510/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4511/// well-formednes of the conversion function declarator @p D with
4512/// type @p R. If there are any errors in the declarator, this routine
4513/// will emit diagnostics and return true. Otherwise, it will return
4514/// false. Either way, the type @p R will be updated to reflect a
4515/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00004516void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00004517 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004518 // C++ [class.conv.fct]p1:
4519 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00004520 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00004521 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00004522 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00004523 if (!D.isInvalidType())
4524 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4525 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4526 << SourceRange(D.getIdentifierLoc());
4527 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004528 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004529 }
John McCalla3f81372010-04-13 00:04:31 +00004530
4531 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4532
Chris Lattner6e475012009-04-25 08:35:12 +00004533 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004534 // Conversion functions don't have return types, but the parser will
4535 // happily parse something like:
4536 //
4537 // class X {
4538 // float operator bool();
4539 // };
4540 //
4541 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004542 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4543 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4544 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00004545 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004546 }
4547
John McCalla3f81372010-04-13 00:04:31 +00004548 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4549
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004550 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00004551 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004552 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4553
4554 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004555 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00004556 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00004557 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004558 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00004559 D.setInvalidType();
4560 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004561
John McCalla3f81372010-04-13 00:04:31 +00004562 // Diagnose "&operator bool()" and other such nonsense. This
4563 // is actually a gcc extension which we don't support.
4564 if (Proto->getResultType() != ConvType) {
4565 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4566 << Proto->getResultType();
4567 D.setInvalidType();
4568 ConvType = Proto->getResultType();
4569 }
4570
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004571 // C++ [class.conv.fct]p4:
4572 // The conversion-type-id shall not represent a function type nor
4573 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004574 if (ConvType->isArrayType()) {
4575 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4576 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004577 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004578 } else if (ConvType->isFunctionType()) {
4579 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4580 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004581 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004582 }
4583
4584 // Rebuild the function type "R" without any parameters (in case any
4585 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00004586 // return type.
John McCalle23cf432010-12-14 08:05:40 +00004587 if (D.isInvalidType())
4588 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004589
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004590 // C++0x explicit conversion operators.
4591 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00004592 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004593 diag::warn_explicit_conversion_functions)
4594 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004595}
4596
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004597/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4598/// the declaration of the given C++ conversion function. This routine
4599/// is responsible for recording the conversion function in the C++
4600/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00004601Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004602 assert(Conversion && "Expected to receive a conversion function declaration");
4603
Douglas Gregor9d350972008-12-12 08:25:50 +00004604 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004605
4606 // Make sure we aren't redeclaring the conversion function.
4607 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004608
4609 // C++ [class.conv.fct]p1:
4610 // [...] A conversion function is never used to convert a
4611 // (possibly cv-qualified) object to the (possibly cv-qualified)
4612 // same object type (or a reference to it), to a (possibly
4613 // cv-qualified) base class of that type (or a reference to it),
4614 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00004615 // FIXME: Suppress this warning if the conversion function ends up being a
4616 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00004617 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004618 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00004619 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004620 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004621 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4622 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00004623 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004624 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004625 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4626 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00004627 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004628 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004629 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00004630 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004631 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004632 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00004633 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004634 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004635 }
4636
Douglas Gregore80622f2010-09-29 04:25:11 +00004637 if (FunctionTemplateDecl *ConversionTemplate
4638 = Conversion->getDescribedFunctionTemplate())
4639 return ConversionTemplate;
4640
John McCalld226f652010-08-21 09:40:31 +00004641 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004642}
4643
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004644//===----------------------------------------------------------------------===//
4645// Namespace Handling
4646//===----------------------------------------------------------------------===//
4647
John McCallea318642010-08-26 09:15:37 +00004648
4649
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004650/// ActOnStartNamespaceDef - This is called at the start of a namespace
4651/// definition.
John McCalld226f652010-08-21 09:40:31 +00004652Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00004653 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004654 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00004655 SourceLocation IdentLoc,
4656 IdentifierInfo *II,
4657 SourceLocation LBrace,
4658 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004659 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4660 // For anonymous namespace, take the location of the left brace.
4661 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00004662 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004663 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004664 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004665
4666 Scope *DeclRegionScope = NamespcScope->getParent();
4667
Anders Carlsson2a3503d2010-02-07 01:09:23 +00004668 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4669
John McCall90f14502010-12-10 02:59:44 +00004670 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4671 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004672
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004673 if (II) {
4674 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00004675 // The identifier in an original-namespace-definition shall not
4676 // have been previously defined in the declarative region in
4677 // which the original-namespace-definition appears. The
4678 // identifier in an original-namespace-definition is the name of
4679 // the namespace. Subsequently in that declarative region, it is
4680 // treated as an original-namespace-name.
4681 //
4682 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00004683 // look through using directives, just look for any ordinary names.
4684
4685 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4686 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4687 Decl::IDNS_Namespace;
4688 NamedDecl *PrevDecl = 0;
4689 for (DeclContext::lookup_result R
4690 = CurContext->getRedeclContext()->lookup(II);
4691 R.first != R.second; ++R.first) {
4692 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4693 PrevDecl = *R.first;
4694 break;
4695 }
4696 }
4697
Douglas Gregor44b43212008-12-11 16:49:14 +00004698 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4699 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004700 if (Namespc->isInline() != OrigNS->isInline()) {
4701 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004702 if (OrigNS->isInline()) {
4703 // The user probably just forgot the 'inline', so suggest that it
4704 // be added back.
4705 Diag(Namespc->getLocation(),
4706 diag::warn_inline_namespace_reopened_noninline)
4707 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4708 } else {
4709 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4710 << Namespc->isInline();
4711 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004712 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004713
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004714 // Recover by ignoring the new namespace's inline status.
4715 Namespc->setInline(OrigNS->isInline());
4716 }
4717
Douglas Gregor44b43212008-12-11 16:49:14 +00004718 // Attach this namespace decl to the chain of extended namespace
4719 // definitions.
4720 OrigNS->setNextNamespace(Namespc);
4721 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004722
Mike Stump1eb44332009-09-09 15:08:12 +00004723 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00004724 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00004725 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00004726 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004727 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004728 } else if (PrevDecl) {
4729 // This is an invalid name redefinition.
4730 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4731 << Namespc->getDeclName();
4732 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4733 Namespc->setInvalidDecl();
4734 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004735 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004736 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004737 // This is the first "real" definition of the namespace "std", so update
4738 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004739 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004740 // We had already defined a dummy namespace "std". Link this new
4741 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004742 StdNS->setNextNamespace(Namespc);
4743 StdNS->setLocation(IdentLoc);
4744 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004745 }
4746
4747 // Make our StdNamespace cache point at the first real definition of the
4748 // "std" namespace.
4749 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004750
4751 // Add this instance of "std" to the set of known namespaces
4752 KnownNamespaces[Namespc] = false;
4753 } else if (!Namespc->isInline()) {
4754 // Since this is an "original" namespace, add it to the known set of
4755 // namespaces if it is not an inline namespace.
4756 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004757 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004758
4759 PushOnScopeChains(Namespc, DeclRegionScope);
4760 } else {
John McCall9aeed322009-10-01 00:25:31 +00004761 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00004762 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00004763
4764 // Link the anonymous namespace into its parent.
4765 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004766 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00004767 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4768 PrevDecl = TU->getAnonymousNamespace();
4769 TU->setAnonymousNamespace(Namespc);
4770 } else {
4771 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4772 PrevDecl = ND->getAnonymousNamespace();
4773 ND->setAnonymousNamespace(Namespc);
4774 }
4775
4776 // Link the anonymous namespace with its previous declaration.
4777 if (PrevDecl) {
4778 assert(PrevDecl->isAnonymousNamespace());
4779 assert(!PrevDecl->getNextNamespace());
4780 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4781 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004782
4783 if (Namespc->isInline() != PrevDecl->isInline()) {
4784 // inline-ness must match
4785 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4786 << Namespc->isInline();
4787 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4788 Namespc->setInvalidDecl();
4789 // Recover by ignoring the new namespace's inline status.
4790 Namespc->setInline(PrevDecl->isInline());
4791 }
John McCall5fdd7642009-12-16 02:06:49 +00004792 }
John McCall9aeed322009-10-01 00:25:31 +00004793
Douglas Gregora4181472010-03-24 00:46:35 +00004794 CurContext->addDecl(Namespc);
4795
John McCall9aeed322009-10-01 00:25:31 +00004796 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4797 // behaves as if it were replaced by
4798 // namespace unique { /* empty body */ }
4799 // using namespace unique;
4800 // namespace unique { namespace-body }
4801 // where all occurrences of 'unique' in a translation unit are
4802 // replaced by the same identifier and this identifier differs
4803 // from all other identifiers in the entire program.
4804
4805 // We just create the namespace with an empty name and then add an
4806 // implicit using declaration, just like the standard suggests.
4807 //
4808 // CodeGen enforces the "universally unique" aspect by giving all
4809 // declarations semantically contained within an anonymous
4810 // namespace internal linkage.
4811
John McCall5fdd7642009-12-16 02:06:49 +00004812 if (!PrevDecl) {
4813 UsingDirectiveDecl* UD
4814 = UsingDirectiveDecl::Create(Context, CurContext,
4815 /* 'using' */ LBrace,
4816 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00004817 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00004818 /* identifier */ SourceLocation(),
4819 Namespc,
4820 /* Ancestor */ CurContext);
4821 UD->setImplicit();
4822 CurContext->addDecl(UD);
4823 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004824 }
4825
4826 // Although we could have an invalid decl (i.e. the namespace name is a
4827 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00004828 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4829 // for the namespace has the declarations that showed up in that particular
4830 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00004831 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00004832 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004833}
4834
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004835/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4836/// is a namespace alias, returns the namespace it points to.
4837static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4838 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4839 return AD->getNamespace();
4840 return dyn_cast_or_null<NamespaceDecl>(D);
4841}
4842
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004843/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4844/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00004845void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004846 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4847 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004848 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004849 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004850 if (Namespc->hasAttr<VisibilityAttr>())
4851 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004852}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004853
John McCall384aff82010-08-25 07:42:41 +00004854CXXRecordDecl *Sema::getStdBadAlloc() const {
4855 return cast_or_null<CXXRecordDecl>(
4856 StdBadAlloc.get(Context.getExternalSource()));
4857}
4858
4859NamespaceDecl *Sema::getStdNamespace() const {
4860 return cast_or_null<NamespaceDecl>(
4861 StdNamespace.get(Context.getExternalSource()));
4862}
4863
Douglas Gregor66992202010-06-29 17:53:46 +00004864/// \brief Retrieve the special "std" namespace, which may require us to
4865/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004866NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00004867 if (!StdNamespace) {
4868 // The "std" namespace has not yet been defined, so build one implicitly.
4869 StdNamespace = NamespaceDecl::Create(Context,
4870 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004871 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00004872 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004873 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00004874 }
4875
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004876 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00004877}
4878
Douglas Gregor9172aa62011-03-26 22:25:30 +00004879/// \brief Determine whether a using statement is in a context where it will be
4880/// apply in all contexts.
4881static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4882 switch (CurContext->getDeclKind()) {
4883 case Decl::TranslationUnit:
4884 return true;
4885 case Decl::LinkageSpec:
4886 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4887 default:
4888 return false;
4889 }
4890}
4891
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004892static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
4893 CXXScopeSpec &SS,
4894 SourceLocation IdentLoc,
4895 IdentifierInfo *Ident) {
4896 R.clear();
4897 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
4898 R.getLookupKind(), Sc, &SS, NULL,
4899 false, S.CTC_NoKeywords, NULL)) {
4900 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
4901 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
4902 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
4903 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
4904 if (DeclContext *DC = S.computeDeclContext(SS, false))
4905 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
4906 << Ident << DC << CorrectedQuotedStr << SS.getRange()
4907 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4908 else
4909 S.Diag(IdentLoc, diag::err_using_directive_suggest)
4910 << Ident << CorrectedQuotedStr
4911 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4912
4913 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
4914 diag::note_namespace_defined_here) << CorrectedQuotedStr;
4915
4916 Ident = Corrected.getCorrectionAsIdentifierInfo();
4917 R.addDecl(Corrected.getCorrectionDecl());
4918 return true;
4919 }
4920 R.setLookupName(Ident);
4921 }
4922 return false;
4923}
4924
John McCalld226f652010-08-21 09:40:31 +00004925Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004926 SourceLocation UsingLoc,
4927 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004928 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004929 SourceLocation IdentLoc,
4930 IdentifierInfo *NamespcName,
4931 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00004932 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4933 assert(NamespcName && "Invalid NamespcName.");
4934 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00004935
4936 // This can only happen along a recovery path.
4937 while (S->getFlags() & Scope::TemplateParamScope)
4938 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004939 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00004940
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004941 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00004942 NestedNameSpecifier *Qualifier = 0;
4943 if (SS.isSet())
4944 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4945
Douglas Gregoreb11cd02009-01-14 22:20:51 +00004946 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004947 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4948 LookupParsedName(R, S, &SS);
4949 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004950 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004951
Douglas Gregor66992202010-06-29 17:53:46 +00004952 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004953 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00004954 // Allow "using namespace std;" or "using namespace ::std;" even if
4955 // "std" hasn't been defined yet, for GCC compatibility.
4956 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4957 NamespcName->isStr("std")) {
4958 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004959 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00004960 R.resolveKind();
4961 }
4962 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004963 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00004964 }
4965
John McCallf36e02d2009-10-09 21:13:30 +00004966 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004967 NamedDecl *Named = R.getFoundDecl();
4968 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4969 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004970 // C++ [namespace.udir]p1:
4971 // A using-directive specifies that the names in the nominated
4972 // namespace can be used in the scope in which the
4973 // using-directive appears after the using-directive. During
4974 // unqualified name lookup (3.4.1), the names appear as if they
4975 // were declared in the nearest enclosing namespace which
4976 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00004977 // namespace. [Note: in this context, "contains" means "contains
4978 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004979
4980 // Find enclosing context containing both using-directive and
4981 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004982 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004983 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4984 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4985 CommonAncestor = CommonAncestor->getParent();
4986
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004987 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00004988 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004989 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004990
Douglas Gregor9172aa62011-03-26 22:25:30 +00004991 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00004992 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004993 Diag(IdentLoc, diag::warn_using_directive_in_header);
4994 }
4995
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004996 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004997 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00004998 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00004999 }
5000
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005001 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005002 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005003}
5004
5005void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5006 // If scope has associated entity, then using directive is at namespace
5007 // or translation unit scope. We add UsingDirectiveDecls, into
5008 // it's lookup structure.
5009 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005010 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005011 else
5012 // Otherwise it is block-sope. using-directives will affect lookup
5013 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005014 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005015}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005016
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005017
John McCalld226f652010-08-21 09:40:31 +00005018Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005019 AccessSpecifier AS,
5020 bool HasUsingKeyword,
5021 SourceLocation UsingLoc,
5022 CXXScopeSpec &SS,
5023 UnqualifiedId &Name,
5024 AttributeList *AttrList,
5025 bool IsTypeName,
5026 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005027 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005028
Douglas Gregor12c118a2009-11-04 16:30:06 +00005029 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005030 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005031 case UnqualifiedId::IK_Identifier:
5032 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005033 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005034 case UnqualifiedId::IK_ConversionFunctionId:
5035 break;
5036
5037 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005038 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005039 // C++0x inherited constructors.
5040 if (getLangOptions().CPlusPlus0x) break;
5041
Douglas Gregor12c118a2009-11-04 16:30:06 +00005042 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5043 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005044 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005045
5046 case UnqualifiedId::IK_DestructorName:
5047 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5048 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005049 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005050
5051 case UnqualifiedId::IK_TemplateId:
5052 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5053 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005054 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005055 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005056
5057 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5058 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005059 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005060 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005061
John McCall60fa3cf2009-12-11 02:10:03 +00005062 // Warn about using declarations.
5063 // TODO: store that the declaration was written without 'using' and
5064 // talk about access decls instead of using decls in the
5065 // diagnostics.
5066 if (!HasUsingKeyword) {
5067 UsingLoc = Name.getSourceRange().getBegin();
5068
5069 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005070 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005071 }
5072
Douglas Gregor56c04582010-12-16 00:46:58 +00005073 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5074 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5075 return 0;
5076
John McCall9488ea12009-11-17 05:59:44 +00005077 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005078 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005079 /* IsInstantiation */ false,
5080 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005081 if (UD)
5082 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005083
John McCalld226f652010-08-21 09:40:31 +00005084 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005085}
5086
Douglas Gregor09acc982010-07-07 23:08:52 +00005087/// \brief Determine whether a using declaration considers the given
5088/// declarations as "equivalent", e.g., if they are redeclarations of
5089/// the same entity or are both typedefs of the same type.
5090static bool
5091IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5092 bool &SuppressRedeclaration) {
5093 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5094 SuppressRedeclaration = false;
5095 return true;
5096 }
5097
Richard Smith162e1c12011-04-15 14:24:37 +00005098 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5099 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005100 SuppressRedeclaration = true;
5101 return Context.hasSameType(TD1->getUnderlyingType(),
5102 TD2->getUnderlyingType());
5103 }
5104
5105 return false;
5106}
5107
5108
John McCall9f54ad42009-12-10 09:41:52 +00005109/// Determines whether to create a using shadow decl for a particular
5110/// decl, given the set of decls existing prior to this using lookup.
5111bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5112 const LookupResult &Previous) {
5113 // Diagnose finding a decl which is not from a base class of the
5114 // current class. We do this now because there are cases where this
5115 // function will silently decide not to build a shadow decl, which
5116 // will pre-empt further diagnostics.
5117 //
5118 // We don't need to do this in C++0x because we do the check once on
5119 // the qualifier.
5120 //
5121 // FIXME: diagnose the following if we care enough:
5122 // struct A { int foo; };
5123 // struct B : A { using A::foo; };
5124 // template <class T> struct C : A {};
5125 // template <class T> struct D : C<T> { using B::foo; } // <---
5126 // This is invalid (during instantiation) in C++03 because B::foo
5127 // resolves to the using decl in B, which is not a base class of D<T>.
5128 // We can't diagnose it immediately because C<T> is an unknown
5129 // specialization. The UsingShadowDecl in D<T> then points directly
5130 // to A::foo, which will look well-formed when we instantiate.
5131 // The right solution is to not collapse the shadow-decl chain.
5132 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5133 DeclContext *OrigDC = Orig->getDeclContext();
5134
5135 // Handle enums and anonymous structs.
5136 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5137 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5138 while (OrigRec->isAnonymousStructOrUnion())
5139 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5140
5141 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5142 if (OrigDC == CurContext) {
5143 Diag(Using->getLocation(),
5144 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005145 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005146 Diag(Orig->getLocation(), diag::note_using_decl_target);
5147 return true;
5148 }
5149
Douglas Gregordc355712011-02-25 00:36:19 +00005150 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005151 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005152 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005153 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005154 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005155 Diag(Orig->getLocation(), diag::note_using_decl_target);
5156 return true;
5157 }
5158 }
5159
5160 if (Previous.empty()) return false;
5161
5162 NamedDecl *Target = Orig;
5163 if (isa<UsingShadowDecl>(Target))
5164 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5165
John McCalld7533ec2009-12-11 02:33:26 +00005166 // If the target happens to be one of the previous declarations, we
5167 // don't have a conflict.
5168 //
5169 // FIXME: but we might be increasing its access, in which case we
5170 // should redeclare it.
5171 NamedDecl *NonTag = 0, *Tag = 0;
5172 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5173 I != E; ++I) {
5174 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005175 bool Result;
5176 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5177 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005178
5179 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5180 }
5181
John McCall9f54ad42009-12-10 09:41:52 +00005182 if (Target->isFunctionOrFunctionTemplate()) {
5183 FunctionDecl *FD;
5184 if (isa<FunctionTemplateDecl>(Target))
5185 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5186 else
5187 FD = cast<FunctionDecl>(Target);
5188
5189 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005190 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005191 case Ovl_Overload:
5192 return false;
5193
5194 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005195 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005196 break;
5197
5198 // We found a decl with the exact signature.
5199 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005200 // If we're in a record, we want to hide the target, so we
5201 // return true (without a diagnostic) to tell the caller not to
5202 // build a shadow decl.
5203 if (CurContext->isRecord())
5204 return true;
5205
5206 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005207 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005208 break;
5209 }
5210
5211 Diag(Target->getLocation(), diag::note_using_decl_target);
5212 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5213 return true;
5214 }
5215
5216 // Target is not a function.
5217
John McCall9f54ad42009-12-10 09:41:52 +00005218 if (isa<TagDecl>(Target)) {
5219 // No conflict between a tag and a non-tag.
5220 if (!Tag) return false;
5221
John McCall41ce66f2009-12-10 19:51:03 +00005222 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005223 Diag(Target->getLocation(), diag::note_using_decl_target);
5224 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5225 return true;
5226 }
5227
5228 // No conflict between a tag and a non-tag.
5229 if (!NonTag) return false;
5230
John McCall41ce66f2009-12-10 19:51:03 +00005231 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005232 Diag(Target->getLocation(), diag::note_using_decl_target);
5233 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5234 return true;
5235}
5236
John McCall9488ea12009-11-17 05:59:44 +00005237/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005238UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005239 UsingDecl *UD,
5240 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005241
5242 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005243 NamedDecl *Target = Orig;
5244 if (isa<UsingShadowDecl>(Target)) {
5245 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5246 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005247 }
5248
5249 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005250 = UsingShadowDecl::Create(Context, CurContext,
5251 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005252 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005253
5254 Shadow->setAccess(UD->getAccess());
5255 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5256 Shadow->setInvalidDecl();
5257
John McCall9488ea12009-11-17 05:59:44 +00005258 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005259 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005260 else
John McCall604e7f12009-12-08 07:46:18 +00005261 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005262
John McCall604e7f12009-12-08 07:46:18 +00005263
John McCall9f54ad42009-12-10 09:41:52 +00005264 return Shadow;
5265}
John McCall604e7f12009-12-08 07:46:18 +00005266
John McCall9f54ad42009-12-10 09:41:52 +00005267/// Hides a using shadow declaration. This is required by the current
5268/// using-decl implementation when a resolvable using declaration in a
5269/// class is followed by a declaration which would hide or override
5270/// one or more of the using decl's targets; for example:
5271///
5272/// struct Base { void foo(int); };
5273/// struct Derived : Base {
5274/// using Base::foo;
5275/// void foo(int);
5276/// };
5277///
5278/// The governing language is C++03 [namespace.udecl]p12:
5279///
5280/// When a using-declaration brings names from a base class into a
5281/// derived class scope, member functions in the derived class
5282/// override and/or hide member functions with the same name and
5283/// parameter types in a base class (rather than conflicting).
5284///
5285/// There are two ways to implement this:
5286/// (1) optimistically create shadow decls when they're not hidden
5287/// by existing declarations, or
5288/// (2) don't create any shadow decls (or at least don't make them
5289/// visible) until we've fully parsed/instantiated the class.
5290/// The problem with (1) is that we might have to retroactively remove
5291/// a shadow decl, which requires several O(n) operations because the
5292/// decl structures are (very reasonably) not designed for removal.
5293/// (2) avoids this but is very fiddly and phase-dependent.
5294void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005295 if (Shadow->getDeclName().getNameKind() ==
5296 DeclarationName::CXXConversionFunctionName)
5297 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5298
John McCall9f54ad42009-12-10 09:41:52 +00005299 // Remove it from the DeclContext...
5300 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005301
John McCall9f54ad42009-12-10 09:41:52 +00005302 // ...and the scope, if applicable...
5303 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005304 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005305 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005306 }
5307
John McCall9f54ad42009-12-10 09:41:52 +00005308 // ...and the using decl.
5309 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5310
5311 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005312 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005313}
5314
John McCall7ba107a2009-11-18 02:36:19 +00005315/// Builds a using declaration.
5316///
5317/// \param IsInstantiation - Whether this call arises from an
5318/// instantiation of an unresolved using declaration. We treat
5319/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005320NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5321 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005322 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005323 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005324 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005325 bool IsInstantiation,
5326 bool IsTypeName,
5327 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005328 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005329 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005330 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005331
Anders Carlsson550b14b2009-08-28 05:49:21 +00005332 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005333
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005334 if (SS.isEmpty()) {
5335 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005336 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005337 }
Mike Stump1eb44332009-09-09 15:08:12 +00005338
John McCall9f54ad42009-12-10 09:41:52 +00005339 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005340 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005341 ForRedeclaration);
5342 Previous.setHideTags(false);
5343 if (S) {
5344 LookupName(Previous, S);
5345
5346 // It is really dumb that we have to do this.
5347 LookupResult::Filter F = Previous.makeFilter();
5348 while (F.hasNext()) {
5349 NamedDecl *D = F.next();
5350 if (!isDeclInScope(D, CurContext, S))
5351 F.erase();
5352 }
5353 F.done();
5354 } else {
5355 assert(IsInstantiation && "no scope in non-instantiation");
5356 assert(CurContext->isRecord() && "scope not record in instantiation");
5357 LookupQualifiedName(Previous, CurContext);
5358 }
5359
John McCall9f54ad42009-12-10 09:41:52 +00005360 // Check for invalid redeclarations.
5361 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5362 return 0;
5363
5364 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005365 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5366 return 0;
5367
John McCallaf8e6ed2009-11-12 03:15:40 +00005368 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005369 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005370 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005371 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005372 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005373 // FIXME: not all declaration name kinds are legal here
5374 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5375 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005376 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005377 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005378 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005379 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5380 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005381 }
John McCalled976492009-12-04 22:46:56 +00005382 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005383 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5384 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005385 }
John McCalled976492009-12-04 22:46:56 +00005386 D->setAccess(AS);
5387 CurContext->addDecl(D);
5388
5389 if (!LookupContext) return D;
5390 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005391
John McCall77bb1aa2010-05-01 00:40:08 +00005392 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005393 UD->setInvalidDecl();
5394 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005395 }
5396
Sebastian Redlf677ea32011-02-05 19:23:19 +00005397 // Constructor inheriting using decls get special treatment.
5398 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005399 if (CheckInheritedConstructorUsingDecl(UD))
5400 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005401 return UD;
5402 }
5403
5404 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005405
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005406 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005407 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005408
John McCall604e7f12009-12-08 07:46:18 +00005409 // Unlike most lookups, we don't always want to hide tag
5410 // declarations: tag names are visible through the using declaration
5411 // even if hidden by ordinary names, *except* in a dependent context
5412 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005413 if (!IsInstantiation)
5414 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005415
John McCalla24dc2e2009-11-17 02:14:36 +00005416 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005417
John McCallf36e02d2009-10-09 21:13:30 +00005418 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005419 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005420 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005421 UD->setInvalidDecl();
5422 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005423 }
5424
John McCalled976492009-12-04 22:46:56 +00005425 if (R.isAmbiguous()) {
5426 UD->setInvalidDecl();
5427 return UD;
5428 }
Mike Stump1eb44332009-09-09 15:08:12 +00005429
John McCall7ba107a2009-11-18 02:36:19 +00005430 if (IsTypeName) {
5431 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005432 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005433 Diag(IdentLoc, diag::err_using_typename_non_type);
5434 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5435 Diag((*I)->getUnderlyingDecl()->getLocation(),
5436 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005437 UD->setInvalidDecl();
5438 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005439 }
5440 } else {
5441 // If we asked for a non-typename and we got a type, error out,
5442 // but only if this is an instantiation of an unresolved using
5443 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005444 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005445 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5446 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005447 UD->setInvalidDecl();
5448 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005449 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005450 }
5451
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005452 // C++0x N2914 [namespace.udecl]p6:
5453 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005454 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005455 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5456 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005457 UD->setInvalidDecl();
5458 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005459 }
Mike Stump1eb44332009-09-09 15:08:12 +00005460
John McCall9f54ad42009-12-10 09:41:52 +00005461 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5462 if (!CheckUsingShadowDecl(UD, *I, Previous))
5463 BuildUsingShadowDecl(S, UD, *I);
5464 }
John McCall9488ea12009-11-17 05:59:44 +00005465
5466 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005467}
5468
Sebastian Redlf677ea32011-02-05 19:23:19 +00005469/// Additional checks for a using declaration referring to a constructor name.
5470bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5471 if (UD->isTypeName()) {
5472 // FIXME: Cannot specify typename when specifying constructor
5473 return true;
5474 }
5475
Douglas Gregordc355712011-02-25 00:36:19 +00005476 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005477 assert(SourceType &&
5478 "Using decl naming constructor doesn't have type in scope spec.");
5479 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5480
5481 // Check whether the named type is a direct base class.
5482 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5483 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5484 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5485 BaseIt != BaseE; ++BaseIt) {
5486 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5487 if (CanonicalSourceType == BaseType)
5488 break;
5489 }
5490
5491 if (BaseIt == BaseE) {
5492 // Did not find SourceType in the bases.
5493 Diag(UD->getUsingLocation(),
5494 diag::err_using_decl_constructor_not_in_direct_base)
5495 << UD->getNameInfo().getSourceRange()
5496 << QualType(SourceType, 0) << TargetClass;
5497 return true;
5498 }
5499
5500 BaseIt->setInheritConstructors();
5501
5502 return false;
5503}
5504
John McCall9f54ad42009-12-10 09:41:52 +00005505/// Checks that the given using declaration is not an invalid
5506/// redeclaration. Note that this is checking only for the using decl
5507/// itself, not for any ill-formedness among the UsingShadowDecls.
5508bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5509 bool isTypeName,
5510 const CXXScopeSpec &SS,
5511 SourceLocation NameLoc,
5512 const LookupResult &Prev) {
5513 // C++03 [namespace.udecl]p8:
5514 // C++0x [namespace.udecl]p10:
5515 // A using-declaration is a declaration and can therefore be used
5516 // repeatedly where (and only where) multiple declarations are
5517 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00005518 //
John McCall8a726212010-11-29 18:01:58 +00005519 // That's in non-member contexts.
5520 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00005521 return false;
5522
5523 NestedNameSpecifier *Qual
5524 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5525
5526 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5527 NamedDecl *D = *I;
5528
5529 bool DTypename;
5530 NestedNameSpecifier *DQual;
5531 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5532 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00005533 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005534 } else if (UnresolvedUsingValueDecl *UD
5535 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5536 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00005537 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005538 } else if (UnresolvedUsingTypenameDecl *UD
5539 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5540 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00005541 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005542 } else continue;
5543
5544 // using decls differ if one says 'typename' and the other doesn't.
5545 // FIXME: non-dependent using decls?
5546 if (isTypeName != DTypename) continue;
5547
5548 // using decls differ if they name different scopes (but note that
5549 // template instantiation can cause this check to trigger when it
5550 // didn't before instantiation).
5551 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5552 Context.getCanonicalNestedNameSpecifier(DQual))
5553 continue;
5554
5555 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00005556 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00005557 return true;
5558 }
5559
5560 return false;
5561}
5562
John McCall604e7f12009-12-08 07:46:18 +00005563
John McCalled976492009-12-04 22:46:56 +00005564/// Checks that the given nested-name qualifier used in a using decl
5565/// in the current context is appropriately related to the current
5566/// scope. If an error is found, diagnoses it and returns true.
5567bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5568 const CXXScopeSpec &SS,
5569 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00005570 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005571
John McCall604e7f12009-12-08 07:46:18 +00005572 if (!CurContext->isRecord()) {
5573 // C++03 [namespace.udecl]p3:
5574 // C++0x [namespace.udecl]p8:
5575 // A using-declaration for a class member shall be a member-declaration.
5576
5577 // If we weren't able to compute a valid scope, it must be a
5578 // dependent class scope.
5579 if (!NamedContext || NamedContext->isRecord()) {
5580 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5581 << SS.getRange();
5582 return true;
5583 }
5584
5585 // Otherwise, everything is known to be fine.
5586 return false;
5587 }
5588
5589 // The current scope is a record.
5590
5591 // If the named context is dependent, we can't decide much.
5592 if (!NamedContext) {
5593 // FIXME: in C++0x, we can diagnose if we can prove that the
5594 // nested-name-specifier does not refer to a base class, which is
5595 // still possible in some cases.
5596
5597 // Otherwise we have to conservatively report that things might be
5598 // okay.
5599 return false;
5600 }
5601
5602 if (!NamedContext->isRecord()) {
5603 // Ideally this would point at the last name in the specifier,
5604 // but we don't have that level of source info.
5605 Diag(SS.getRange().getBegin(),
5606 diag::err_using_decl_nested_name_specifier_is_not_class)
5607 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5608 return true;
5609 }
5610
Douglas Gregor6fb07292010-12-21 07:41:49 +00005611 if (!NamedContext->isDependentContext() &&
5612 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5613 return true;
5614
John McCall604e7f12009-12-08 07:46:18 +00005615 if (getLangOptions().CPlusPlus0x) {
5616 // C++0x [namespace.udecl]p3:
5617 // In a using-declaration used as a member-declaration, the
5618 // nested-name-specifier shall name a base class of the class
5619 // being defined.
5620
5621 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5622 cast<CXXRecordDecl>(NamedContext))) {
5623 if (CurContext == NamedContext) {
5624 Diag(NameLoc,
5625 diag::err_using_decl_nested_name_specifier_is_current_class)
5626 << SS.getRange();
5627 return true;
5628 }
5629
5630 Diag(SS.getRange().getBegin(),
5631 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5632 << (NestedNameSpecifier*) SS.getScopeRep()
5633 << cast<CXXRecordDecl>(CurContext)
5634 << SS.getRange();
5635 return true;
5636 }
5637
5638 return false;
5639 }
5640
5641 // C++03 [namespace.udecl]p4:
5642 // A using-declaration used as a member-declaration shall refer
5643 // to a member of a base class of the class being defined [etc.].
5644
5645 // Salient point: SS doesn't have to name a base class as long as
5646 // lookup only finds members from base classes. Therefore we can
5647 // diagnose here only if we can prove that that can't happen,
5648 // i.e. if the class hierarchies provably don't intersect.
5649
5650 // TODO: it would be nice if "definitely valid" results were cached
5651 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5652 // need to be repeated.
5653
5654 struct UserData {
5655 llvm::DenseSet<const CXXRecordDecl*> Bases;
5656
5657 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5658 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5659 Data->Bases.insert(Base);
5660 return true;
5661 }
5662
5663 bool hasDependentBases(const CXXRecordDecl *Class) {
5664 return !Class->forallBases(collect, this);
5665 }
5666
5667 /// Returns true if the base is dependent or is one of the
5668 /// accumulated base classes.
5669 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5670 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5671 return !Data->Bases.count(Base);
5672 }
5673
5674 bool mightShareBases(const CXXRecordDecl *Class) {
5675 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5676 }
5677 };
5678
5679 UserData Data;
5680
5681 // Returns false if we find a dependent base.
5682 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5683 return false;
5684
5685 // Returns false if the class has a dependent base or if it or one
5686 // of its bases is present in the base set of the current context.
5687 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5688 return false;
5689
5690 Diag(SS.getRange().getBegin(),
5691 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5692 << (NestedNameSpecifier*) SS.getScopeRep()
5693 << cast<CXXRecordDecl>(CurContext)
5694 << SS.getRange();
5695
5696 return true;
John McCalled976492009-12-04 22:46:56 +00005697}
5698
Richard Smith162e1c12011-04-15 14:24:37 +00005699Decl *Sema::ActOnAliasDeclaration(Scope *S,
5700 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005701 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00005702 SourceLocation UsingLoc,
5703 UnqualifiedId &Name,
5704 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00005705 // Skip up to the relevant declaration scope.
5706 while (S->getFlags() & Scope::TemplateParamScope)
5707 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00005708 assert((S->getFlags() & Scope::DeclScope) &&
5709 "got alias-declaration outside of declaration scope");
5710
5711 if (Type.isInvalid())
5712 return 0;
5713
5714 bool Invalid = false;
5715 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5716 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00005717 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00005718
5719 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5720 return 0;
5721
5722 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005723 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00005724 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005725 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5726 TInfo->getTypeLoc().getBeginLoc());
5727 }
Richard Smith162e1c12011-04-15 14:24:37 +00005728
5729 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5730 LookupName(Previous, S);
5731
5732 // Warn about shadowing the name of a template parameter.
5733 if (Previous.isSingleResult() &&
5734 Previous.getFoundDecl()->isTemplateParameter()) {
5735 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5736 Previous.getFoundDecl()))
5737 Invalid = true;
5738 Previous.clear();
5739 }
5740
5741 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5742 "name in alias declaration must be an identifier");
5743 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5744 Name.StartLocation,
5745 Name.Identifier, TInfo);
5746
5747 NewTD->setAccess(AS);
5748
5749 if (Invalid)
5750 NewTD->setInvalidDecl();
5751
Richard Smith3e4c6c42011-05-05 21:57:07 +00005752 CheckTypedefForVariablyModifiedType(S, NewTD);
5753 Invalid |= NewTD->isInvalidDecl();
5754
Richard Smith162e1c12011-04-15 14:24:37 +00005755 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005756
5757 NamedDecl *NewND;
5758 if (TemplateParamLists.size()) {
5759 TypeAliasTemplateDecl *OldDecl = 0;
5760 TemplateParameterList *OldTemplateParams = 0;
5761
5762 if (TemplateParamLists.size() != 1) {
5763 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5764 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5765 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5766 }
5767 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5768
5769 // Only consider previous declarations in the same scope.
5770 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5771 /*ExplicitInstantiationOrSpecialization*/false);
5772 if (!Previous.empty()) {
5773 Redeclaration = true;
5774
5775 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5776 if (!OldDecl && !Invalid) {
5777 Diag(UsingLoc, diag::err_redefinition_different_kind)
5778 << Name.Identifier;
5779
5780 NamedDecl *OldD = Previous.getRepresentativeDecl();
5781 if (OldD->getLocation().isValid())
5782 Diag(OldD->getLocation(), diag::note_previous_definition);
5783
5784 Invalid = true;
5785 }
5786
5787 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5788 if (TemplateParameterListsAreEqual(TemplateParams,
5789 OldDecl->getTemplateParameters(),
5790 /*Complain=*/true,
5791 TPL_TemplateMatch))
5792 OldTemplateParams = OldDecl->getTemplateParameters();
5793 else
5794 Invalid = true;
5795
5796 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5797 if (!Invalid &&
5798 !Context.hasSameType(OldTD->getUnderlyingType(),
5799 NewTD->getUnderlyingType())) {
5800 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5801 // but we can't reasonably accept it.
5802 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5803 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5804 if (OldTD->getLocation().isValid())
5805 Diag(OldTD->getLocation(), diag::note_previous_definition);
5806 Invalid = true;
5807 }
5808 }
5809 }
5810
5811 // Merge any previous default template arguments into our parameters,
5812 // and check the parameter list.
5813 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5814 TPC_TypeAliasTemplate))
5815 return 0;
5816
5817 TypeAliasTemplateDecl *NewDecl =
5818 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5819 Name.Identifier, TemplateParams,
5820 NewTD);
5821
5822 NewDecl->setAccess(AS);
5823
5824 if (Invalid)
5825 NewDecl->setInvalidDecl();
5826 else if (OldDecl)
5827 NewDecl->setPreviousDeclaration(OldDecl);
5828
5829 NewND = NewDecl;
5830 } else {
5831 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5832 NewND = NewTD;
5833 }
Richard Smith162e1c12011-04-15 14:24:37 +00005834
5835 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00005836 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00005837
Richard Smith3e4c6c42011-05-05 21:57:07 +00005838 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00005839}
5840
John McCalld226f652010-08-21 09:40:31 +00005841Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005842 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005843 SourceLocation AliasLoc,
5844 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005845 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005846 SourceLocation IdentLoc,
5847 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00005848
Anders Carlsson81c85c42009-03-28 23:53:49 +00005849 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005850 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5851 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00005852
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005853 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00005854 NamedDecl *PrevDecl
5855 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5856 ForRedeclaration);
5857 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5858 PrevDecl = 0;
5859
5860 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00005861 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005862 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00005863 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00005864 // FIXME: At some point, we'll want to create the (redundant)
5865 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00005866 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00005867 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00005868 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00005869 }
Mike Stump1eb44332009-09-09 15:08:12 +00005870
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005871 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5872 diag::err_redefinition_different_kind;
5873 Diag(AliasLoc, DiagID) << Alias;
5874 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00005875 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005876 }
5877
John McCalla24dc2e2009-11-17 02:14:36 +00005878 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005879 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005880
John McCallf36e02d2009-10-09 21:13:30 +00005881 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005882 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005883 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005884 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005885 }
Anders Carlsson5721c682009-03-28 06:42:02 +00005886 }
Mike Stump1eb44332009-09-09 15:08:12 +00005887
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005888 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00005889 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00005890 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00005891 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00005892
John McCall3dbd3d52010-02-16 06:53:13 +00005893 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00005894 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00005895}
5896
Douglas Gregor39957dc2010-05-01 15:04:51 +00005897namespace {
5898 /// \brief Scoped object used to handle the state changes required in Sema
5899 /// to implicitly define the body of a C++ member function;
5900 class ImplicitlyDefinedFunctionScope {
5901 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00005902 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00005903
5904 public:
5905 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00005906 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00005907 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00005908 S.PushFunctionScope();
5909 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5910 }
5911
5912 ~ImplicitlyDefinedFunctionScope() {
5913 S.PopExpressionEvaluationContext();
5914 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00005915 }
5916 };
5917}
5918
Sean Hunt001cad92011-05-10 00:49:42 +00005919Sema::ImplicitExceptionSpecification
5920Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005921 // C++ [except.spec]p14:
5922 // An implicitly declared special member function (Clause 12) shall have an
5923 // exception-specification. [...]
5924 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00005925 if (ClassDecl->isInvalidDecl())
5926 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005927
Sebastian Redl60618fa2011-03-12 11:50:43 +00005928 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005929 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5930 BEnd = ClassDecl->bases_end();
5931 B != BEnd; ++B) {
5932 if (B->isVirtual()) // Handled below.
5933 continue;
5934
Douglas Gregor18274032010-07-03 00:47:00 +00005935 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5936 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00005937 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5938 // If this is a deleted function, add it anyway. This might be conformant
5939 // with the standard. This might not. I'm not sure. It might not matter.
5940 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005941 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005942 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005943 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005944
5945 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005946 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5947 BEnd = ClassDecl->vbases_end();
5948 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00005949 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5950 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00005951 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5952 // If this is a deleted function, add it anyway. This might be conformant
5953 // with the standard. This might not. I'm not sure. It might not matter.
5954 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005955 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005956 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005957 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005958
5959 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005960 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5961 FEnd = ClassDecl->field_end();
5962 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00005963 if (F->hasInClassInitializer()) {
5964 if (Expr *E = F->getInClassInitializer())
5965 ExceptSpec.CalledExpr(E);
5966 else if (!F->isInvalidDecl())
5967 ExceptSpec.SetDelayed();
5968 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00005969 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00005970 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5971 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5972 // If this is a deleted function, add it anyway. This might be conformant
5973 // with the standard. This might not. I'm not sure. It might not matter.
5974 // In particular, the problem is that this function never gets called. It
5975 // might just be ill-formed because this function attempts to refer to
5976 // a deleted function here.
5977 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005978 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005979 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005980 }
John McCalle23cf432010-12-14 08:05:40 +00005981
Sean Hunt001cad92011-05-10 00:49:42 +00005982 return ExceptSpec;
5983}
5984
5985CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5986 CXXRecordDecl *ClassDecl) {
5987 // C++ [class.ctor]p5:
5988 // A default constructor for a class X is a constructor of class X
5989 // that can be called without an argument. If there is no
5990 // user-declared constructor for class X, a default constructor is
5991 // implicitly declared. An implicitly-declared default constructor
5992 // is an inline public member of its class.
5993 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5994 "Should not build implicit default constructor!");
5995
5996 ImplicitExceptionSpecification Spec =
5997 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5998 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00005999
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006000 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006001 CanQualType ClassType
6002 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006003 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006004 DeclarationName Name
6005 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006006 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006007 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006008 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006009 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006010 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006011 /*TInfo=*/0,
6012 /*isExplicit=*/false,
6013 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006014 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006015 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006016 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006017 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006018 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006019
6020 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006021 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6022
Douglas Gregor23c94db2010-07-02 17:43:08 +00006023 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006024 PushOnScopeChains(DefaultCon, S, false);
6025 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006026
6027 if (ShouldDeleteDefaultConstructor(DefaultCon))
6028 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006029
Douglas Gregor32df23e2010-07-01 22:02:46 +00006030 return DefaultCon;
6031}
6032
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006033void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6034 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006035 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006036 !Constructor->doesThisDeclarationHaveABody() &&
6037 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006038 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006039
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006040 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006041 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006042
Douglas Gregor39957dc2010-05-01 15:04:51 +00006043 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006044 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006045 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006046 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006047 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006048 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006049 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006050 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006051 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006052
6053 SourceLocation Loc = Constructor->getLocation();
6054 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6055
6056 Constructor->setUsed();
6057 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006058
6059 if (ASTMutationListener *L = getASTMutationListener()) {
6060 L->CompletedImplicitDefinition(Constructor);
6061 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006062}
6063
Richard Smith7a614d82011-06-11 17:19:42 +00006064/// Get any existing defaulted default constructor for the given class. Do not
6065/// implicitly define one if it does not exist.
6066static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6067 CXXRecordDecl *D) {
6068 ASTContext &Context = Self.Context;
6069 QualType ClassType = Context.getTypeDeclType(D);
6070 DeclarationName ConstructorName
6071 = Context.DeclarationNames.getCXXConstructorName(
6072 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6073
6074 DeclContext::lookup_const_iterator Con, ConEnd;
6075 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6076 Con != ConEnd; ++Con) {
6077 // A function template cannot be defaulted.
6078 if (isa<FunctionTemplateDecl>(*Con))
6079 continue;
6080
6081 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6082 if (Constructor->isDefaultConstructor())
6083 return Constructor->isDefaulted() ? Constructor : 0;
6084 }
6085 return 0;
6086}
6087
6088void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6089 if (!D) return;
6090 AdjustDeclIfTemplate(D);
6091
6092 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6093 CXXConstructorDecl *CtorDecl
6094 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6095
6096 if (!CtorDecl) return;
6097
6098 // Compute the exception specification for the default constructor.
6099 const FunctionProtoType *CtorTy =
6100 CtorDecl->getType()->castAs<FunctionProtoType>();
6101 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6102 ImplicitExceptionSpecification Spec =
6103 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6104 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6105 assert(EPI.ExceptionSpecType != EST_Delayed);
6106
6107 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6108 }
6109
6110 // If the default constructor is explicitly defaulted, checking the exception
6111 // specification is deferred until now.
6112 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6113 !ClassDecl->isDependentType())
6114 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6115}
6116
Sebastian Redlf677ea32011-02-05 19:23:19 +00006117void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6118 // We start with an initial pass over the base classes to collect those that
6119 // inherit constructors from. If there are none, we can forgo all further
6120 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006121 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006122 BasesVector BasesToInheritFrom;
6123 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6124 BaseE = ClassDecl->bases_end();
6125 BaseIt != BaseE; ++BaseIt) {
6126 if (BaseIt->getInheritConstructors()) {
6127 QualType Base = BaseIt->getType();
6128 if (Base->isDependentType()) {
6129 // If we inherit constructors from anything that is dependent, just
6130 // abort processing altogether. We'll get another chance for the
6131 // instantiations.
6132 return;
6133 }
6134 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6135 }
6136 }
6137 if (BasesToInheritFrom.empty())
6138 return;
6139
6140 // Now collect the constructors that we already have in the current class.
6141 // Those take precedence over inherited constructors.
6142 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6143 // unless there is a user-declared constructor with the same signature in
6144 // the class where the using-declaration appears.
6145 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6146 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6147 CtorE = ClassDecl->ctor_end();
6148 CtorIt != CtorE; ++CtorIt) {
6149 ExistingConstructors.insert(
6150 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6151 }
6152
6153 Scope *S = getScopeForContext(ClassDecl);
6154 DeclarationName CreatedCtorName =
6155 Context.DeclarationNames.getCXXConstructorName(
6156 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6157
6158 // Now comes the true work.
6159 // First, we keep a map from constructor types to the base that introduced
6160 // them. Needed for finding conflicting constructors. We also keep the
6161 // actually inserted declarations in there, for pretty diagnostics.
6162 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6163 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6164 ConstructorToSourceMap InheritedConstructors;
6165 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6166 BaseE = BasesToInheritFrom.end();
6167 BaseIt != BaseE; ++BaseIt) {
6168 const RecordType *Base = *BaseIt;
6169 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6170 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6171 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6172 CtorE = BaseDecl->ctor_end();
6173 CtorIt != CtorE; ++CtorIt) {
6174 // Find the using declaration for inheriting this base's constructors.
6175 DeclarationName Name =
6176 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6177 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6178 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6179 SourceLocation UsingLoc = UD ? UD->getLocation() :
6180 ClassDecl->getLocation();
6181
6182 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6183 // from the class X named in the using-declaration consists of actual
6184 // constructors and notional constructors that result from the
6185 // transformation of defaulted parameters as follows:
6186 // - all non-template default constructors of X, and
6187 // - for each non-template constructor of X that has at least one
6188 // parameter with a default argument, the set of constructors that
6189 // results from omitting any ellipsis parameter specification and
6190 // successively omitting parameters with a default argument from the
6191 // end of the parameter-type-list.
6192 CXXConstructorDecl *BaseCtor = *CtorIt;
6193 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6194 const FunctionProtoType *BaseCtorType =
6195 BaseCtor->getType()->getAs<FunctionProtoType>();
6196
6197 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6198 maxParams = BaseCtor->getNumParams();
6199 params <= maxParams; ++params) {
6200 // Skip default constructors. They're never inherited.
6201 if (params == 0)
6202 continue;
6203 // Skip copy and move constructors for the same reason.
6204 if (CanBeCopyOrMove && params == 1)
6205 continue;
6206
6207 // Build up a function type for this particular constructor.
6208 // FIXME: The working paper does not consider that the exception spec
6209 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006210 // source. This code doesn't yet, either. When it does, this code will
6211 // need to be delayed until after exception specifications and in-class
6212 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006213 const Type *NewCtorType;
6214 if (params == maxParams)
6215 NewCtorType = BaseCtorType;
6216 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006217 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006218 for (unsigned i = 0; i < params; ++i) {
6219 Args.push_back(BaseCtorType->getArgType(i));
6220 }
6221 FunctionProtoType::ExtProtoInfo ExtInfo =
6222 BaseCtorType->getExtProtoInfo();
6223 ExtInfo.Variadic = false;
6224 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6225 Args.data(), params, ExtInfo)
6226 .getTypePtr();
6227 }
6228 const Type *CanonicalNewCtorType =
6229 Context.getCanonicalType(NewCtorType);
6230
6231 // Now that we have the type, first check if the class already has a
6232 // constructor with this signature.
6233 if (ExistingConstructors.count(CanonicalNewCtorType))
6234 continue;
6235
6236 // Then we check if we have already declared an inherited constructor
6237 // with this signature.
6238 std::pair<ConstructorToSourceMap::iterator, bool> result =
6239 InheritedConstructors.insert(std::make_pair(
6240 CanonicalNewCtorType,
6241 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6242 if (!result.second) {
6243 // Already in the map. If it came from a different class, that's an
6244 // error. Not if it's from the same.
6245 CanQualType PreviousBase = result.first->second.first;
6246 if (CanonicalBase != PreviousBase) {
6247 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6248 const CXXConstructorDecl *PrevBaseCtor =
6249 PrevCtor->getInheritedConstructor();
6250 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6251
6252 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6253 Diag(BaseCtor->getLocation(),
6254 diag::note_using_decl_constructor_conflict_current_ctor);
6255 Diag(PrevBaseCtor->getLocation(),
6256 diag::note_using_decl_constructor_conflict_previous_ctor);
6257 Diag(PrevCtor->getLocation(),
6258 diag::note_using_decl_constructor_conflict_previous_using);
6259 }
6260 continue;
6261 }
6262
6263 // OK, we're there, now add the constructor.
6264 // C++0x [class.inhctor]p8: [...] that would be performed by a
6265 // user-writtern inline constructor [...]
6266 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6267 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006268 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6269 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006270 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006271 NewCtor->setAccess(BaseCtor->getAccess());
6272
6273 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006274 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006275 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006276 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6277 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006278 /*IdentifierInfo=*/0,
6279 BaseCtorType->getArgType(i),
6280 /*TInfo=*/0, SC_None,
6281 SC_None, /*DefaultArg=*/0));
6282 }
6283 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6284 NewCtor->setInheritedConstructor(BaseCtor);
6285
6286 PushOnScopeChains(NewCtor, S, false);
6287 ClassDecl->addDecl(NewCtor);
6288 result.first->second.second = NewCtor;
6289 }
6290 }
6291 }
6292}
6293
Sean Huntcb45a0f2011-05-12 22:46:25 +00006294Sema::ImplicitExceptionSpecification
6295Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006296 // C++ [except.spec]p14:
6297 // An implicitly declared special member function (Clause 12) shall have
6298 // an exception-specification.
6299 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006300 if (ClassDecl->isInvalidDecl())
6301 return ExceptSpec;
6302
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006303 // Direct base-class destructors.
6304 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6305 BEnd = ClassDecl->bases_end();
6306 B != BEnd; ++B) {
6307 if (B->isVirtual()) // Handled below.
6308 continue;
6309
6310 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6311 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006312 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006313 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006314
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006315 // Virtual base-class destructors.
6316 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6317 BEnd = ClassDecl->vbases_end();
6318 B != BEnd; ++B) {
6319 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6320 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006321 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006322 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006323
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006324 // Field destructors.
6325 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6326 FEnd = ClassDecl->field_end();
6327 F != FEnd; ++F) {
6328 if (const RecordType *RecordTy
6329 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6330 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006331 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006332 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006333
Sean Huntcb45a0f2011-05-12 22:46:25 +00006334 return ExceptSpec;
6335}
6336
6337CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6338 // C++ [class.dtor]p2:
6339 // If a class has no user-declared destructor, a destructor is
6340 // declared implicitly. An implicitly-declared destructor is an
6341 // inline public member of its class.
6342
6343 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006344 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006345 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6346
Douglas Gregor4923aa22010-07-02 20:37:36 +00006347 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006348 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006349
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006350 CanQualType ClassType
6351 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006352 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006353 DeclarationName Name
6354 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006355 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006356 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006357 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6358 /*isInline=*/true,
6359 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006360 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006361 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006362 Destructor->setImplicit();
6363 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006364
6365 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006366 ++ASTContext::NumImplicitDestructorsDeclared;
6367
6368 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006369 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006370 PushOnScopeChains(Destructor, S, false);
6371 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006372
6373 // This could be uniqued if it ever proves significant.
6374 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006375
6376 if (ShouldDeleteDestructor(Destructor))
6377 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006378
6379 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006380
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006381 return Destructor;
6382}
6383
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006384void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006385 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006386 assert((Destructor->isDefaulted() &&
6387 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006388 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006389 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006390 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006391
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006392 if (Destructor->isInvalidDecl())
6393 return;
6394
Douglas Gregor39957dc2010-05-01 15:04:51 +00006395 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006396
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006397 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006398 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6399 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006400
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006401 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006402 Diag(CurrentLocation, diag::note_member_synthesized_at)
6403 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6404
6405 Destructor->setInvalidDecl();
6406 return;
6407 }
6408
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006409 SourceLocation Loc = Destructor->getLocation();
6410 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6411
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006412 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006413 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006414
6415 if (ASTMutationListener *L = getASTMutationListener()) {
6416 L->CompletedImplicitDefinition(Destructor);
6417 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006418}
6419
Sebastian Redl0ee33912011-05-19 05:13:44 +00006420void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6421 CXXDestructorDecl *destructor) {
6422 // C++11 [class.dtor]p3:
6423 // A declaration of a destructor that does not have an exception-
6424 // specification is implicitly considered to have the same exception-
6425 // specification as an implicit declaration.
6426 const FunctionProtoType *dtorType = destructor->getType()->
6427 getAs<FunctionProtoType>();
6428 if (dtorType->hasExceptionSpec())
6429 return;
6430
6431 ImplicitExceptionSpecification exceptSpec =
6432 ComputeDefaultedDtorExceptionSpec(classDecl);
6433
6434 // Replace the destructor's type.
6435 FunctionProtoType::ExtProtoInfo epi;
6436 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6437 epi.NumExceptions = exceptSpec.size();
6438 epi.Exceptions = exceptSpec.data();
6439 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6440
6441 destructor->setType(ty);
6442
6443 // FIXME: If the destructor has a body that could throw, and the newly created
6444 // spec doesn't allow exceptions, we should emit a warning, because this
6445 // change in behavior can break conforming C++03 programs at runtime.
6446 // However, we don't have a body yet, so it needs to be done somewhere else.
6447}
6448
Douglas Gregor06a9f362010-05-01 20:49:11 +00006449/// \brief Builds a statement that copies the given entity from \p From to
6450/// \c To.
6451///
6452/// This routine is used to copy the members of a class with an
6453/// implicitly-declared copy assignment operator. When the entities being
6454/// copied are arrays, this routine builds for loops to copy them.
6455///
6456/// \param S The Sema object used for type-checking.
6457///
6458/// \param Loc The location where the implicit copy is being generated.
6459///
6460/// \param T The type of the expressions being copied. Both expressions must
6461/// have this type.
6462///
6463/// \param To The expression we are copying to.
6464///
6465/// \param From The expression we are copying from.
6466///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006467/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6468/// Otherwise, it's a non-static member subobject.
6469///
Douglas Gregor06a9f362010-05-01 20:49:11 +00006470/// \param Depth Internal parameter recording the depth of the recursion.
6471///
6472/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006473static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00006474BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00006475 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006476 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006477 // C++0x [class.copy]p30:
6478 // Each subobject is assigned in the manner appropriate to its type:
6479 //
6480 // - if the subobject is of class type, the copy assignment operator
6481 // for the class is used (as if by explicit qualification; that is,
6482 // ignoring any possible virtual overriding functions in more derived
6483 // classes);
6484 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6485 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6486
6487 // Look for operator=.
6488 DeclarationName Name
6489 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6490 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6491 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6492
6493 // Filter out any result that isn't a copy-assignment operator.
6494 LookupResult::Filter F = OpLookup.makeFilter();
6495 while (F.hasNext()) {
6496 NamedDecl *D = F.next();
6497 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6498 if (Method->isCopyAssignmentOperator())
6499 continue;
6500
6501 F.erase();
John McCallb0207482010-03-16 06:11:48 +00006502 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006503 F.done();
6504
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006505 // Suppress the protected check (C++ [class.protected]) for each of the
6506 // assignment operators we found. This strange dance is required when
6507 // we're assigning via a base classes's copy-assignment operator. To
6508 // ensure that we're getting the right base class subobject (without
6509 // ambiguities), we need to cast "this" to that subobject type; to
6510 // ensure that we don't go through the virtual call mechanism, we need
6511 // to qualify the operator= name with the base class (see below). However,
6512 // this means that if the base class has a protected copy assignment
6513 // operator, the protected member access check will fail. So, we
6514 // rewrite "protected" access to "public" access in this case, since we
6515 // know by construction that we're calling from a derived class.
6516 if (CopyingBaseSubobject) {
6517 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6518 L != LEnd; ++L) {
6519 if (L.getAccess() == AS_protected)
6520 L.setAccess(AS_public);
6521 }
6522 }
6523
Douglas Gregor06a9f362010-05-01 20:49:11 +00006524 // Create the nested-name-specifier that will be used to qualify the
6525 // reference to operator=; this is required to suppress the virtual
6526 // call mechanism.
6527 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00006528 SS.MakeTrivial(S.Context,
6529 NestedNameSpecifier::Create(S.Context, 0, false,
6530 T.getTypePtr()),
6531 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006532
6533 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00006534 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00006535 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006536 /*FirstQualifierInScope=*/0, OpLookup,
6537 /*TemplateArgs=*/0,
6538 /*SuppressQualifierCheck=*/true);
6539 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006540 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006541
6542 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00006543
John McCall60d7b3a2010-08-24 06:29:42 +00006544 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00006545 OpEqualRef.takeAs<Expr>(),
6546 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006547 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006548 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006549
6550 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006551 }
John McCallb0207482010-03-16 06:11:48 +00006552
Douglas Gregor06a9f362010-05-01 20:49:11 +00006553 // - if the subobject is of scalar type, the built-in assignment
6554 // operator is used.
6555 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6556 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00006557 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006558 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006559 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006560
6561 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006562 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006563
6564 // - if the subobject is an array, each element is assigned, in the
6565 // manner appropriate to the element type;
6566
6567 // Construct a loop over the array bounds, e.g.,
6568 //
6569 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6570 //
6571 // that will copy each of the array elements.
6572 QualType SizeType = S.Context.getSizeType();
6573
6574 // Create the iteration variable.
6575 IdentifierInfo *IterationVarName = 0;
6576 {
6577 llvm::SmallString<8> Str;
6578 llvm::raw_svector_ostream OS(Str);
6579 OS << "__i" << Depth;
6580 IterationVarName = &S.Context.Idents.get(OS.str());
6581 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006582 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006583 IterationVarName, SizeType,
6584 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00006585 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006586
6587 // Initialize the iteration variable to zero.
6588 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006589 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006590
6591 // Create a reference to the iteration variable; we'll use this several
6592 // times throughout.
6593 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00006594 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006595 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6596
6597 // Create the DeclStmt that holds the iteration variable.
6598 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6599
6600 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006601 llvm::APInt Upper
6602 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00006603 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00006604 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00006605 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6606 BO_NE, S.Context.BoolTy,
6607 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006608
6609 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006610 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00006611 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6612 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006613
6614 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006615 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6616 IterationVarRef, Loc));
6617 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6618 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006619
6620 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00006621 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6622 To, From, CopyingBaseSubobject,
6623 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00006624 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006625 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006626
6627 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00006628 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006629 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00006630 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00006631 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006632}
6633
Sean Hunt30de05c2011-05-14 05:23:20 +00006634std::pair<Sema::ImplicitExceptionSpecification, bool>
6635Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6636 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006637 if (ClassDecl->isInvalidDecl())
6638 return std::make_pair(ImplicitExceptionSpecification(Context), false);
6639
Douglas Gregord3c35902010-07-01 16:36:15 +00006640 // C++ [class.copy]p10:
6641 // If the class definition does not explicitly declare a copy
6642 // assignment operator, one is declared implicitly.
6643 // The implicitly-defined copy assignment operator for a class X
6644 // will have the form
6645 //
6646 // X& X::operator=(const X&)
6647 //
6648 // if
6649 bool HasConstCopyAssignment = true;
6650
6651 // -- each direct base class B of X has a copy assignment operator
6652 // whose parameter is of type const B&, const volatile B& or B,
6653 // and
6654 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6655 BaseEnd = ClassDecl->bases_end();
6656 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00006657 // We'll handle this below
6658 if (LangOpts.CPlusPlus0x && Base->isVirtual())
6659 continue;
6660
Douglas Gregord3c35902010-07-01 16:36:15 +00006661 assert(!Base->getType()->isDependentType() &&
6662 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00006663 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6664 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6665 &HasConstCopyAssignment);
6666 }
6667
6668 // In C++0x, the above citation has "or virtual added"
6669 if (LangOpts.CPlusPlus0x) {
6670 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6671 BaseEnd = ClassDecl->vbases_end();
6672 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6673 assert(!Base->getType()->isDependentType() &&
6674 "Cannot generate implicit members for class with dependent bases.");
6675 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6676 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6677 &HasConstCopyAssignment);
6678 }
Douglas Gregord3c35902010-07-01 16:36:15 +00006679 }
6680
6681 // -- for all the nonstatic data members of X that are of a class
6682 // type M (or array thereof), each such class type has a copy
6683 // assignment operator whose parameter is of type const M&,
6684 // const volatile M& or M.
6685 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6686 FieldEnd = ClassDecl->field_end();
6687 HasConstCopyAssignment && Field != FieldEnd;
6688 ++Field) {
6689 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00006690 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6691 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
6692 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006693 }
6694 }
6695
6696 // Otherwise, the implicitly declared copy assignment operator will
6697 // have the form
6698 //
6699 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00006700
Douglas Gregorb87786f2010-07-01 17:48:08 +00006701 // C++ [except.spec]p14:
6702 // An implicitly declared special member function (Clause 12) shall have an
6703 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00006704
6705 // It is unspecified whether or not an implicit copy assignment operator
6706 // attempts to deduplicate calls to assignment operators of virtual bases are
6707 // made. As such, this exception specification is effectively unspecified.
6708 // Based on a similar decision made for constness in C++0x, we're erring on
6709 // the side of assuming such calls to be made regardless of whether they
6710 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00006711 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00006712 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00006713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6714 BaseEnd = ClassDecl->bases_end();
6715 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00006716 if (Base->isVirtual())
6717 continue;
6718
Douglas Gregora376d102010-07-02 21:50:04 +00006719 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006720 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00006721 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6722 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00006723 ExceptSpec.CalledDecl(CopyAssign);
6724 }
Sean Hunt661c67a2011-06-21 23:42:56 +00006725
6726 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6727 BaseEnd = ClassDecl->vbases_end();
6728 Base != BaseEnd; ++Base) {
6729 CXXRecordDecl *BaseClassDecl
6730 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6731 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6732 ArgQuals, false, 0))
6733 ExceptSpec.CalledDecl(CopyAssign);
6734 }
6735
Douglas Gregorb87786f2010-07-01 17:48:08 +00006736 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6737 FieldEnd = ClassDecl->field_end();
6738 Field != FieldEnd;
6739 ++Field) {
6740 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00006741 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6742 if (CXXMethodDecl *CopyAssign =
6743 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
6744 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006745 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00006746 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006747
Sean Hunt30de05c2011-05-14 05:23:20 +00006748 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6749}
6750
6751CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6752 // Note: The following rules are largely analoguous to the copy
6753 // constructor rules. Note that virtual bases are not taken into account
6754 // for determining the argument type of the operator. Note also that
6755 // operators taking an object instead of a reference are allowed.
6756
6757 ImplicitExceptionSpecification Spec(Context);
6758 bool Const;
6759 llvm::tie(Spec, Const) =
6760 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6761
6762 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6763 QualType RetType = Context.getLValueReferenceType(ArgType);
6764 if (Const)
6765 ArgType = ArgType.withConst();
6766 ArgType = Context.getLValueReferenceType(ArgType);
6767
Douglas Gregord3c35902010-07-01 16:36:15 +00006768 // An implicitly-declared copy assignment operator is an inline public
6769 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00006770 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00006771 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006772 SourceLocation ClassLoc = ClassDecl->getLocation();
6773 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00006774 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006775 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00006776 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00006777 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00006778 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00006779 /*isInline=*/true,
6780 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00006781 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00006782 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00006783 CopyAssignment->setImplicit();
6784 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00006785
6786 // Add the parameter to the operator.
6787 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006788 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00006789 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006790 SC_None,
6791 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00006792 CopyAssignment->setParams(&FromParam, 1);
6793
Douglas Gregora376d102010-07-02 21:50:04 +00006794 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00006795 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00006796
Douglas Gregor23c94db2010-07-02 17:43:08 +00006797 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00006798 PushOnScopeChains(CopyAssignment, S, false);
6799 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006800
Sean Hunt1ccbc542011-06-22 01:05:13 +00006801 // C++0x [class.copy]p18:
6802 // ... If the class definition declares a move constructor or move
6803 // assignment operator, the implicitly declared copy assignment operator is
6804 // defined as deleted; ...
6805 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
6806 ClassDecl->hasUserDeclaredMoveAssignment() ||
6807 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00006808 CopyAssignment->setDeletedAsWritten();
6809
Douglas Gregord3c35902010-07-01 16:36:15 +00006810 AddOverriddenMethods(ClassDecl, CopyAssignment);
6811 return CopyAssignment;
6812}
6813
Douglas Gregor06a9f362010-05-01 20:49:11 +00006814void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6815 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00006816 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006817 CopyAssignOperator->isOverloadedOperator() &&
6818 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006819 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006820 "DefineImplicitCopyAssignment called for wrong function");
6821
6822 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6823
6824 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6825 CopyAssignOperator->setInvalidDecl();
6826 return;
6827 }
6828
6829 CopyAssignOperator->setUsed();
6830
6831 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006832 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006833
6834 // C++0x [class.copy]p30:
6835 // The implicitly-defined or explicitly-defaulted copy assignment operator
6836 // for a non-union class X performs memberwise copy assignment of its
6837 // subobjects. The direct base classes of X are assigned first, in the
6838 // order of their declaration in the base-specifier-list, and then the
6839 // immediate non-static data members of X are assigned, in the order in
6840 // which they were declared in the class definition.
6841
6842 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00006843 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006844
6845 // The parameter for the "other" object, which we are copying from.
6846 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6847 Qualifiers OtherQuals = Other->getType().getQualifiers();
6848 QualType OtherRefType = Other->getType();
6849 if (const LValueReferenceType *OtherRef
6850 = OtherRefType->getAs<LValueReferenceType>()) {
6851 OtherRefType = OtherRef->getPointeeType();
6852 OtherQuals = OtherRefType.getQualifiers();
6853 }
6854
6855 // Our location for everything implicitly-generated.
6856 SourceLocation Loc = CopyAssignOperator->getLocation();
6857
6858 // Construct a reference to the "other" object. We'll be using this
6859 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00006860 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006861 assert(OtherRef && "Reference to parameter cannot fail!");
6862
6863 // Construct the "this" pointer. We'll be using this throughout the generated
6864 // ASTs.
6865 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6866 assert(This && "Reference to this cannot fail!");
6867
6868 // Assign base classes.
6869 bool Invalid = false;
6870 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6871 E = ClassDecl->bases_end(); Base != E; ++Base) {
6872 // Form the assignment:
6873 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6874 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00006875 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006876 Invalid = true;
6877 continue;
6878 }
6879
John McCallf871d0c2010-08-07 06:22:56 +00006880 CXXCastPath BasePath;
6881 BasePath.push_back(Base);
6882
Douglas Gregor06a9f362010-05-01 20:49:11 +00006883 // Construct the "from" expression, which is an implicit cast to the
6884 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00006885 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00006886 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6887 CK_UncheckedDerivedToBase,
6888 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006889
6890 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00006891 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006892
6893 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00006894 To = ImpCastExprToType(To.take(),
6895 Context.getCVRQualifiedType(BaseType,
6896 CopyAssignOperator->getTypeQualifiers()),
6897 CK_UncheckedDerivedToBase,
6898 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006899
6900 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00006901 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00006902 To.get(), From,
6903 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006904 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006905 Diag(CurrentLocation, diag::note_member_synthesized_at)
6906 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6907 CopyAssignOperator->setInvalidDecl();
6908 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006909 }
6910
6911 // Success! Record the copy.
6912 Statements.push_back(Copy.takeAs<Expr>());
6913 }
6914
6915 // \brief Reference to the __builtin_memcpy function.
6916 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006917 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006918 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006919
6920 // Assign non-static members.
6921 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6922 FieldEnd = ClassDecl->field_end();
6923 Field != FieldEnd; ++Field) {
6924 // Check for members of reference type; we can't copy those.
6925 if (Field->getType()->isReferenceType()) {
6926 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6927 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6928 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006929 Diag(CurrentLocation, diag::note_member_synthesized_at)
6930 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006931 Invalid = true;
6932 continue;
6933 }
6934
6935 // Check for members of const-qualified, non-class type.
6936 QualType BaseType = Context.getBaseElementType(Field->getType());
6937 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6938 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6939 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6940 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006941 Diag(CurrentLocation, diag::note_member_synthesized_at)
6942 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006943 Invalid = true;
6944 continue;
6945 }
John McCallb77115d2011-06-17 00:18:42 +00006946
6947 // Suppress assigning zero-width bitfields.
6948 if (const Expr *Width = Field->getBitWidth())
6949 if (Width->EvaluateAsInt(Context) == 0)
6950 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006951
6952 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006953 if (FieldType->isIncompleteArrayType()) {
6954 assert(ClassDecl->hasFlexibleArrayMember() &&
6955 "Incomplete array type is not valid");
6956 continue;
6957 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006958
6959 // Build references to the field in the object we're copying from and to.
6960 CXXScopeSpec SS; // Intentionally empty
6961 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6962 LookupMemberName);
6963 MemberLookup.addDecl(*Field);
6964 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00006965 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00006966 Loc, /*IsArrow=*/false,
6967 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006968 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00006969 Loc, /*IsArrow=*/true,
6970 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006971 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6972 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6973
6974 // If the field should be copied with __builtin_memcpy rather than via
6975 // explicit assignments, do so. This optimization only applies for arrays
6976 // of scalars and arrays of class type with trivial copy-assignment
6977 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00006978 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
6979 && BaseType.hasTrivialCopyAssignment(Context)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006980 // Compute the size of the memory buffer to be copied.
6981 QualType SizeType = Context.getSizeType();
6982 llvm::APInt Size(Context.getTypeSize(SizeType),
6983 Context.getTypeSizeInChars(BaseType).getQuantity());
6984 for (const ConstantArrayType *Array
6985 = Context.getAsConstantArrayType(FieldType);
6986 Array;
6987 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00006988 llvm::APInt ArraySize
6989 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006990 Size *= ArraySize;
6991 }
6992
6993 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00006994 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6995 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006996
6997 bool NeedsCollectableMemCpy =
6998 (BaseType->isRecordType() &&
6999 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7000
7001 if (NeedsCollectableMemCpy) {
7002 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007003 // Create a reference to the __builtin_objc_memmove_collectable function.
7004 LookupResult R(*this,
7005 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007006 Loc, LookupOrdinaryName);
7007 LookupName(R, TUScope, true);
7008
7009 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7010 if (!CollectableMemCpy) {
7011 // Something went horribly wrong earlier, and we will have
7012 // complained about it.
7013 Invalid = true;
7014 continue;
7015 }
7016
7017 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7018 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007019 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007020 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7021 }
7022 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007023 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007024 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007025 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7026 LookupOrdinaryName);
7027 LookupName(R, TUScope, true);
7028
7029 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7030 if (!BuiltinMemCpy) {
7031 // Something went horribly wrong earlier, and we will have complained
7032 // about it.
7033 Invalid = true;
7034 continue;
7035 }
7036
7037 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7038 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007039 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007040 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7041 }
7042
John McCallca0408f2010-08-23 06:44:23 +00007043 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007044 CallArgs.push_back(To.takeAs<Expr>());
7045 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007046 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007047 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007048 if (NeedsCollectableMemCpy)
7049 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007050 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007051 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007052 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007053 else
7054 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007055 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007056 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007057 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007058
Douglas Gregor06a9f362010-05-01 20:49:11 +00007059 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7060 Statements.push_back(Call.takeAs<Expr>());
7061 continue;
7062 }
7063
7064 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007065 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00007066 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007067 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007068 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007069 Diag(CurrentLocation, diag::note_member_synthesized_at)
7070 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7071 CopyAssignOperator->setInvalidDecl();
7072 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007073 }
7074
7075 // Success! Record the copy.
7076 Statements.push_back(Copy.takeAs<Stmt>());
7077 }
7078
7079 if (!Invalid) {
7080 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007081 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007082
John McCall60d7b3a2010-08-24 06:29:42 +00007083 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007084 if (Return.isInvalid())
7085 Invalid = true;
7086 else {
7087 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007088
7089 if (Trap.hasErrorOccurred()) {
7090 Diag(CurrentLocation, diag::note_member_synthesized_at)
7091 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7092 Invalid = true;
7093 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007094 }
7095 }
7096
7097 if (Invalid) {
7098 CopyAssignOperator->setInvalidDecl();
7099 return;
7100 }
7101
John McCall60d7b3a2010-08-24 06:29:42 +00007102 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007103 /*isStmtExpr=*/false);
7104 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7105 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007106
7107 if (ASTMutationListener *L = getASTMutationListener()) {
7108 L->CompletedImplicitDefinition(CopyAssignOperator);
7109 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007110}
7111
Sean Hunt49634cf2011-05-13 06:10:58 +00007112std::pair<Sema::ImplicitExceptionSpecification, bool>
7113Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007114 if (ClassDecl->isInvalidDecl())
7115 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7116
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007117 // C++ [class.copy]p5:
7118 // The implicitly-declared copy constructor for a class X will
7119 // have the form
7120 //
7121 // X::X(const X&)
7122 //
7123 // if
Sean Huntc530d172011-06-10 04:44:37 +00007124 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007125 bool HasConstCopyConstructor = true;
7126
7127 // -- each direct or virtual base class B of X has a copy
7128 // constructor whose first parameter is of type const B& or
7129 // const volatile B&, and
7130 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7131 BaseEnd = ClassDecl->bases_end();
7132 HasConstCopyConstructor && Base != BaseEnd;
7133 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007134 // Virtual bases are handled below.
7135 if (Base->isVirtual())
7136 continue;
7137
Douglas Gregor22584312010-07-02 23:41:54 +00007138 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00007139 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007140 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7141 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00007142 }
7143
7144 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7145 BaseEnd = ClassDecl->vbases_end();
7146 HasConstCopyConstructor && Base != BaseEnd;
7147 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007148 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007149 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007150 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7151 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007152 }
7153
7154 // -- for all the nonstatic data members of X that are of a
7155 // class type M (or array thereof), each such class type
7156 // has a copy constructor whose first parameter is of type
7157 // const M& or const volatile M&.
7158 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7159 FieldEnd = ClassDecl->field_end();
7160 HasConstCopyConstructor && Field != FieldEnd;
7161 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007162 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007163 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007164 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
7165 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007166 }
7167 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007168 // Otherwise, the implicitly declared copy constructor will have
7169 // the form
7170 //
7171 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00007172
Douglas Gregor0d405db2010-07-01 20:59:04 +00007173 // C++ [except.spec]p14:
7174 // An implicitly declared special member function (Clause 12) shall have an
7175 // exception-specification. [...]
7176 ImplicitExceptionSpecification ExceptSpec(Context);
7177 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7178 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7179 BaseEnd = ClassDecl->bases_end();
7180 Base != BaseEnd;
7181 ++Base) {
7182 // Virtual bases are handled below.
7183 if (Base->isVirtual())
7184 continue;
7185
Douglas Gregor22584312010-07-02 23:41:54 +00007186 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007187 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007188 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00007189 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007190 ExceptSpec.CalledDecl(CopyConstructor);
7191 }
7192 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7193 BaseEnd = ClassDecl->vbases_end();
7194 Base != BaseEnd;
7195 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007196 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007197 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007198 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00007199 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007200 ExceptSpec.CalledDecl(CopyConstructor);
7201 }
7202 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7203 FieldEnd = ClassDecl->field_end();
7204 Field != FieldEnd;
7205 ++Field) {
7206 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007207 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7208 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00007209 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00007210 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00007211 }
7212 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007213
Sean Hunt49634cf2011-05-13 06:10:58 +00007214 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7215}
7216
7217CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7218 CXXRecordDecl *ClassDecl) {
7219 // C++ [class.copy]p4:
7220 // If the class definition does not explicitly declare a copy
7221 // constructor, one is declared implicitly.
7222
7223 ImplicitExceptionSpecification Spec(Context);
7224 bool Const;
7225 llvm::tie(Spec, Const) =
7226 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7227
7228 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7229 QualType ArgType = ClassType;
7230 if (Const)
7231 ArgType = ArgType.withConst();
7232 ArgType = Context.getLValueReferenceType(ArgType);
7233
7234 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7235
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007236 DeclarationName Name
7237 = Context.DeclarationNames.getCXXConstructorName(
7238 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007239 SourceLocation ClassLoc = ClassDecl->getLocation();
7240 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00007241
7242 // An implicitly-declared copy constructor is an inline public
7243 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007244 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007245 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007246 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00007247 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007248 /*TInfo=*/0,
7249 /*isExplicit=*/false,
7250 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00007251 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007252 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00007253 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007254 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7255
Douglas Gregor22584312010-07-02 23:41:54 +00007256 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00007257 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7258
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007259 // Add the parameter to the constructor.
7260 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007261 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007262 /*IdentifierInfo=*/0,
7263 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007264 SC_None,
7265 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007266 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00007267
Douglas Gregor23c94db2010-07-02 17:43:08 +00007268 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00007269 PushOnScopeChains(CopyConstructor, S, false);
7270 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00007271
Sean Hunt1ccbc542011-06-22 01:05:13 +00007272 // C++0x [class.copy]p7:
7273 // ... If the class definition declares a move constructor or move
7274 // assignment operator, the implicitly declared constructor is defined as
7275 // deleted; ...
7276 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7277 ClassDecl->hasUserDeclaredMoveAssignment() ||
7278 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007279 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007280
7281 return CopyConstructor;
7282}
7283
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007284void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00007285 CXXConstructorDecl *CopyConstructor) {
7286 assert((CopyConstructor->isDefaulted() &&
7287 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007288 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007289 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007290
Anders Carlsson63010a72010-04-23 16:24:12 +00007291 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007292 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007293
Douglas Gregor39957dc2010-05-01 15:04:51 +00007294 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007295 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007296
Sean Huntcbb67482011-01-08 20:30:50 +00007297 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007298 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00007299 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007300 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00007301 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007302 } else {
7303 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7304 CopyConstructor->getLocation(),
7305 MultiStmtArg(*this, 0, 0),
7306 /*isStmtExpr=*/false)
7307 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00007308 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007309
7310 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007311
7312 if (ASTMutationListener *L = getASTMutationListener()) {
7313 L->CompletedImplicitDefinition(CopyConstructor);
7314 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007315}
7316
John McCall60d7b3a2010-08-24 06:29:42 +00007317ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007318Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00007319 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00007320 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007321 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007322 unsigned ConstructKind,
7323 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007324 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00007325
Douglas Gregor2f599792010-04-02 18:24:57 +00007326 // C++0x [class.copy]p34:
7327 // When certain criteria are met, an implementation is allowed to
7328 // omit the copy/move construction of a class object, even if the
7329 // copy/move constructor and/or destructor for the object have
7330 // side effects. [...]
7331 // - when a temporary class object that has not been bound to a
7332 // reference (12.2) would be copied/moved to a class object
7333 // with the same cv-unqualified type, the copy/move operation
7334 // can be omitted by constructing the temporary object
7335 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00007336 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00007337 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00007338 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00007339 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007340 }
Mike Stump1eb44332009-09-09 15:08:12 +00007341
7342 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007343 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007344 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007345}
7346
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007347/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7348/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007349ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007350Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7351 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00007352 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007353 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007354 unsigned ConstructKind,
7355 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00007356 unsigned NumExprs = ExprArgs.size();
7357 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00007358
Nick Lewycky909a70d2011-03-25 01:44:32 +00007359 for (specific_attr_iterator<NonNullAttr>
7360 i = Constructor->specific_attr_begin<NonNullAttr>(),
7361 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7362 const NonNullAttr *NonNull = *i;
7363 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7364 }
7365
Douglas Gregor7edfb692009-11-23 12:27:39 +00007366 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00007367 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00007368 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00007369 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007370 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7371 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007372}
7373
Mike Stump1eb44332009-09-09 15:08:12 +00007374bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007375 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00007376 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00007377 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00007378 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00007379 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007380 move(Exprs), false, CXXConstructExpr::CK_Complete,
7381 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00007382 if (TempResult.isInvalid())
7383 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007384
Anders Carlssonda3f4e22009-08-25 05:12:04 +00007385 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00007386 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007387 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00007388 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00007389 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00007390
Anders Carlssonfe2de492009-08-25 05:18:00 +00007391 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00007392}
7393
John McCall68c6c9a2010-02-02 09:10:11 +00007394void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007395 if (VD->isInvalidDecl()) return;
7396
John McCall68c6c9a2010-02-02 09:10:11 +00007397 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007398 if (ClassDecl->isInvalidDecl()) return;
7399 if (ClassDecl->hasTrivialDestructor()) return;
7400 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00007401
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007402 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7403 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7404 CheckDestructorAccess(VD->getLocation(), Destructor,
7405 PDiag(diag::err_access_dtor_var)
7406 << VD->getDeclName()
7407 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00007408
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007409 if (!VD->hasGlobalStorage()) return;
7410
7411 // Emit warning for non-trivial dtor in global scope (a real global,
7412 // class-static, function-static).
7413 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7414
7415 // TODO: this should be re-enabled for static locals by !CXAAtExit
7416 if (!VD->isStaticLocal())
7417 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007418}
7419
Mike Stump1eb44332009-09-09 15:08:12 +00007420/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007421/// ActOnDeclarator, when a C++ direct initializer is present.
7422/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00007423void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007424 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007425 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00007426 SourceLocation RParenLoc,
7427 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00007428 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007429
7430 // If there is no declaration, there was an error parsing it. Just ignore
7431 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00007432 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007433 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007434
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007435 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7436 if (!VDecl) {
7437 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7438 RealDecl->setInvalidDecl();
7439 return;
7440 }
7441
Richard Smith34b41d92011-02-20 03:19:35 +00007442 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7443 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00007444 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7445 if (Exprs.size() > 1) {
7446 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7447 diag::err_auto_var_init_multiple_expressions)
7448 << VDecl->getDeclName() << VDecl->getType()
7449 << VDecl->getSourceRange();
7450 RealDecl->setInvalidDecl();
7451 return;
7452 }
7453
7454 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00007455 TypeSourceInfo *DeducedType = 0;
7456 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00007457 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7458 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7459 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00007460 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00007461 RealDecl->setInvalidDecl();
7462 return;
7463 }
Richard Smitha085da82011-03-17 16:11:59 +00007464 VDecl->setTypeSourceInfo(DeducedType);
7465 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00007466
John McCallf85e1932011-06-15 23:02:42 +00007467 // In ARC, infer lifetime.
7468 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7469 VDecl->setInvalidDecl();
7470
Richard Smith34b41d92011-02-20 03:19:35 +00007471 // If this is a redeclaration, check that the type we just deduced matches
7472 // the previously declared type.
7473 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7474 MergeVarDeclTypes(VDecl, Old);
7475 }
7476
Douglas Gregor83ddad32009-08-26 21:14:46 +00007477 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007478 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007479 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7480 //
7481 // Clients that want to distinguish between the two forms, can check for
7482 // direct initializer using VarDecl::hasCXXDirectInitializer().
7483 // A major benefit is that clients that don't particularly care about which
7484 // exactly form was it (like the CodeGen) can handle both cases without
7485 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007486
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007487 // C++ 8.5p11:
7488 // The form of initialization (using parentheses or '=') is generally
7489 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007490 // class type.
7491
Douglas Gregor4dffad62010-02-11 22:55:30 +00007492 if (!VDecl->getType()->isDependentType() &&
7493 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00007494 diag::err_typecheck_decl_incomplete_type)) {
7495 VDecl->setInvalidDecl();
7496 return;
7497 }
7498
Douglas Gregor90f93822009-12-22 22:17:25 +00007499 // The variable can not have an abstract class type.
7500 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7501 diag::err_abstract_type_in_decl,
7502 AbstractVariableType))
7503 VDecl->setInvalidDecl();
7504
Sebastian Redl31310a22010-02-01 20:16:42 +00007505 const VarDecl *Def;
7506 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00007507 Diag(VDecl->getLocation(), diag::err_redefinition)
7508 << VDecl->getDeclName();
7509 Diag(Def->getLocation(), diag::note_previous_definition);
7510 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007511 return;
7512 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00007513
Douglas Gregor3a91abf2010-08-24 05:27:49 +00007514 // C++ [class.static.data]p4
7515 // If a static data member is of const integral or const
7516 // enumeration type, its declaration in the class definition can
7517 // specify a constant-initializer which shall be an integral
7518 // constant expression (5.19). In that case, the member can appear
7519 // in integral constant expressions. The member shall still be
7520 // defined in a namespace scope if it is used in the program and the
7521 // namespace scope definition shall not contain an initializer.
7522 //
7523 // We already performed a redefinition check above, but for static
7524 // data members we also need to check whether there was an in-class
7525 // declaration with an initializer.
7526 const VarDecl* PrevInit = 0;
7527 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7528 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7529 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7530 return;
7531 }
7532
Douglas Gregora31040f2010-12-16 01:31:22 +00007533 bool IsDependent = false;
7534 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7535 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7536 VDecl->setInvalidDecl();
7537 return;
7538 }
7539
7540 if (Exprs.get()[I]->isTypeDependent())
7541 IsDependent = true;
7542 }
7543
Douglas Gregor4dffad62010-02-11 22:55:30 +00007544 // If either the declaration has a dependent type or if any of the
7545 // expressions is type-dependent, we represent the initialization
7546 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00007547 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00007548 // Let clients know that initialization was done with a direct initializer.
7549 VDecl->setCXXDirectInitializer(true);
7550
7551 // Store the initialization expressions as a ParenListExpr.
7552 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00007553 VDecl->setInit(new (Context) ParenListExpr(
7554 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
7555 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00007556 return;
7557 }
Douglas Gregor90f93822009-12-22 22:17:25 +00007558
7559 // Capture the variable that is being initialized and the style of
7560 // initialization.
7561 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7562
7563 // FIXME: Poor source location information.
7564 InitializationKind Kind
7565 = InitializationKind::CreateDirect(VDecl->getLocation(),
7566 LParenLoc, RParenLoc);
7567
7568 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00007569 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00007570 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00007571 if (Result.isInvalid()) {
7572 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007573 return;
7574 }
John McCallb4eb64d2010-10-08 02:01:28 +00007575
7576 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00007577
Douglas Gregor53c374f2010-12-07 00:41:46 +00007578 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00007579 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007580 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007581
John McCall2998d6b2011-01-19 11:48:09 +00007582 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007583}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00007584
Douglas Gregor39da0b82009-09-09 23:08:42 +00007585/// \brief Given a constructor and the set of arguments provided for the
7586/// constructor, convert the arguments and add any required default arguments
7587/// to form a proper call to this constructor.
7588///
7589/// \returns true if an error occurred, false otherwise.
7590bool
7591Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7592 MultiExprArg ArgsPtr,
7593 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00007594 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00007595 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7596 unsigned NumArgs = ArgsPtr.size();
7597 Expr **Args = (Expr **)ArgsPtr.get();
7598
7599 const FunctionProtoType *Proto
7600 = Constructor->getType()->getAs<FunctionProtoType>();
7601 assert(Proto && "Constructor without a prototype?");
7602 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00007603
7604 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007605 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00007606 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007607 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00007608 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007609
7610 VariadicCallType CallType =
7611 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007612 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007613 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7614 Proto, 0, Args, NumArgs, AllArgs,
7615 CallType);
7616 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7617 ConvertedArgs.push_back(AllArgs[i]);
7618 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00007619}
7620
Anders Carlsson20d45d22009-12-12 00:32:00 +00007621static inline bool
7622CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7623 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007624 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00007625 if (isa<NamespaceDecl>(DC)) {
7626 return SemaRef.Diag(FnDecl->getLocation(),
7627 diag::err_operator_new_delete_declared_in_namespace)
7628 << FnDecl->getDeclName();
7629 }
7630
7631 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00007632 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007633 return SemaRef.Diag(FnDecl->getLocation(),
7634 diag::err_operator_new_delete_declared_static)
7635 << FnDecl->getDeclName();
7636 }
7637
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00007638 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00007639}
7640
Anders Carlsson156c78e2009-12-13 17:53:43 +00007641static inline bool
7642CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7643 CanQualType ExpectedResultType,
7644 CanQualType ExpectedFirstParamType,
7645 unsigned DependentParamTypeDiag,
7646 unsigned InvalidParamTypeDiag) {
7647 QualType ResultType =
7648 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7649
7650 // Check that the result type is not dependent.
7651 if (ResultType->isDependentType())
7652 return SemaRef.Diag(FnDecl->getLocation(),
7653 diag::err_operator_new_delete_dependent_result_type)
7654 << FnDecl->getDeclName() << ExpectedResultType;
7655
7656 // Check that the result type is what we expect.
7657 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7658 return SemaRef.Diag(FnDecl->getLocation(),
7659 diag::err_operator_new_delete_invalid_result_type)
7660 << FnDecl->getDeclName() << ExpectedResultType;
7661
7662 // A function template must have at least 2 parameters.
7663 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7664 return SemaRef.Diag(FnDecl->getLocation(),
7665 diag::err_operator_new_delete_template_too_few_parameters)
7666 << FnDecl->getDeclName();
7667
7668 // The function decl must have at least 1 parameter.
7669 if (FnDecl->getNumParams() == 0)
7670 return SemaRef.Diag(FnDecl->getLocation(),
7671 diag::err_operator_new_delete_too_few_parameters)
7672 << FnDecl->getDeclName();
7673
7674 // Check the the first parameter type is not dependent.
7675 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7676 if (FirstParamType->isDependentType())
7677 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7678 << FnDecl->getDeclName() << ExpectedFirstParamType;
7679
7680 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00007681 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00007682 ExpectedFirstParamType)
7683 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7684 << FnDecl->getDeclName() << ExpectedFirstParamType;
7685
7686 return false;
7687}
7688
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007689static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00007690CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007691 // C++ [basic.stc.dynamic.allocation]p1:
7692 // A program is ill-formed if an allocation function is declared in a
7693 // namespace scope other than global scope or declared static in global
7694 // scope.
7695 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7696 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00007697
7698 CanQualType SizeTy =
7699 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7700
7701 // C++ [basic.stc.dynamic.allocation]p1:
7702 // The return type shall be void*. The first parameter shall have type
7703 // std::size_t.
7704 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7705 SizeTy,
7706 diag::err_operator_new_dependent_param_type,
7707 diag::err_operator_new_param_type))
7708 return true;
7709
7710 // C++ [basic.stc.dynamic.allocation]p1:
7711 // The first parameter shall not have an associated default argument.
7712 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00007713 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00007714 diag::err_operator_new_default_arg)
7715 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7716
7717 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00007718}
7719
7720static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007721CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7722 // C++ [basic.stc.dynamic.deallocation]p1:
7723 // A program is ill-formed if deallocation functions are declared in a
7724 // namespace scope other than global scope or declared static in global
7725 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00007726 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7727 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007728
7729 // C++ [basic.stc.dynamic.deallocation]p2:
7730 // Each deallocation function shall return void and its first parameter
7731 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00007732 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7733 SemaRef.Context.VoidPtrTy,
7734 diag::err_operator_delete_dependent_param_type,
7735 diag::err_operator_delete_param_type))
7736 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007737
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007738 return false;
7739}
7740
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007741/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7742/// of this overloaded operator is well-formed. If so, returns false;
7743/// otherwise, emits appropriate diagnostics and returns true.
7744bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007745 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007746 "Expected an overloaded operator declaration");
7747
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007748 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7749
Mike Stump1eb44332009-09-09 15:08:12 +00007750 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007751 // The allocation and deallocation functions, operator new,
7752 // operator new[], operator delete and operator delete[], are
7753 // described completely in 3.7.3. The attributes and restrictions
7754 // found in the rest of this subclause do not apply to them unless
7755 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00007756 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007757 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00007758
Anders Carlssona3ccda52009-12-12 00:26:23 +00007759 if (Op == OO_New || Op == OO_Array_New)
7760 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007761
7762 // C++ [over.oper]p6:
7763 // An operator function shall either be a non-static member
7764 // function or be a non-member function and have at least one
7765 // parameter whose type is a class, a reference to a class, an
7766 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007767 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7768 if (MethodDecl->isStatic())
7769 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007770 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007771 } else {
7772 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007773 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7774 ParamEnd = FnDecl->param_end();
7775 Param != ParamEnd; ++Param) {
7776 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00007777 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7778 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007779 ClassOrEnumParam = true;
7780 break;
7781 }
7782 }
7783
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007784 if (!ClassOrEnumParam)
7785 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007786 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007787 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007788 }
7789
7790 // C++ [over.oper]p8:
7791 // An operator function cannot have default arguments (8.3.6),
7792 // except where explicitly stated below.
7793 //
Mike Stump1eb44332009-09-09 15:08:12 +00007794 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007795 // (C++ [over.call]p1).
7796 if (Op != OO_Call) {
7797 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7798 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00007799 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00007800 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00007801 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00007802 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007803 }
7804 }
7805
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007806 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7807 { false, false, false }
7808#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7809 , { Unary, Binary, MemberOnly }
7810#include "clang/Basic/OperatorKinds.def"
7811 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007812
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007813 bool CanBeUnaryOperator = OperatorUses[Op][0];
7814 bool CanBeBinaryOperator = OperatorUses[Op][1];
7815 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007816
7817 // C++ [over.oper]p8:
7818 // [...] Operator functions cannot have more or fewer parameters
7819 // than the number required for the corresponding operator, as
7820 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00007821 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007822 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007823 if (Op != OO_Call &&
7824 ((NumParams == 1 && !CanBeUnaryOperator) ||
7825 (NumParams == 2 && !CanBeBinaryOperator) ||
7826 (NumParams < 1) || (NumParams > 2))) {
7827 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00007828 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007829 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007830 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007831 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007832 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007833 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007834 assert(CanBeBinaryOperator &&
7835 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00007836 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007837 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007838
Chris Lattner416e46f2008-11-21 07:57:12 +00007839 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007840 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007841 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00007842
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007843 // Overloaded operators other than operator() cannot be variadic.
7844 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00007845 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007846 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007847 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007848 }
7849
7850 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007851 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7852 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007853 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007854 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007855 }
7856
7857 // C++ [over.inc]p1:
7858 // The user-defined function called operator++ implements the
7859 // prefix and postfix ++ operator. If this function is a member
7860 // function with no parameters, or a non-member function with one
7861 // parameter of class or enumeration type, it defines the prefix
7862 // increment operator ++ for objects of that type. If the function
7863 // is a member function with one parameter (which shall be of type
7864 // int) or a non-member function with two parameters (the second
7865 // of which shall be of type int), it defines the postfix
7866 // increment operator ++ for objects of that type.
7867 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7868 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7869 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00007870 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007871 ParamIsInt = BT->getKind() == BuiltinType::Int;
7872
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007873 if (!ParamIsInt)
7874 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00007875 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00007876 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007877 }
7878
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007879 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007880}
Chris Lattner5a003a42008-12-17 07:09:26 +00007881
Sean Hunta6c058d2010-01-13 09:01:02 +00007882/// CheckLiteralOperatorDeclaration - Check whether the declaration
7883/// of this literal operator function is well-formed. If so, returns
7884/// false; otherwise, emits appropriate diagnostics and returns true.
7885bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7886 DeclContext *DC = FnDecl->getDeclContext();
7887 Decl::Kind Kind = DC->getDeclKind();
7888 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7889 Kind != Decl::LinkageSpec) {
7890 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7891 << FnDecl->getDeclName();
7892 return true;
7893 }
7894
7895 bool Valid = false;
7896
Sean Hunt216c2782010-04-07 23:11:06 +00007897 // template <char...> type operator "" name() is the only valid template
7898 // signature, and the only valid signature with no parameters.
7899 if (FnDecl->param_size() == 0) {
7900 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7901 // Must have only one template parameter
7902 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7903 if (Params->size() == 1) {
7904 NonTypeTemplateParmDecl *PmDecl =
7905 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00007906
Sean Hunt216c2782010-04-07 23:11:06 +00007907 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00007908 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7909 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7910 Valid = true;
7911 }
7912 }
7913 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00007914 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00007915 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7916
Sean Hunta6c058d2010-01-13 09:01:02 +00007917 QualType T = (*Param)->getType();
7918
Sean Hunt30019c02010-04-07 22:57:35 +00007919 // unsigned long long int, long double, and any character type are allowed
7920 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00007921 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7922 Context.hasSameType(T, Context.LongDoubleTy) ||
7923 Context.hasSameType(T, Context.CharTy) ||
7924 Context.hasSameType(T, Context.WCharTy) ||
7925 Context.hasSameType(T, Context.Char16Ty) ||
7926 Context.hasSameType(T, Context.Char32Ty)) {
7927 if (++Param == FnDecl->param_end())
7928 Valid = true;
7929 goto FinishedParams;
7930 }
7931
Sean Hunt30019c02010-04-07 22:57:35 +00007932 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00007933 const PointerType *PT = T->getAs<PointerType>();
7934 if (!PT)
7935 goto FinishedParams;
7936 T = PT->getPointeeType();
7937 if (!T.isConstQualified())
7938 goto FinishedParams;
7939 T = T.getUnqualifiedType();
7940
7941 // Move on to the second parameter;
7942 ++Param;
7943
7944 // If there is no second parameter, the first must be a const char *
7945 if (Param == FnDecl->param_end()) {
7946 if (Context.hasSameType(T, Context.CharTy))
7947 Valid = true;
7948 goto FinishedParams;
7949 }
7950
7951 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7952 // are allowed as the first parameter to a two-parameter function
7953 if (!(Context.hasSameType(T, Context.CharTy) ||
7954 Context.hasSameType(T, Context.WCharTy) ||
7955 Context.hasSameType(T, Context.Char16Ty) ||
7956 Context.hasSameType(T, Context.Char32Ty)))
7957 goto FinishedParams;
7958
7959 // The second and final parameter must be an std::size_t
7960 T = (*Param)->getType().getUnqualifiedType();
7961 if (Context.hasSameType(T, Context.getSizeType()) &&
7962 ++Param == FnDecl->param_end())
7963 Valid = true;
7964 }
7965
7966 // FIXME: This diagnostic is absolutely terrible.
7967FinishedParams:
7968 if (!Valid) {
7969 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7970 << FnDecl->getDeclName();
7971 return true;
7972 }
7973
7974 return false;
7975}
7976
Douglas Gregor074149e2009-01-05 19:45:36 +00007977/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7978/// linkage specification, including the language and (if present)
7979/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7980/// the location of the language string literal, which is provided
7981/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7982/// the '{' brace. Otherwise, this linkage specification does not
7983/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00007984Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7985 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00007986 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00007987 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00007988 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007989 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007990 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007991 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007992 Language = LinkageSpecDecl::lang_cxx;
7993 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00007994 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00007995 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00007996 }
Mike Stump1eb44332009-09-09 15:08:12 +00007997
Chris Lattnercc98eac2008-12-17 07:13:27 +00007998 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00007999
Douglas Gregor074149e2009-01-05 19:45:36 +00008000 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008001 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008002 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00008003 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00008004 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00008005}
8006
Abramo Bagnara35f9a192010-07-30 16:47:02 +00008007/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00008008/// the C++ linkage specification LinkageSpec. If RBraceLoc is
8009/// valid, it's the position of the closing '}' brace in a linkage
8010/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00008011Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00008012 Decl *LinkageSpec,
8013 SourceLocation RBraceLoc) {
8014 if (LinkageSpec) {
8015 if (RBraceLoc.isValid()) {
8016 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
8017 LSDecl->setRBraceLoc(RBraceLoc);
8018 }
Douglas Gregor074149e2009-01-05 19:45:36 +00008019 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00008020 }
Douglas Gregor074149e2009-01-05 19:45:36 +00008021 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00008022}
8023
Douglas Gregord308e622009-05-18 20:51:54 +00008024/// \brief Perform semantic analysis for the variable declaration that
8025/// occurs within a C++ catch clause, returning the newly-created
8026/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008027VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00008028 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008029 SourceLocation StartLoc,
8030 SourceLocation Loc,
8031 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00008032 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00008033 QualType ExDeclType = TInfo->getType();
8034
Sebastian Redl4b07b292008-12-22 19:15:10 +00008035 // Arrays and functions decay.
8036 if (ExDeclType->isArrayType())
8037 ExDeclType = Context.getArrayDecayedType(ExDeclType);
8038 else if (ExDeclType->isFunctionType())
8039 ExDeclType = Context.getPointerType(ExDeclType);
8040
8041 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8042 // The exception-declaration shall not denote a pointer or reference to an
8043 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008044 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00008045 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00008046 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008047 Invalid = true;
8048 }
Douglas Gregord308e622009-05-18 20:51:54 +00008049
Douglas Gregora2762912010-03-08 01:47:36 +00008050 // GCC allows catching pointers and references to incomplete types
8051 // as an extension; so do we, but we warn by default.
8052
Sebastian Redl4b07b292008-12-22 19:15:10 +00008053 QualType BaseType = ExDeclType;
8054 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008055 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00008056 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00008057 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008058 BaseType = Ptr->getPointeeType();
8059 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00008060 DK = diag::ext_catch_incomplete_ptr;
8061 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008062 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008063 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008064 BaseType = Ref->getPointeeType();
8065 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00008066 DK = diag::ext_catch_incomplete_ref;
8067 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008068 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008069 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00008070 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8071 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00008072 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008073
Mike Stump1eb44332009-09-09 15:08:12 +00008074 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00008075 RequireNonAbstractType(Loc, ExDeclType,
8076 diag::err_abstract_type_in_decl,
8077 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00008078 Invalid = true;
8079
John McCall5a180392010-07-24 00:37:23 +00008080 // Only the non-fragile NeXT runtime currently supports C++ catches
8081 // of ObjC types, and no runtime supports catching ObjC types by value.
8082 if (!Invalid && getLangOptions().ObjC1) {
8083 QualType T = ExDeclType;
8084 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8085 T = RT->getPointeeType();
8086
8087 if (T->isObjCObjectType()) {
8088 Diag(Loc, diag::err_objc_object_catch);
8089 Invalid = true;
8090 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00008091 if (!getLangOptions().ObjCNonFragileABI)
8092 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00008093 }
8094 }
8095
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008096 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8097 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00008098 ExDecl->setExceptionVariable(true);
8099
Douglas Gregorc41b8782011-07-06 18:14:43 +00008100 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00008101 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00008102 // C++ [except.handle]p16:
8103 // The object declared in an exception-declaration or, if the
8104 // exception-declaration does not specify a name, a temporary (12.2) is
8105 // copy-initialized (8.5) from the exception object. [...]
8106 // The object is destroyed when the handler exits, after the destruction
8107 // of any automatic objects initialized within the handler.
8108 //
8109 // We just pretend to initialize the object with itself, then make sure
8110 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00008111 QualType initType = ExDeclType;
8112
8113 InitializedEntity entity =
8114 InitializedEntity::InitializeVariable(ExDecl);
8115 InitializationKind initKind =
8116 InitializationKind::CreateCopy(Loc, SourceLocation());
8117
8118 Expr *opaqueValue =
8119 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8120 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8121 ExprResult result = sequence.Perform(*this, entity, initKind,
8122 MultiExprArg(&opaqueValue, 1));
8123 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00008124 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00008125 else {
8126 // If the constructor used was non-trivial, set this as the
8127 // "initializer".
8128 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8129 if (!construct->getConstructor()->isTrivial()) {
8130 Expr *init = MaybeCreateExprWithCleanups(construct);
8131 ExDecl->setInit(init);
8132 }
8133
8134 // And make sure it's destructable.
8135 FinalizeVarWithDestructor(ExDecl, recordType);
8136 }
Douglas Gregor6d182892010-03-05 23:38:39 +00008137 }
8138 }
8139
Douglas Gregord308e622009-05-18 20:51:54 +00008140 if (Invalid)
8141 ExDecl->setInvalidDecl();
8142
8143 return ExDecl;
8144}
8145
8146/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8147/// handler.
John McCalld226f652010-08-21 09:40:31 +00008148Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00008149 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00008150 bool Invalid = D.isInvalidType();
8151
8152 // Check for unexpanded parameter packs.
8153 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8154 UPPC_ExceptionType)) {
8155 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8156 D.getIdentifierLoc());
8157 Invalid = true;
8158 }
8159
Sebastian Redl4b07b292008-12-22 19:15:10 +00008160 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00008161 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00008162 LookupOrdinaryName,
8163 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008164 // The scope should be freshly made just for us. There is just no way
8165 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00008166 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00008167 if (PrevDecl->isTemplateParameter()) {
8168 // Maybe we will complain about the shadowed template parameter.
8169 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008170 }
8171 }
8172
Chris Lattnereaaebc72009-04-25 08:06:05 +00008173 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008174 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8175 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00008176 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008177 }
8178
Douglas Gregor83cb9422010-09-09 17:09:21 +00008179 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008180 D.getSourceRange().getBegin(),
8181 D.getIdentifierLoc(),
8182 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00008183 if (Invalid)
8184 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00008185
Sebastian Redl4b07b292008-12-22 19:15:10 +00008186 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008187 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00008188 PushOnScopeChains(ExDecl, S);
8189 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008190 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008191
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008192 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00008193 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008194}
Anders Carlssonfb311762009-03-14 00:25:26 +00008195
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008196Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008197 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008198 Expr *AssertMessageExpr_,
8199 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00008200 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00008201
Anders Carlssonc3082412009-03-14 00:33:21 +00008202 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8203 llvm::APSInt Value(32);
8204 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008205 Diag(StaticAssertLoc,
8206 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00008207 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008208 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00008209 }
Anders Carlssonfb311762009-03-14 00:25:26 +00008210
Anders Carlssonc3082412009-03-14 00:33:21 +00008211 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008212 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00008213 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00008214 }
8215 }
Mike Stump1eb44332009-09-09 15:08:12 +00008216
Douglas Gregor399ad972010-12-15 23:55:21 +00008217 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8218 return 0;
8219
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008220 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8221 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00008222
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008223 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00008224 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00008225}
Sebastian Redl50de12f2009-03-24 22:27:57 +00008226
Douglas Gregor1d869352010-04-07 16:53:43 +00008227/// \brief Perform semantic analysis of the given friend type declaration.
8228///
8229/// \returns A friend declaration that.
8230FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8231 TypeSourceInfo *TSInfo) {
8232 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8233
8234 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008235 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00008236
Douglas Gregor06245bf2010-04-07 17:57:12 +00008237 if (!getLangOptions().CPlusPlus0x) {
8238 // C++03 [class.friend]p2:
8239 // An elaborated-type-specifier shall be used in a friend declaration
8240 // for a class.*
8241 //
8242 // * The class-key of the elaborated-type-specifier is required.
8243 if (!ActiveTemplateInstantiations.empty()) {
8244 // Do not complain about the form of friend template types during
8245 // template instantiation; we will already have complained when the
8246 // template was declared.
8247 } else if (!T->isElaboratedTypeSpecifier()) {
8248 // If we evaluated the type to a record type, suggest putting
8249 // a tag in front.
8250 if (const RecordType *RT = T->getAs<RecordType>()) {
8251 RecordDecl *RD = RT->getDecl();
8252
8253 std::string InsertionText = std::string(" ") + RD->getKindName();
8254
8255 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8256 << (unsigned) RD->getTagKind()
8257 << T
8258 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8259 InsertionText);
8260 } else {
8261 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8262 << T
8263 << SourceRange(FriendLoc, TypeRange.getEnd());
8264 }
8265 } else if (T->getAs<EnumType>()) {
8266 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00008267 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00008268 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00008269 }
8270 }
8271
Douglas Gregor06245bf2010-04-07 17:57:12 +00008272 // C++0x [class.friend]p3:
8273 // If the type specifier in a friend declaration designates a (possibly
8274 // cv-qualified) class type, that class is declared as a friend; otherwise,
8275 // the friend declaration is ignored.
8276
8277 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8278 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00008279
8280 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8281}
8282
John McCall9a34edb2010-10-19 01:40:49 +00008283/// Handle a friend tag declaration where the scope specifier was
8284/// templated.
8285Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8286 unsigned TagSpec, SourceLocation TagLoc,
8287 CXXScopeSpec &SS,
8288 IdentifierInfo *Name, SourceLocation NameLoc,
8289 AttributeList *Attr,
8290 MultiTemplateParamsArg TempParamLists) {
8291 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8292
8293 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00008294 bool Invalid = false;
8295
8296 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00008297 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00008298 TempParamLists.get(),
8299 TempParamLists.size(),
8300 /*friend*/ true,
8301 isExplicitSpecialization,
8302 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00008303 if (TemplateParams->size() > 0) {
8304 // This is a declaration of a class template.
8305 if (Invalid)
8306 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008307
Eric Christopher4110e132011-07-21 05:34:24 +00008308 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8309 SS, Name, NameLoc, Attr,
8310 TemplateParams, AS_public,
8311 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008312 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00008313 } else {
8314 // The "template<>" header is extraneous.
8315 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8316 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8317 isExplicitSpecialization = true;
8318 }
8319 }
8320
8321 if (Invalid) return 0;
8322
8323 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8324
8325 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008326 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00008327 if (TempParamLists.get()[I]->size()) {
8328 isAllExplicitSpecializations = false;
8329 break;
8330 }
8331 }
8332
8333 // FIXME: don't ignore attributes.
8334
8335 // If it's explicit specializations all the way down, just forget
8336 // about the template header and build an appropriate non-templated
8337 // friend. TODO: for source fidelity, remember the headers.
8338 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00008339 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00008340 ElaboratedTypeKeyword Keyword
8341 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008342 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00008343 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008344 if (T.isNull())
8345 return 0;
8346
8347 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8348 if (isa<DependentNameType>(T)) {
8349 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8350 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008351 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008352 TL.setNameLoc(NameLoc);
8353 } else {
8354 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8355 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00008356 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008357 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8358 }
8359
8360 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8361 TSI, FriendLoc);
8362 Friend->setAccess(AS_public);
8363 CurContext->addDecl(Friend);
8364 return Friend;
8365 }
8366
8367 // Handle the case of a templated-scope friend class. e.g.
8368 // template <class T> class A<T>::B;
8369 // FIXME: we don't support these right now.
8370 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8371 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8372 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8373 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8374 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008375 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00008376 TL.setNameLoc(NameLoc);
8377
8378 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8379 TSI, FriendLoc);
8380 Friend->setAccess(AS_public);
8381 Friend->setUnsupportedFriend(true);
8382 CurContext->addDecl(Friend);
8383 return Friend;
8384}
8385
8386
John McCalldd4a3b02009-09-16 22:47:08 +00008387/// Handle a friend type declaration. This works in tandem with
8388/// ActOnTag.
8389///
8390/// Notes on friend class templates:
8391///
8392/// We generally treat friend class declarations as if they were
8393/// declaring a class. So, for example, the elaborated type specifier
8394/// in a friend declaration is required to obey the restrictions of a
8395/// class-head (i.e. no typedefs in the scope chain), template
8396/// parameters are required to match up with simple template-ids, &c.
8397/// However, unlike when declaring a template specialization, it's
8398/// okay to refer to a template specialization without an empty
8399/// template parameter declaration, e.g.
8400/// friend class A<T>::B<unsigned>;
8401/// We permit this as a special case; if there are any template
8402/// parameters present at all, require proper matching, i.e.
8403/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00008404Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00008405 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00008406 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00008407
8408 assert(DS.isFriendSpecified());
8409 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8410
John McCalldd4a3b02009-09-16 22:47:08 +00008411 // Try to convert the decl specifier to a type. This works for
8412 // friend templates because ActOnTag never produces a ClassTemplateDecl
8413 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00008414 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00008415 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8416 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00008417 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00008418 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008419
Douglas Gregor6ccab972010-12-16 01:14:37 +00008420 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8421 return 0;
8422
John McCalldd4a3b02009-09-16 22:47:08 +00008423 // This is definitely an error in C++98. It's probably meant to
8424 // be forbidden in C++0x, too, but the specification is just
8425 // poorly written.
8426 //
8427 // The problem is with declarations like the following:
8428 // template <T> friend A<T>::foo;
8429 // where deciding whether a class C is a friend or not now hinges
8430 // on whether there exists an instantiation of A that causes
8431 // 'foo' to equal C. There are restrictions on class-heads
8432 // (which we declare (by fiat) elaborated friend declarations to
8433 // be) that makes this tractable.
8434 //
8435 // FIXME: handle "template <> friend class A<T>;", which
8436 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00008437 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00008438 Diag(Loc, diag::err_tagless_friend_type_template)
8439 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008440 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00008441 }
Douglas Gregor1d869352010-04-07 16:53:43 +00008442
John McCall02cace72009-08-28 07:59:38 +00008443 // C++98 [class.friend]p1: A friend of a class is a function
8444 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00008445 // This is fixed in DR77, which just barely didn't make the C++03
8446 // deadline. It's also a very silly restriction that seriously
8447 // affects inner classes and which nobody else seems to implement;
8448 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00008449 //
8450 // But note that we could warn about it: it's always useless to
8451 // friend one of your own members (it's not, however, worthless to
8452 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00008453
John McCalldd4a3b02009-09-16 22:47:08 +00008454 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00008455 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00008456 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00008457 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00008458 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00008459 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00008460 DS.getFriendSpecLoc());
8461 else
Douglas Gregor1d869352010-04-07 16:53:43 +00008462 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8463
8464 if (!D)
John McCalld226f652010-08-21 09:40:31 +00008465 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00008466
John McCalldd4a3b02009-09-16 22:47:08 +00008467 D->setAccess(AS_public);
8468 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00008469
John McCalld226f652010-08-21 09:40:31 +00008470 return D;
John McCall02cace72009-08-28 07:59:38 +00008471}
8472
John McCall337ec3d2010-10-12 23:13:28 +00008473Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8474 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00008475 const DeclSpec &DS = D.getDeclSpec();
8476
8477 assert(DS.isFriendSpecified());
8478 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8479
8480 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00008481 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8482 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00008483
8484 // C++ [class.friend]p1
8485 // A friend of a class is a function or class....
8486 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00008487 // It *doesn't* see through dependent types, which is correct
8488 // according to [temp.arg.type]p3:
8489 // If a declaration acquires a function type through a
8490 // type dependent on a template-parameter and this causes
8491 // a declaration that does not use the syntactic form of a
8492 // function declarator to have a function type, the program
8493 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00008494 if (!T->isFunctionType()) {
8495 Diag(Loc, diag::err_unexpected_friend);
8496
8497 // It might be worthwhile to try to recover by creating an
8498 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00008499 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008500 }
8501
8502 // C++ [namespace.memdef]p3
8503 // - If a friend declaration in a non-local class first declares a
8504 // class or function, the friend class or function is a member
8505 // of the innermost enclosing namespace.
8506 // - The name of the friend is not found by simple name lookup
8507 // until a matching declaration is provided in that namespace
8508 // scope (either before or after the class declaration granting
8509 // friendship).
8510 // - If a friend function is called, its name may be found by the
8511 // name lookup that considers functions from namespaces and
8512 // classes associated with the types of the function arguments.
8513 // - When looking for a prior declaration of a class or a function
8514 // declared as a friend, scopes outside the innermost enclosing
8515 // namespace scope are not considered.
8516
John McCall337ec3d2010-10-12 23:13:28 +00008517 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00008518 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8519 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00008520 assert(Name);
8521
Douglas Gregor6ccab972010-12-16 01:14:37 +00008522 // Check for unexpanded parameter packs.
8523 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8524 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8525 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8526 return 0;
8527
John McCall67d1a672009-08-06 02:15:43 +00008528 // The context we found the declaration in, or in which we should
8529 // create the declaration.
8530 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00008531 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00008532 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00008533 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00008534
John McCall337ec3d2010-10-12 23:13:28 +00008535 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00008536
John McCall337ec3d2010-10-12 23:13:28 +00008537 // There are four cases here.
8538 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00008539 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00008540 // there as appropriate.
8541 // Recover from invalid scope qualifiers as if they just weren't there.
8542 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00008543 // C++0x [namespace.memdef]p3:
8544 // If the name in a friend declaration is neither qualified nor
8545 // a template-id and the declaration is a function or an
8546 // elaborated-type-specifier, the lookup to determine whether
8547 // the entity has been previously declared shall not consider
8548 // any scopes outside the innermost enclosing namespace.
8549 // C++0x [class.friend]p11:
8550 // If a friend declaration appears in a local class and the name
8551 // specified is an unqualified name, a prior declaration is
8552 // looked up without considering scopes that are outside the
8553 // innermost enclosing non-class scope. For a friend function
8554 // declaration, if there is no prior declaration, the program is
8555 // ill-formed.
8556 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00008557 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00008558
John McCall29ae6e52010-10-13 05:45:15 +00008559 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00008560 DC = CurContext;
8561 while (true) {
8562 // Skip class contexts. If someone can cite chapter and verse
8563 // for this behavior, that would be nice --- it's what GCC and
8564 // EDG do, and it seems like a reasonable intent, but the spec
8565 // really only says that checks for unqualified existing
8566 // declarations should stop at the nearest enclosing namespace,
8567 // not that they should only consider the nearest enclosing
8568 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00008569 while (DC->isRecord())
8570 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00008571
John McCall68263142009-11-18 22:49:29 +00008572 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00008573
8574 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00008575 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00008576 break;
John McCall29ae6e52010-10-13 05:45:15 +00008577
John McCall8a407372010-10-14 22:22:28 +00008578 if (isTemplateId) {
8579 if (isa<TranslationUnitDecl>(DC)) break;
8580 } else {
8581 if (DC->isFileContext()) break;
8582 }
John McCall67d1a672009-08-06 02:15:43 +00008583 DC = DC->getParent();
8584 }
8585
8586 // C++ [class.friend]p1: A friend of a class is a function or
8587 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00008588 // C++0x changes this for both friend types and functions.
8589 // Most C++ 98 compilers do seem to give an error here, so
8590 // we do, too.
John McCall68263142009-11-18 22:49:29 +00008591 if (!Previous.empty() && DC->Equals(CurContext)
8592 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00008593 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00008594
John McCall380aaa42010-10-13 06:22:15 +00008595 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00008596
John McCall337ec3d2010-10-12 23:13:28 +00008597 // - There's a non-dependent scope specifier, in which case we
8598 // compute it and do a previous lookup there for a function
8599 // or function template.
8600 } else if (!SS.getScopeRep()->isDependent()) {
8601 DC = computeDeclContext(SS);
8602 if (!DC) return 0;
8603
8604 if (RequireCompleteDeclContext(SS, DC)) return 0;
8605
8606 LookupQualifiedName(Previous, DC);
8607
8608 // Ignore things found implicitly in the wrong scope.
8609 // TODO: better diagnostics for this case. Suggesting the right
8610 // qualified scope would be nice...
8611 LookupResult::Filter F = Previous.makeFilter();
8612 while (F.hasNext()) {
8613 NamedDecl *D = F.next();
8614 if (!DC->InEnclosingNamespaceSetOf(
8615 D->getDeclContext()->getRedeclContext()))
8616 F.erase();
8617 }
8618 F.done();
8619
8620 if (Previous.empty()) {
8621 D.setInvalidType();
8622 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8623 return 0;
8624 }
8625
8626 // C++ [class.friend]p1: A friend of a class is a function or
8627 // class that is not a member of the class . . .
8628 if (DC->Equals(CurContext))
8629 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8630
8631 // - There's a scope specifier that does not match any template
8632 // parameter lists, in which case we use some arbitrary context,
8633 // create a method or method template, and wait for instantiation.
8634 // - There's a scope specifier that does match some template
8635 // parameter lists, which we don't handle right now.
8636 } else {
8637 DC = CurContext;
8638 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00008639 }
8640
John McCall29ae6e52010-10-13 05:45:15 +00008641 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00008642 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008643 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8644 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8645 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00008646 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008647 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8648 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00008649 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008650 }
John McCall67d1a672009-08-06 02:15:43 +00008651 }
8652
Douglas Gregor182ddf02009-09-28 00:08:27 +00008653 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00008654 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00008655 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00008656 IsDefinition,
8657 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00008658 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00008659
Douglas Gregor182ddf02009-09-28 00:08:27 +00008660 assert(ND->getDeclContext() == DC);
8661 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00008662
John McCallab88d972009-08-31 22:39:49 +00008663 // Add the function declaration to the appropriate lookup tables,
8664 // adjusting the redeclarations list as necessary. We don't
8665 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00008666 //
John McCallab88d972009-08-31 22:39:49 +00008667 // Also update the scope-based lookup if the target context's
8668 // lookup context is in lexical scope.
8669 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008670 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00008671 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008672 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00008673 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008674 }
John McCall02cace72009-08-28 07:59:38 +00008675
8676 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00008677 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00008678 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00008679 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00008680 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00008681
John McCall337ec3d2010-10-12 23:13:28 +00008682 if (ND->isInvalidDecl())
8683 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00008684 else {
8685 FunctionDecl *FD;
8686 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8687 FD = FTD->getTemplatedDecl();
8688 else
8689 FD = cast<FunctionDecl>(ND);
8690
8691 // Mark templated-scope function declarations as unsupported.
8692 if (FD->getNumTemplateParameterLists())
8693 FrD->setUnsupportedFriend(true);
8694 }
John McCall337ec3d2010-10-12 23:13:28 +00008695
John McCalld226f652010-08-21 09:40:31 +00008696 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00008697}
8698
John McCalld226f652010-08-21 09:40:31 +00008699void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8700 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00008701
Sebastian Redl50de12f2009-03-24 22:27:57 +00008702 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8703 if (!Fn) {
8704 Diag(DelLoc, diag::err_deleted_non_function);
8705 return;
8706 }
8707 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8708 Diag(DelLoc, diag::err_deleted_decl_not_first);
8709 Diag(Prev->getLocation(), diag::note_previous_declaration);
8710 // If the declaration wasn't the first, we delete the function anyway for
8711 // recovery.
8712 }
Sean Hunt10620eb2011-05-06 20:44:56 +00008713 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00008714}
Sebastian Redl13e88542009-04-27 21:33:24 +00008715
Sean Hunte4246a62011-05-12 06:15:49 +00008716void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8717 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8718
8719 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00008720 if (MD->getParent()->isDependentType()) {
8721 MD->setDefaulted();
8722 MD->setExplicitlyDefaulted();
8723 return;
8724 }
8725
Sean Hunte4246a62011-05-12 06:15:49 +00008726 CXXSpecialMember Member = getSpecialMember(MD);
8727 if (Member == CXXInvalid) {
8728 Diag(DefaultLoc, diag::err_default_special_members);
8729 return;
8730 }
8731
8732 MD->setDefaulted();
8733 MD->setExplicitlyDefaulted();
8734
Sean Huntcd10dec2011-05-23 23:14:04 +00008735 // If this definition appears within the record, do the checking when
8736 // the record is complete.
8737 const FunctionDecl *Primary = MD;
8738 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8739 // Find the uninstantiated declaration that actually had the '= default'
8740 // on it.
8741 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8742
8743 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00008744 return;
8745
8746 switch (Member) {
8747 case CXXDefaultConstructor: {
8748 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8749 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008750 if (!CD->isInvalidDecl())
8751 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8752 break;
8753 }
8754
8755 case CXXCopyConstructor: {
8756 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8757 CheckExplicitlyDefaultedCopyConstructor(CD);
8758 if (!CD->isInvalidDecl())
8759 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00008760 break;
8761 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00008762
Sean Hunt2b188082011-05-14 05:23:28 +00008763 case CXXCopyAssignment: {
8764 CheckExplicitlyDefaultedCopyAssignment(MD);
8765 if (!MD->isInvalidDecl())
8766 DefineImplicitCopyAssignment(DefaultLoc, MD);
8767 break;
8768 }
8769
Sean Huntcb45a0f2011-05-12 22:46:25 +00008770 case CXXDestructor: {
8771 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8772 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008773 if (!DD->isInvalidDecl())
8774 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008775 break;
8776 }
8777
Sean Hunt82713172011-05-25 23:16:36 +00008778 case CXXMoveConstructor:
8779 case CXXMoveAssignment:
8780 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8781 break;
8782
Sean Hunte4246a62011-05-12 06:15:49 +00008783 default:
Sean Hunt2b188082011-05-14 05:23:28 +00008784 // FIXME: Do the rest once we have move functions
Sean Hunte4246a62011-05-12 06:15:49 +00008785 break;
8786 }
8787 } else {
8788 Diag(DefaultLoc, diag::err_default_special_members);
8789 }
8790}
8791
Sebastian Redl13e88542009-04-27 21:33:24 +00008792static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00008793 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00008794 Stmt *SubStmt = *CI;
8795 if (!SubStmt)
8796 continue;
8797 if (isa<ReturnStmt>(SubStmt))
8798 Self.Diag(SubStmt->getSourceRange().getBegin(),
8799 diag::err_return_in_constructor_handler);
8800 if (!isa<Expr>(SubStmt))
8801 SearchForReturnInStmt(Self, SubStmt);
8802 }
8803}
8804
8805void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8806 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8807 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8808 SearchForReturnInStmt(*this, Handler);
8809 }
8810}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008811
Mike Stump1eb44332009-09-09 15:08:12 +00008812bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008813 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00008814 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8815 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008816
Chandler Carruth73857792010-02-15 11:53:20 +00008817 if (Context.hasSameType(NewTy, OldTy) ||
8818 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008819 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00008820
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008821 // Check if the return types are covariant
8822 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00008823
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008824 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008825 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8826 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008827 NewClassTy = NewPT->getPointeeType();
8828 OldClassTy = OldPT->getPointeeType();
8829 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008830 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8831 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8832 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8833 NewClassTy = NewRT->getPointeeType();
8834 OldClassTy = OldRT->getPointeeType();
8835 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008836 }
8837 }
Mike Stump1eb44332009-09-09 15:08:12 +00008838
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008839 // The return types aren't either both pointers or references to a class type.
8840 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00008841 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008842 diag::err_different_return_type_for_overriding_virtual_function)
8843 << New->getDeclName() << NewTy << OldTy;
8844 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00008845
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008846 return true;
8847 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008848
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008849 // C++ [class.virtual]p6:
8850 // If the return type of D::f differs from the return type of B::f, the
8851 // class type in the return type of D::f shall be complete at the point of
8852 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00008853 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8854 if (!RT->isBeingDefined() &&
8855 RequireCompleteType(New->getLocation(), NewClassTy,
8856 PDiag(diag::err_covariant_return_incomplete)
8857 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008858 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00008859 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008860
Douglas Gregora4923eb2009-11-16 21:35:15 +00008861 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008862 // Check if the new class derives from the old class.
8863 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8864 Diag(New->getLocation(),
8865 diag::err_covariant_return_not_derived)
8866 << New->getDeclName() << NewTy << OldTy;
8867 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8868 return true;
8869 }
Mike Stump1eb44332009-09-09 15:08:12 +00008870
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008871 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00008872 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00008873 diag::err_covariant_return_inaccessible_base,
8874 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8875 // FIXME: Should this point to the return type?
8876 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00008877 // FIXME: this note won't trigger for delayed access control
8878 // diagnostics, and it's impossible to get an undelayed error
8879 // here from access control during the original parse because
8880 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008881 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8882 return true;
8883 }
8884 }
Mike Stump1eb44332009-09-09 15:08:12 +00008885
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008886 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008887 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008888 Diag(New->getLocation(),
8889 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008890 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008891 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8892 return true;
8893 };
Mike Stump1eb44332009-09-09 15:08:12 +00008894
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008895
8896 // The new class type must have the same or less qualifiers as the old type.
8897 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8898 Diag(New->getLocation(),
8899 diag::err_covariant_return_type_class_type_more_qualified)
8900 << New->getDeclName() << NewTy << OldTy;
8901 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8902 return true;
8903 };
Mike Stump1eb44332009-09-09 15:08:12 +00008904
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008905 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008906}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008907
Douglas Gregor4ba31362009-12-01 17:24:26 +00008908/// \brief Mark the given method pure.
8909///
8910/// \param Method the method to be marked pure.
8911///
8912/// \param InitRange the source range that covers the "0" initializer.
8913bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00008914 SourceLocation EndLoc = InitRange.getEnd();
8915 if (EndLoc.isValid())
8916 Method->setRangeEnd(EndLoc);
8917
Douglas Gregor4ba31362009-12-01 17:24:26 +00008918 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8919 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00008920 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00008921 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00008922
8923 if (!Method->isInvalidDecl())
8924 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8925 << Method->getDeclName() << InitRange;
8926 return true;
8927}
8928
John McCall731ad842009-12-19 09:28:58 +00008929/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8930/// an initializer for the out-of-line declaration 'Dcl'. The scope
8931/// is a fresh scope pushed for just this purpose.
8932///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008933/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8934/// static data member of class X, names should be looked up in the scope of
8935/// class X.
John McCalld226f652010-08-21 09:40:31 +00008936void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008937 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008938 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008939
John McCall731ad842009-12-19 09:28:58 +00008940 // We should only get called for declarations with scope specifiers, like:
8941 // int foo::bar;
8942 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008943 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008944}
8945
8946/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00008947/// initializer for the out-of-line declaration 'D'.
8948void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008949 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008950 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008951
John McCall731ad842009-12-19 09:28:58 +00008952 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008953 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008954}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008955
8956/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8957/// C++ if/switch/while/for statement.
8958/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00008959DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008960 // C++ 6.4p2:
8961 // The declarator shall not specify a function or an array.
8962 // The type-specifier-seq shall not contain typedef and shall not declare a
8963 // new class or enumeration.
8964 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8965 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00008966
8967 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +00008968 if (!Dcl)
8969 return true;
8970
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00008971 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
8972 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008973 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +00008974 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008975 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008976
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008977 return Dcl;
8978}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008979
Douglas Gregordfe65432011-07-28 19:11:31 +00008980void Sema::LoadExternalVTableUses() {
8981 if (!ExternalSource)
8982 return;
8983
8984 SmallVector<ExternalVTableUse, 4> VTables;
8985 ExternalSource->ReadUsedVTables(VTables);
8986 SmallVector<VTableUse, 4> NewUses;
8987 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
8988 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
8989 = VTablesUsed.find(VTables[I].Record);
8990 // Even if a definition wasn't required before, it may be required now.
8991 if (Pos != VTablesUsed.end()) {
8992 if (!Pos->second && VTables[I].DefinitionRequired)
8993 Pos->second = true;
8994 continue;
8995 }
8996
8997 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
8998 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
8999 }
9000
9001 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
9002}
9003
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009004void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
9005 bool DefinitionRequired) {
9006 // Ignore any vtable uses in unevaluated operands or for classes that do
9007 // not have a vtable.
9008 if (!Class->isDynamicClass() || Class->isDependentContext() ||
9009 CurContext->isDependentContext() ||
9010 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00009011 return;
9012
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009013 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +00009014 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009015 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9016 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
9017 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
9018 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00009019 // If we already had an entry, check to see if we are promoting this vtable
9020 // to required a definition. If so, we need to reappend to the VTableUses
9021 // list, since we may have already processed the first entry.
9022 if (DefinitionRequired && !Pos.first->second) {
9023 Pos.first->second = true;
9024 } else {
9025 // Otherwise, we can early exit.
9026 return;
9027 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009028 }
9029
9030 // Local classes need to have their virtual members marked
9031 // immediately. For all other classes, we mark their virtual members
9032 // at the end of the translation unit.
9033 if (Class->isLocalClass())
9034 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00009035 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009036 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00009037}
9038
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009039bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +00009040 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009041 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00009042 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00009043
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009044 // Note: The VTableUses vector could grow as a result of marking
9045 // the members of a class as "used", so we check the size each
9046 // time through the loop and prefer indices (with are stable) to
9047 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00009048 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009049 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00009050 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009051 if (!Class)
9052 continue;
9053
9054 SourceLocation Loc = VTableUses[I].second;
9055
9056 // If this class has a key function, but that key function is
9057 // defined in another translation unit, we don't need to emit the
9058 // vtable even though we're using it.
9059 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00009060 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009061 switch (KeyFunction->getTemplateSpecializationKind()) {
9062 case TSK_Undeclared:
9063 case TSK_ExplicitSpecialization:
9064 case TSK_ExplicitInstantiationDeclaration:
9065 // The key function is in another translation unit.
9066 continue;
9067
9068 case TSK_ExplicitInstantiationDefinition:
9069 case TSK_ImplicitInstantiation:
9070 // We will be instantiating the key function.
9071 break;
9072 }
9073 } else if (!KeyFunction) {
9074 // If we have a class with no key function that is the subject
9075 // of an explicit instantiation declaration, suppress the
9076 // vtable; it will live with the explicit instantiation
9077 // definition.
9078 bool IsExplicitInstantiationDeclaration
9079 = Class->getTemplateSpecializationKind()
9080 == TSK_ExplicitInstantiationDeclaration;
9081 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9082 REnd = Class->redecls_end();
9083 R != REnd; ++R) {
9084 TemplateSpecializationKind TSK
9085 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9086 if (TSK == TSK_ExplicitInstantiationDeclaration)
9087 IsExplicitInstantiationDeclaration = true;
9088 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9089 IsExplicitInstantiationDeclaration = false;
9090 break;
9091 }
9092 }
9093
9094 if (IsExplicitInstantiationDeclaration)
9095 continue;
9096 }
9097
9098 // Mark all of the virtual members of this class as referenced, so
9099 // that we can build a vtable. Then, tell the AST consumer that a
9100 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00009101 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009102 MarkVirtualMembersReferenced(Loc, Class);
9103 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9104 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9105
9106 // Optionally warn if we're emitting a weak vtable.
9107 if (Class->getLinkage() == ExternalLinkage &&
9108 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00009109 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009110 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9111 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009112 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009113 VTableUses.clear();
9114
Douglas Gregor78844032011-04-22 22:25:37 +00009115 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009116}
Anders Carlssond6a637f2009-12-07 08:24:59 +00009117
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009118void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9119 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00009120 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9121 e = RD->method_end(); i != e; ++i) {
9122 CXXMethodDecl *MD = *i;
9123
9124 // C++ [basic.def.odr]p2:
9125 // [...] A virtual member function is used if it is not pure. [...]
9126 if (MD->isVirtual() && !MD->isPure())
9127 MarkDeclarationReferenced(Loc, MD);
9128 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009129
9130 // Only classes that have virtual bases need a VTT.
9131 if (RD->getNumVBases() == 0)
9132 return;
9133
9134 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9135 e = RD->bases_end(); i != e; ++i) {
9136 const CXXRecordDecl *Base =
9137 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009138 if (Base->getNumVBases() == 0)
9139 continue;
9140 MarkVirtualMembersReferenced(Loc, Base);
9141 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00009142}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009143
9144/// SetIvarInitializers - This routine builds initialization ASTs for the
9145/// Objective-C implementation whose ivars need be initialized.
9146void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9147 if (!getLangOptions().CPlusPlus)
9148 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00009149 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00009150 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009151 CollectIvarsToConstructOrDestruct(OID, ivars);
9152 if (ivars.empty())
9153 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009154 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009155 for (unsigned i = 0; i < ivars.size(); i++) {
9156 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009157 if (Field->isInvalidDecl())
9158 continue;
9159
Sean Huntcbb67482011-01-08 20:30:50 +00009160 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009161 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9162 InitializationKind InitKind =
9163 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9164
9165 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009166 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00009167 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00009168 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009169 // Note, MemberInit could actually come back empty if no initialization
9170 // is required (e.g., because it would call a trivial default constructor)
9171 if (!MemberInit.get() || MemberInit.isInvalid())
9172 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00009173
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009174 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00009175 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9176 SourceLocation(),
9177 MemberInit.takeAs<Expr>(),
9178 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009179 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009180
9181 // Be sure that the destructor is accessible and is marked as referenced.
9182 if (const RecordType *RecordTy
9183 = Context.getBaseElementType(Field->getType())
9184 ->getAs<RecordType>()) {
9185 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00009186 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009187 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9188 CheckDestructorAccess(Field->getLocation(), Destructor,
9189 PDiag(diag::err_access_dtor_ivar)
9190 << Context.getBaseElementType(Field->getType()));
9191 }
9192 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009193 }
9194 ObjCImplementation->setIvarInitializers(Context,
9195 AllToInit.data(), AllToInit.size());
9196 }
9197}
Sean Huntfe57eef2011-05-04 05:57:24 +00009198
Sean Huntebcbe1d2011-05-04 23:29:54 +00009199static
9200void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9201 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9202 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9203 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9204 Sema &S) {
9205 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9206 CE = Current.end();
9207 if (Ctor->isInvalidDecl())
9208 return;
9209
9210 const FunctionDecl *FNTarget = 0;
9211 CXXConstructorDecl *Target;
9212
9213 // We ignore the result here since if we don't have a body, Target will be
9214 // null below.
9215 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9216 Target
9217= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9218
9219 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9220 // Avoid dereferencing a null pointer here.
9221 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9222
9223 if (!Current.insert(Canonical))
9224 return;
9225
9226 // We know that beyond here, we aren't chaining into a cycle.
9227 if (!Target || !Target->isDelegatingConstructor() ||
9228 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9229 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9230 Valid.insert(*CI);
9231 Current.clear();
9232 // We've hit a cycle.
9233 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9234 Current.count(TCanonical)) {
9235 // If we haven't diagnosed this cycle yet, do so now.
9236 if (!Invalid.count(TCanonical)) {
9237 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00009238 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00009239 << Ctor;
9240
9241 // Don't add a note for a function delegating directo to itself.
9242 if (TCanonical != Canonical)
9243 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9244
9245 CXXConstructorDecl *C = Target;
9246 while (C->getCanonicalDecl() != Canonical) {
9247 (void)C->getTargetConstructor()->hasBody(FNTarget);
9248 assert(FNTarget && "Ctor cycle through bodiless function");
9249
9250 C
9251 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9252 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9253 }
9254 }
9255
9256 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9257 Invalid.insert(*CI);
9258 Current.clear();
9259 } else {
9260 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9261 }
9262}
9263
9264
Sean Huntfe57eef2011-05-04 05:57:24 +00009265void Sema::CheckDelegatingCtorCycles() {
9266 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9267
Sean Huntebcbe1d2011-05-04 23:29:54 +00009268 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9269 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00009270
Douglas Gregor0129b562011-07-27 21:57:17 +00009271 for (DelegatingCtorDeclsType::iterator
9272 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +00009273 E = DelegatingCtorDecls.end();
9274 I != E; ++I) {
9275 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00009276 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00009277
9278 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9279 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00009280}