blob: 07eb9fe572aa4a696bfb79e7caa5406bdaa93a68 [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000036#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000037#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner58258242008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000055
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 public:
Mike Stump11289f42009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 };
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000071 }
72
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 }
Chris Lattner58258242008-04-10 02:22:51 +000099
Douglas Gregor8e12c382008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000102
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111 }
Chris Lattner58258242008-04-10 02:22:51 +0000112}
113
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith938f40b2011-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)
Alexis Hunt6d5b96c2011-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 Smith938f40b2011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith938f40b2011-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
Alexis Hunt6d5b96c2011-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) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-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)
Alexis Hunt913820d2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith938f40b2011-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 Takumi53648472011-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 Smith938f40b2011-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 Carlssonc80a1272009-08-25 02:29:20 +0000210bool
John McCallb268a282010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000233 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000235
John McCallacf0ee52010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000238
Anders Carlssonc80a1272009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000254 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000255}
256
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000260void
John McCall48871652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000264 return;
Mike Stump11289f42009-09-09 15:08:12 +0000265
John McCall48871652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump11289f42009-09-09 15:08:12 +0000289
John McCallb268a282010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000291}
292
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000306
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000308}
309
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump11289f42009-09-09 15:08:12 +0000315
John McCall48871652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Anders Carlsson84613c42009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Anders Carlsson84613c42009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000321}
322
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000388
Francois Pichet53fe2bb2011-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 Pichet8cb243a2011-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 Pichet93921652011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000409
Francois Pichet8cb243a2011-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 Gregor08dc5842010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor4f15f4d2009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCalle61b02b2010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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();
Alexis Huntd051b872011-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 Gregorc732aba2009-09-11 18:44:32 +0000501 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregorf40863c2010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000507
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000509}
510
Sebastian Redlfa453cf2011-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 Lattner199abbc2008-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 Carlsson5a532382009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000583 else
Mike Stump11289f42009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregor556877c2008-04-13 21:30:24 +0000604
Douglas Gregor61956c42008-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 Kyrtzidis32a03792008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-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 Gregor1aa3edb2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump11289f42009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-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 Gregor752a5952011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor463421d2009-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 Gregor752a5952011-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 Gregor463421d2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000680 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000681 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000682
Eli Friedmanc96d4962009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000690
Anders Carlsson65c76d32011-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 Carlsson1eb95962011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-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 McCall3696dcb2010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000709}
710
Douglas Gregor556877c2008-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 Stump11289f42009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000716BaseResult
John McCall48871652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregorc40290e2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky19b9f952010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000731
Douglas Gregor752a5952011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000736
Douglas Gregor463421d2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregor463421d2009-03-03 04:44:36 +0000742 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000743}
Douglas Gregor556877c2008-04-13 21:30:24 +0000744
Douglas Gregor463421d2009-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 Gregor29a92472008-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 Gregor9d6290b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-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 Gregor463421d2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-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 Gregorb77af8f2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-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 McCall48871652010-08-21 09:40:31 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000809
John McCalle78aac42010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000827 return false;
828
John McCalle78aac42010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000831 return false;
832
John McCall67da35c2010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000845 return false;
846
John McCalle78aac42010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregor36d1b142009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlssona70cff62010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-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 McCallcf142162010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000875}
876
Douglas Gregor88d292c2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallcf142162010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregor36d1b142009-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 McCall1064d7e2010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-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 Carlssona70cff62010-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 Carlsson7afe4242010-04-24 17:11:09 +0000926 }
John McCall5b0829a2010-02-10 09:31:12 +0000927 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregor36d1b142009-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 Redl7c353682009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregor36d1b142009-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 Kyrtzidised983422008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnarad7340582010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +00001016}
1017
Anders Carlssonfd835532011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +00001020 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlssonfd835532011-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 Carlsson1eb95962011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson3f610c72011-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 Carlsson1eb95962011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-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 Carlsson3f610c72011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidised983422008-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 Smith938f40b2011-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 McCall48871652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +00001063 ExprTy *BW, const VirtSpecifiers &VS,
Richard Smith938f40b2011-06-11 17:19:42 +00001064 ExprTy *InitExpr, bool HasDeferredInit,
1065 bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-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 Kyrtzidised983422008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001077
John McCallb1cd7da2010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith938f40b2011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall07e91c02009-08-06 02:15:43 +00001081
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001083
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-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 Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001099 else
Chris Lattner3b054132008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001101
Sebastian Redl8071edb2008-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 Redlccdfaba2008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregora007d362010-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 Gregor3447e762009-08-20 22:52:58 +00001142 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001143 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001145 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001146 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001147 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001148 assert(!HasDeferredInit);
1149
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001151 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001152 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001153 }
Chris Lattnerd26760a2009-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 Gregor212cab32009-03-11 20:22:50 +00001159 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-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 Stump11289f42009-09-09 15:08:12 +00001172 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001173 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001174 }
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattnerd26760a2009-03-05 23:01:03 +00001176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001179
1180 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Douglas Gregor3447e762009-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 Lattner73bf7b42009-03-05 22:45:59 +00001186 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001187
Anders Carlsson13a69102011-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 Carlssonfd835532011-01-20 05:57:14 +00001194 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-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 Carlssonfd835532011-01-20 05:57:14 +00001203 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001205 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001206
Douglas Gregorf2f08062011-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 Carlssonc87f8612011-01-20 06:29:02 +00001213 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001214
Douglas Gregor92751d42008-11-17 22:58:34 +00001215 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001216
Douglas Gregor0c880302009-03-11 23:00:04 +00001217 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith938f40b2011-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 Kyrtzidised983422008-07-01 10:37:29 +00001228
Richard Smithb2bc2e62011-02-21 20:05:19 +00001229 FinalizeDeclaration(Member);
1230
John McCall25849ca2011-02-15 07:12:36 +00001231 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001232 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001233 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001234}
1235
Richard Smith938f40b2011-06-11 17:19:42 +00001236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1237/// in-class initializer for a non-static C++ class member. Such parsing
1238/// is deferred until the class is complete.
1239void
1240Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1241 Expr *InitExpr) {
1242 FieldDecl *FD = cast<FieldDecl>(D);
1243
1244 if (!InitExpr) {
1245 FD->setInvalidDecl();
1246 FD->removeInClassInitializer();
1247 return;
1248 }
1249
1250 ExprResult Init = InitExpr;
1251 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1252 // FIXME: if there is no EqualLoc, this is list-initialization.
1253 Init = PerformCopyInitialization(
1254 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1255 if (Init.isInvalid()) {
1256 FD->setInvalidDecl();
1257 return;
1258 }
1259
1260 CheckImplicitConversions(Init.get(), EqualLoc);
1261 }
1262
1263 // C++0x [class.base.init]p7:
1264 // The initialization of each base and member constitutes a
1265 // full-expression.
1266 Init = MaybeCreateExprWithCleanups(Init);
1267 if (Init.isInvalid()) {
1268 FD->setInvalidDecl();
1269 return;
1270 }
1271
1272 InitExpr = Init.release();
1273
1274 FD->setInClassInitializer(InitExpr);
1275}
1276
Douglas Gregor15e77a22009-12-31 09:10:24 +00001277/// \brief Find the direct and/or virtual base specifiers that
1278/// correspond to the given base type, for use in base initialization
1279/// within a constructor.
1280static bool FindBaseInitializer(Sema &SemaRef,
1281 CXXRecordDecl *ClassDecl,
1282 QualType BaseType,
1283 const CXXBaseSpecifier *&DirectBaseSpec,
1284 const CXXBaseSpecifier *&VirtualBaseSpec) {
1285 // First, check for a direct base class.
1286 DirectBaseSpec = 0;
1287 for (CXXRecordDecl::base_class_const_iterator Base
1288 = ClassDecl->bases_begin();
1289 Base != ClassDecl->bases_end(); ++Base) {
1290 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1291 // We found a direct base of this type. That's what we're
1292 // initializing.
1293 DirectBaseSpec = &*Base;
1294 break;
1295 }
1296 }
1297
1298 // Check for a virtual base class.
1299 // FIXME: We might be able to short-circuit this if we know in advance that
1300 // there are no virtual bases.
1301 VirtualBaseSpec = 0;
1302 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1303 // We haven't found a base yet; search the class hierarchy for a
1304 // virtual base class.
1305 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1306 /*DetectVirtual=*/false);
1307 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1308 BaseType, Paths)) {
1309 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1310 Path != Paths.end(); ++Path) {
1311 if (Path->back().Base->isVirtual()) {
1312 VirtualBaseSpec = Path->back().Base;
1313 break;
1314 }
1315 }
1316 }
1317 }
1318
1319 return DirectBaseSpec || VirtualBaseSpec;
1320}
1321
Douglas Gregore8381c02008-11-05 04:29:56 +00001322/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001323MemInitResult
John McCall48871652010-08-21 09:40:31 +00001324Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001325 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001326 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001327 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001328 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001329 SourceLocation IdLoc,
1330 SourceLocation LParenLoc,
1331 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001332 SourceLocation RParenLoc,
1333 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001334 if (!ConstructorD)
1335 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001336
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001337 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001338
1339 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001340 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001341 if (!Constructor) {
1342 // The user wrote a constructor initializer on a function that is
1343 // not a C++ constructor. Ignore the error for now, because we may
1344 // have more member initializers coming; we'll diagnose it just
1345 // once in ActOnMemInitializers.
1346 return true;
1347 }
1348
1349 CXXRecordDecl *ClassDecl = Constructor->getParent();
1350
1351 // C++ [class.base.init]p2:
1352 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001353 // constructor's class and, if not found in that scope, are looked
1354 // up in the scope containing the constructor's definition.
1355 // [Note: if the constructor's class contains a member with the
1356 // same name as a direct or virtual base class of the class, a
1357 // mem-initializer-id naming the member or base class and composed
1358 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001359 // mem-initializer-id for the hidden base class may be specified
1360 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001361 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001362 // Look for a member, first.
1363 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001364 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001365 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001366 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001367 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001368
Douglas Gregor44e7df62011-01-04 00:32:56 +00001369 if (Member) {
1370 if (EllipsisLoc.isValid())
1371 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1372 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1373
Francois Pichetd583da02010-12-04 09:14:42 +00001374 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001375 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001376 }
1377
Francois Pichetd583da02010-12-04 09:14:42 +00001378 // Handle anonymous union case.
1379 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001380 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1381 if (EllipsisLoc.isValid())
1382 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1383 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1384
Francois Pichetd583da02010-12-04 09:14:42 +00001385 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1386 NumArgs, IdLoc,
1387 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001388 }
Francois Pichetd583da02010-12-04 09:14:42 +00001389 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001390 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001391 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001392 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001393 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001394
1395 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001396 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001397 } else {
1398 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1399 LookupParsedName(R, S, &SS);
1400
1401 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1402 if (!TyD) {
1403 if (R.isAmbiguous()) return true;
1404
John McCallda6841b2010-04-09 19:01:14 +00001405 // We don't want access-control diagnostics here.
1406 R.suppressDiagnostics();
1407
Douglas Gregora3b624a2010-01-19 06:46:48 +00001408 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1409 bool NotUnknownSpecialization = false;
1410 DeclContext *DC = computeDeclContext(SS, false);
1411 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1412 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1413
1414 if (!NotUnknownSpecialization) {
1415 // When the scope specifier can refer to a member of an unknown
1416 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001417 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1418 SS.getWithLocInContext(Context),
1419 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001420 if (BaseType.isNull())
1421 return true;
1422
Douglas Gregora3b624a2010-01-19 06:46:48 +00001423 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001424 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001425 }
1426 }
1427
Douglas Gregor15e77a22009-12-31 09:10:24 +00001428 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001429 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001430 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1431 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001432 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001433 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001434 // We have found a non-static data member with a similar
1435 // name to what was typed; complain and initialize that
1436 // member.
1437 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1438 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001439 << FixItHint::CreateReplacement(R.getNameLoc(),
1440 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001441 Diag(Member->getLocation(), diag::note_previous_decl)
1442 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001443
1444 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1445 LParenLoc, RParenLoc);
1446 }
1447 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1448 const CXXBaseSpecifier *DirectBaseSpec;
1449 const CXXBaseSpecifier *VirtualBaseSpec;
1450 if (FindBaseInitializer(*this, ClassDecl,
1451 Context.getTypeDeclType(Type),
1452 DirectBaseSpec, VirtualBaseSpec)) {
1453 // We have found a direct or virtual base class with a
1454 // similar name to what was typed; complain and initialize
1455 // that base class.
1456 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1457 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001458 << FixItHint::CreateReplacement(R.getNameLoc(),
1459 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001460
1461 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1462 : VirtualBaseSpec;
1463 Diag(BaseSpec->getSourceRange().getBegin(),
1464 diag::note_base_class_specified_here)
1465 << BaseSpec->getType()
1466 << BaseSpec->getSourceRange();
1467
Douglas Gregor15e77a22009-12-31 09:10:24 +00001468 TyD = Type;
1469 }
1470 }
1471 }
1472
Douglas Gregora3b624a2010-01-19 06:46:48 +00001473 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001474 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1475 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1476 return true;
1477 }
John McCallb5a0d312009-12-21 10:41:20 +00001478 }
1479
Douglas Gregora3b624a2010-01-19 06:46:48 +00001480 if (BaseType.isNull()) {
1481 BaseType = Context.getTypeDeclType(TyD);
1482 if (SS.isSet()) {
1483 NestedNameSpecifier *Qualifier =
1484 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001485
Douglas Gregora3b624a2010-01-19 06:46:48 +00001486 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001487 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001488 }
John McCallb5a0d312009-12-21 10:41:20 +00001489 }
1490 }
Mike Stump11289f42009-09-09 15:08:12 +00001491
John McCallbcd03502009-12-07 02:54:59 +00001492 if (!TInfo)
1493 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001494
John McCallbcd03502009-12-07 02:54:59 +00001495 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001496 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001497}
1498
John McCalle22a04a2009-11-04 23:02:40 +00001499/// Checks an initializer expression for use of uninitialized fields, such as
1500/// containing the field that is being initialized. Returns true if there is an
1501/// uninitialized field was used an updates the SourceLocation parameter; false
1502/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001503static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001504 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001505 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001506 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1507
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001508 if (isa<CallExpr>(S)) {
1509 // Do not descend into function calls or constructors, as the use
1510 // of an uninitialized field may be valid. One would have to inspect
1511 // the contents of the function/ctor to determine if it is safe or not.
1512 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1513 // may be safe, depending on what the function/ctor does.
1514 return false;
1515 }
1516 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1517 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001518
1519 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1520 // The member expression points to a static data member.
1521 assert(VD->isStaticDataMember() &&
1522 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001523 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001524 return false;
1525 }
1526
1527 if (isa<EnumConstantDecl>(RhsField)) {
1528 // The member expression points to an enum.
1529 return false;
1530 }
1531
John McCalle22a04a2009-11-04 23:02:40 +00001532 if (RhsField == LhsField) {
1533 // Initializing a field with itself. Throw a warning.
1534 // But wait; there are exceptions!
1535 // Exception #1: The field may not belong to this record.
1536 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001537 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001538 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1539 // Even though the field matches, it does not belong to this record.
1540 return false;
1541 }
1542 // None of the exceptions triggered; return true to indicate an
1543 // uninitialized field was used.
1544 *L = ME->getMemberLoc();
1545 return true;
1546 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001547 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001548 // sizeof/alignof doesn't reference contents, do not warn.
1549 return false;
1550 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1551 // address-of doesn't reference contents (the pointer may be dereferenced
1552 // in the same expression but it would be rare; and weird).
1553 if (UOE->getOpcode() == UO_AddrOf)
1554 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001555 }
John McCall8322c3a2011-02-13 04:07:26 +00001556 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001557 if (!*it) {
1558 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001559 continue;
1560 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001561 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1562 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001563 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001564 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001565}
1566
John McCallfaf5fb42010-08-26 23:41:50 +00001567MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001568Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001569 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001570 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001571 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001572 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1573 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1574 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001575 "Member must be a FieldDecl or IndirectFieldDecl");
1576
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001577 if (Member->isInvalidDecl())
1578 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001579
John McCalle22a04a2009-11-04 23:02:40 +00001580 // Diagnose value-uses of fields to initialize themselves, e.g.
1581 // foo(foo)
1582 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001583 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001584 for (unsigned i = 0; i < NumArgs; ++i) {
1585 SourceLocation L;
1586 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1587 // FIXME: Return true in the case when other fields are used before being
1588 // uninitialized. For example, let this field be the i'th field. When
1589 // initializing the i'th field, throw a warning if any of the >= i'th
1590 // fields are used, as they are not yet initialized.
1591 // Right now we are only handling the case where the i'th field uses
1592 // itself in its initializer.
1593 Diag(L, diag::warn_field_is_uninit);
1594 }
1595 }
1596
Eli Friedman8e1433b2009-07-29 19:44:27 +00001597 bool HasDependentArg = false;
1598 for (unsigned i = 0; i < NumArgs; i++)
1599 HasDependentArg |= Args[i]->isTypeDependent();
1600
Chandler Carruthd44c3102010-12-06 09:23:57 +00001601 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001602 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001603 // Can't check initialization for a member of dependent type or when
1604 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001605 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001606 RParenLoc,
1607 Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001608
John McCall31168b02011-06-15 23:02:42 +00001609 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00001610 } else {
1611 // Initialize the member.
1612 InitializedEntity MemberEntity =
1613 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1614 : InitializedEntity::InitializeMember(IndirectMember, 0);
1615 InitializationKind Kind =
1616 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001617
Chandler Carruthd44c3102010-12-06 09:23:57 +00001618 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1619
1620 ExprResult MemberInit =
1621 InitSeq.Perform(*this, MemberEntity, Kind,
1622 MultiExprArg(*this, Args, NumArgs), 0);
1623 if (MemberInit.isInvalid())
1624 return true;
1625
1626 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1627
1628 // C++0x [class.base.init]p7:
1629 // The initialization of each base and member constitutes a
1630 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001631 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001632 if (MemberInit.isInvalid())
1633 return true;
1634
1635 // If we are in a dependent context, template instantiation will
1636 // perform this type-checking again. Just save the arguments that we
1637 // received in a ParenListExpr.
1638 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1639 // of the information that we have about the member
1640 // initializer. However, deconstructing the ASTs is a dicey process,
1641 // and this approach is far more likely to get the corner cases right.
1642 if (CurContext->isDependentContext())
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001643 Init = new (Context) ParenListExpr(
1644 Context, LParenLoc, Args, NumArgs, RParenLoc,
1645 Member->getType().getNonReferenceType());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001646 else
1647 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001648 }
1649
Chandler Carruthd44c3102010-12-06 09:23:57 +00001650 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001651 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001652 IdLoc, LParenLoc, Init,
1653 RParenLoc);
1654 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001655 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001656 IdLoc, LParenLoc, Init,
1657 RParenLoc);
1658 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001659}
1660
John McCallfaf5fb42010-08-26 23:41:50 +00001661MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001662Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1663 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001664 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001665 SourceLocation LParenLoc,
1666 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001667 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001668 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1669 if (!LangOpts.CPlusPlus0x)
1670 return Diag(Loc, diag::err_delegation_0x_only)
1671 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001672
Alexis Huntc5575cc2011-02-26 19:13:13 +00001673 // Initialize the object.
1674 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1675 QualType(ClassDecl->getTypeForDecl(), 0));
1676 InitializationKind Kind =
1677 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1678
1679 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1680
1681 ExprResult DelegationInit =
1682 InitSeq.Perform(*this, DelegationEntity, Kind,
1683 MultiExprArg(*this, Args, NumArgs), 0);
1684 if (DelegationInit.isInvalid())
1685 return true;
1686
1687 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001688 CXXConstructorDecl *Constructor
1689 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001690 assert(Constructor && "Delegating constructor with no target?");
1691
1692 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1693
1694 // C++0x [class.base.init]p7:
1695 // The initialization of each base and member constitutes a
1696 // full-expression.
1697 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1698 if (DelegationInit.isInvalid())
1699 return true;
1700
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001701 assert(!CurContext->isDependentContext());
Alexis Huntc5575cc2011-02-26 19:13:13 +00001702 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1703 DelegationInit.takeAs<Expr>(),
1704 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001705}
1706
1707MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001708Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001709 Expr **Args, unsigned NumArgs,
1710 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001711 CXXRecordDecl *ClassDecl,
1712 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001713 bool HasDependentArg = false;
1714 for (unsigned i = 0; i < NumArgs; i++)
1715 HasDependentArg |= Args[i]->isTypeDependent();
1716
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001717 SourceLocation BaseLoc
1718 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1719
1720 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1721 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1722 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1723
1724 // C++ [class.base.init]p2:
1725 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001726 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001727 // of that class, the mem-initializer is ill-formed. A
1728 // mem-initializer-list can initialize a base class using any
1729 // name that denotes that base class type.
1730 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1731
Douglas Gregor44e7df62011-01-04 00:32:56 +00001732 if (EllipsisLoc.isValid()) {
1733 // This is a pack expansion.
1734 if (!BaseType->containsUnexpandedParameterPack()) {
1735 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1736 << SourceRange(BaseLoc, RParenLoc);
1737
1738 EllipsisLoc = SourceLocation();
1739 }
1740 } else {
1741 // Check for any unexpanded parameter packs.
1742 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1743 return true;
1744
1745 for (unsigned I = 0; I != NumArgs; ++I)
1746 if (DiagnoseUnexpandedParameterPack(Args[I]))
1747 return true;
1748 }
1749
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001750 // Check for direct and virtual base classes.
1751 const CXXBaseSpecifier *DirectBaseSpec = 0;
1752 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1753 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001754 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1755 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001756 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1757 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001758
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001759 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1760 VirtualBaseSpec);
1761
1762 // C++ [base.class.init]p2:
1763 // Unless the mem-initializer-id names a nonstatic data member of the
1764 // constructor's class or a direct or virtual base of that class, the
1765 // mem-initializer is ill-formed.
1766 if (!DirectBaseSpec && !VirtualBaseSpec) {
1767 // If the class has any dependent bases, then it's possible that
1768 // one of those types will resolve to the same type as
1769 // BaseType. Therefore, just treat this as a dependent base
1770 // class initialization. FIXME: Should we try to check the
1771 // initialization anyway? It seems odd.
1772 if (ClassDecl->hasAnyDependentBases())
1773 Dependent = true;
1774 else
1775 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1776 << BaseType << Context.getTypeDeclType(ClassDecl)
1777 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1778 }
1779 }
1780
1781 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001782 // Can't check initialization for a base of dependent type or when
1783 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001784 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001785 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001786 RParenLoc, BaseType));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001787
John McCall31168b02011-06-15 23:02:42 +00001788 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001789
Alexis Hunt1d792652011-01-08 20:30:50 +00001790 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001791 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001792 LParenLoc,
1793 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001794 RParenLoc,
1795 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001796 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001797
1798 // C++ [base.class.init]p2:
1799 // If a mem-initializer-id is ambiguous because it designates both
1800 // a direct non-virtual base class and an inherited virtual base
1801 // class, the mem-initializer is ill-formed.
1802 if (DirectBaseSpec && VirtualBaseSpec)
1803 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001804 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001805
1806 CXXBaseSpecifier *BaseSpec
1807 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1808 if (!BaseSpec)
1809 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1810
1811 // Initialize the base.
1812 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001813 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001814 InitializationKind Kind =
1815 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1816
1817 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1818
John McCalldadc5752010-08-24 06:29:42 +00001819 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001820 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001821 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001822 if (BaseInit.isInvalid())
1823 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001824
1825 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001826
1827 // C++0x [class.base.init]p7:
1828 // The initialization of each base and member constitutes a
1829 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001830 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001831 if (BaseInit.isInvalid())
1832 return true;
1833
1834 // If we are in a dependent context, template instantiation will
1835 // perform this type-checking again. Just save the arguments that we
1836 // received in a ParenListExpr.
1837 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1838 // of the information that we have about the base
1839 // initializer. However, deconstructing the ASTs is a dicey process,
1840 // and this approach is far more likely to get the corner cases right.
1841 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001842 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001843 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001844 RParenLoc, BaseType));
Alexis Hunt1d792652011-01-08 20:30:50 +00001845 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001846 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001847 LParenLoc,
1848 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001849 RParenLoc,
1850 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001851 }
1852
Alexis Hunt1d792652011-01-08 20:30:50 +00001853 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001854 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001855 LParenLoc,
1856 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001857 RParenLoc,
1858 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001859}
1860
Anders Carlsson1b00e242010-04-23 03:10:23 +00001861/// ImplicitInitializerKind - How an implicit base or member initializer should
1862/// initialize its base or member.
1863enum ImplicitInitializerKind {
1864 IIK_Default,
1865 IIK_Copy,
1866 IIK_Move
1867};
1868
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001869static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001870BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001871 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001872 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001873 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001874 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001875 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001876 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1877 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001878
John McCalldadc5752010-08-24 06:29:42 +00001879 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001880
1881 switch (ImplicitInitKind) {
1882 case IIK_Default: {
1883 InitializationKind InitKind
1884 = InitializationKind::CreateDefault(Constructor->getLocation());
1885 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1886 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001887 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001888 break;
1889 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001890
Anders Carlsson1b00e242010-04-23 03:10:23 +00001891 case IIK_Copy: {
1892 ParmVarDecl *Param = Constructor->getParamDecl(0);
1893 QualType ParamType = Param->getType().getNonReferenceType();
1894
1895 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001896 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001897 Constructor->getLocation(), ParamType,
1898 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001899
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001900 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001901 QualType ArgTy =
1902 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1903 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001904
1905 CXXCastPath BasePath;
1906 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001907 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1908 CK_UncheckedDerivedToBase,
1909 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001910
Anders Carlsson1b00e242010-04-23 03:10:23 +00001911 InitializationKind InitKind
1912 = InitializationKind::CreateDirect(Constructor->getLocation(),
1913 SourceLocation(), SourceLocation());
1914 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1915 &CopyCtorArg, 1);
1916 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001917 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001918 break;
1919 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001920
Anders Carlsson1b00e242010-04-23 03:10:23 +00001921 case IIK_Move:
1922 assert(false && "Unhandled initializer kind!");
1923 }
John McCallb268a282010-08-23 23:25:46 +00001924
Douglas Gregora40433a2010-12-07 00:41:46 +00001925 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001926 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001927 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001928
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001929 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001930 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001931 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1932 SourceLocation()),
1933 BaseSpec->isVirtual(),
1934 SourceLocation(),
1935 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001936 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001937 SourceLocation());
1938
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001939 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001940}
1941
Anders Carlsson3c1db572010-04-23 02:15:47 +00001942static bool
1943BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001944 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001945 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001946 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001947 if (Field->isInvalidDecl())
1948 return true;
1949
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001950 SourceLocation Loc = Constructor->getLocation();
1951
Anders Carlsson423f5d82010-04-23 16:04:08 +00001952 if (ImplicitInitKind == IIK_Copy) {
1953 ParmVarDecl *Param = Constructor->getParamDecl(0);
1954 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00001955
1956 // Suppress copying zero-width bitfields.
1957 if (const Expr *Width = Field->getBitWidth())
1958 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1959 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00001960
1961 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001962 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001963 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001964
1965 // Build a reference to this field within the parameter.
1966 CXXScopeSpec SS;
1967 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1968 Sema::LookupMemberName);
1969 MemberLookup.addDecl(Field, AS_public);
1970 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001971 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001972 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001973 ParamType, Loc,
1974 /*IsArrow=*/false,
1975 SS,
1976 /*FirstQualifierInScope=*/0,
1977 MemberLookup,
1978 /*TemplateArgs=*/0);
1979 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001980 return true;
1981
Douglas Gregor94f9a482010-05-05 05:51:00 +00001982 // When the field we are copying is an array, create index variables for
1983 // each dimension of the array. We use these index variables to subscript
1984 // the source array, and other clients (e.g., CodeGen) will perform the
1985 // necessary iteration with these index variables.
1986 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1987 QualType BaseType = Field->getType();
1988 QualType SizeType = SemaRef.Context.getSizeType();
1989 while (const ConstantArrayType *Array
1990 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1991 // Create the iteration variable for this array index.
1992 IdentifierInfo *IterationVarName = 0;
1993 {
1994 llvm::SmallString<8> Str;
1995 llvm::raw_svector_ostream OS(Str);
1996 OS << "__i" << IndexVariables.size();
1997 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1998 }
1999 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002000 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002001 IterationVarName, SizeType,
2002 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002003 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002004 IndexVariables.push_back(IterationVar);
2005
2006 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002007 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002008 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002009 assert(!IterationVarRef.isInvalid() &&
2010 "Reference to invented variable cannot fail!");
2011
2012 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00002013 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002014 Loc,
John McCallb268a282010-08-23 23:25:46 +00002015 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002016 Loc);
2017 if (CopyCtorArg.isInvalid())
2018 return true;
2019
2020 BaseType = Array->getElementType();
2021 }
2022
2023 // Construct the entity that we will be initializing. For an array, this
2024 // will be first element in the array, which may require several levels
2025 // of array-subscript entities.
2026 llvm::SmallVector<InitializedEntity, 4> Entities;
2027 Entities.reserve(1 + IndexVariables.size());
2028 Entities.push_back(InitializedEntity::InitializeMember(Field));
2029 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2030 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2031 0,
2032 Entities.back()));
2033
2034 // Direct-initialize to use the copy constructor.
2035 InitializationKind InitKind =
2036 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2037
2038 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2039 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2040 &CopyCtorArgE, 1);
2041
John McCalldadc5752010-08-24 06:29:42 +00002042 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002043 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002044 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002045 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002046 if (MemberInit.isInvalid())
2047 return true;
2048
2049 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00002050 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002051 MemberInit.takeAs<Expr>(), Loc,
2052 IndexVariables.data(),
2053 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002054 return false;
2055 }
2056
Anders Carlsson423f5d82010-04-23 16:04:08 +00002057 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2058
Anders Carlsson3c1db572010-04-23 02:15:47 +00002059 QualType FieldBaseElementType =
2060 SemaRef.Context.getBaseElementType(Field->getType());
2061
Anders Carlsson3c1db572010-04-23 02:15:47 +00002062 if (FieldBaseElementType->isRecordType()) {
2063 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002064 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002065 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002066
2067 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002068 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002069 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002070
Douglas Gregora40433a2010-12-07 00:41:46 +00002071 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002072 if (MemberInit.isInvalid())
2073 return true;
2074
2075 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002076 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002077 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002078 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002079 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002080 return false;
2081 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002082
Alexis Hunt8b455182011-05-17 00:19:05 +00002083 if (!Field->getParent()->isUnion()) {
2084 if (FieldBaseElementType->isReferenceType()) {
2085 SemaRef.Diag(Constructor->getLocation(),
2086 diag::err_uninitialized_member_in_ctor)
2087 << (int)Constructor->isImplicit()
2088 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2089 << 0 << Field->getDeclName();
2090 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2091 return true;
2092 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002093
Alexis Hunt8b455182011-05-17 00:19:05 +00002094 if (FieldBaseElementType.isConstQualified()) {
2095 SemaRef.Diag(Constructor->getLocation(),
2096 diag::err_uninitialized_member_in_ctor)
2097 << (int)Constructor->isImplicit()
2098 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2099 << 1 << Field->getDeclName();
2100 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2101 return true;
2102 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002103 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002104
John McCall31168b02011-06-15 23:02:42 +00002105 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2106 FieldBaseElementType->isObjCRetainableType() &&
2107 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2108 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2109 // Instant objects:
2110 // Default-initialize Objective-C pointers to NULL.
2111 CXXMemberInit
2112 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2113 Loc, Loc,
2114 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2115 Loc);
2116 return false;
2117 }
2118
Anders Carlsson3c1db572010-04-23 02:15:47 +00002119 // Nothing to initialize.
2120 CXXMemberInit = 0;
2121 return false;
2122}
John McCallbc83b3f2010-05-20 23:23:51 +00002123
2124namespace {
2125struct BaseAndFieldInfo {
2126 Sema &S;
2127 CXXConstructorDecl *Ctor;
2128 bool AnyErrorsInInits;
2129 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002130 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2131 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002132
2133 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2134 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2135 // FIXME: Handle implicit move constructors.
2136 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2137 IIK = IIK_Copy;
2138 else
2139 IIK = IIK_Default;
2140 }
2141};
2142}
2143
Richard Smith938f40b2011-06-11 17:19:42 +00002144static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
John McCallbc83b3f2010-05-20 23:23:51 +00002145 FieldDecl *Top, FieldDecl *Field) {
2146
Chandler Carruth139e9622010-06-30 02:59:29 +00002147 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002148 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002149 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002150 return false;
2151 }
2152
Richard Smith938f40b2011-06-11 17:19:42 +00002153 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2154 // has a brace-or-equal-initializer, the entity is initialized as specified
2155 // in [dcl.init].
2156 if (Field->hasInClassInitializer()) {
2157 Info.AllToInit.push_back(
2158 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2159 SourceLocation(),
2160 SourceLocation(), 0,
2161 SourceLocation()));
2162 return false;
2163 }
2164
John McCallbc83b3f2010-05-20 23:23:51 +00002165 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2166 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2167 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002168 CXXRecordDecl *FieldClassDecl
2169 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002170
2171 // Even though union members never have non-trivial default
2172 // constructions in C++03, we still build member initializers for aggregate
2173 // record types which can be union members, and C++0x allows non-trivial
2174 // default constructors for union members, so we ensure that only one
2175 // member is initialized for these.
2176 if (FieldClassDecl->isUnion()) {
2177 // First check for an explicit initializer for one field.
2178 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2179 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002180 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002181 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002182
2183 // Once we've initialized a field of an anonymous union, the union
2184 // field in the class is also initialized, so exit immediately.
2185 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002186 } else if ((*FA)->isAnonymousStructOrUnion()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002187 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002188 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002189 }
2190 }
2191
2192 // Fallthrough and construct a default initializer for the union as
2193 // a whole, which can call its default constructor if such a thing exists
2194 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2195 // behavior going forward with C++0x, when anonymous unions there are
2196 // finalized, we should revisit this.
2197 } else {
2198 // For structs, we simply descend through to initialize all members where
2199 // necessary.
2200 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2201 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Richard Smith938f40b2011-06-11 17:19:42 +00002202 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Chandler Carruth139e9622010-06-30 02:59:29 +00002203 return true;
2204 }
2205 }
John McCallbc83b3f2010-05-20 23:23:51 +00002206 }
2207
2208 // Don't try to build an implicit initializer if there were semantic
2209 // errors in any of the initializers (and therefore we might be
2210 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002211 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002212 return false;
2213
Alexis Hunt1d792652011-01-08 20:30:50 +00002214 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002215 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2216 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002217
Francois Pichetd583da02010-12-04 09:14:42 +00002218 if (Init)
2219 Info.AllToInit.push_back(Init);
2220
John McCallbc83b3f2010-05-20 23:23:51 +00002221 return false;
2222}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002223
2224bool
2225Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2226 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002227 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002228 Constructor->setNumCtorInitializers(1);
2229 CXXCtorInitializer **initializer =
2230 new (Context) CXXCtorInitializer*[1];
2231 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2232 Constructor->setCtorInitializers(initializer);
2233
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002234 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2235 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2236 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2237 }
2238
Alexis Hunte2622992011-05-05 00:05:47 +00002239 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002240
Alexis Hunt61bc1732011-05-01 07:04:31 +00002241 return false;
2242}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002243
John McCall1b1a1db2011-06-17 00:18:42 +00002244bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2245 CXXCtorInitializer **Initializers,
2246 unsigned NumInitializers,
2247 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002248 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002249 // Just store the initializers as written, they will be checked during
2250 // instantiation.
2251 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002252 Constructor->setNumCtorInitializers(NumInitializers);
2253 CXXCtorInitializer **baseOrMemberInitializers =
2254 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002255 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002256 NumInitializers * sizeof(CXXCtorInitializer*));
2257 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002258 }
2259
2260 return false;
2261 }
2262
John McCallbc83b3f2010-05-20 23:23:51 +00002263 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002264
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002265 // We need to build the initializer AST according to order of construction
2266 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002267 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002268 if (!ClassDecl)
2269 return true;
2270
Eli Friedman9cf6b592009-11-09 19:20:36 +00002271 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002272
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002273 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002274 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002275
2276 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002277 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002278 else
Francois Pichetd583da02010-12-04 09:14:42 +00002279 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002280 }
2281
Anders Carlsson43c64af2010-04-21 19:52:01 +00002282 // Keep track of the direct virtual bases.
2283 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2284 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2285 E = ClassDecl->bases_end(); I != E; ++I) {
2286 if (I->isVirtual())
2287 DirectVBases.insert(I);
2288 }
2289
Anders Carlssondb0a9652010-04-02 06:26:44 +00002290 // Push virtual bases before others.
2291 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2292 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2293
Alexis Hunt1d792652011-01-08 20:30:50 +00002294 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002295 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2296 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002297 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002298 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002299 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002300 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002301 VBase, IsInheritedVirtualBase,
2302 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002303 HadError = true;
2304 continue;
2305 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002306
John McCallbc83b3f2010-05-20 23:23:51 +00002307 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002308 }
2309 }
Mike Stump11289f42009-09-09 15:08:12 +00002310
John McCallbc83b3f2010-05-20 23:23:51 +00002311 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002312 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2313 E = ClassDecl->bases_end(); Base != E; ++Base) {
2314 // Virtuals are in the virtual base list and already constructed.
2315 if (Base->isVirtual())
2316 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Alexis Hunt1d792652011-01-08 20:30:50 +00002318 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002319 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2320 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002321 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002322 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002323 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002324 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002325 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002326 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002327 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002328 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002329
John McCallbc83b3f2010-05-20 23:23:51 +00002330 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002331 }
2332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
John McCallbc83b3f2010-05-20 23:23:51 +00002334 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002335 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002336 E = ClassDecl->field_end(); Field != E; ++Field) {
2337 if ((*Field)->getType()->isIncompleteArrayType()) {
2338 assert(ClassDecl->hasFlexibleArrayMember() &&
2339 "Incomplete array type is not valid");
2340 continue;
2341 }
Richard Smith938f40b2011-06-11 17:19:42 +00002342 if (CollectFieldInitializer(*this, Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002343 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002344 }
Mike Stump11289f42009-09-09 15:08:12 +00002345
John McCallbc83b3f2010-05-20 23:23:51 +00002346 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002347 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002348 Constructor->setNumCtorInitializers(NumInitializers);
2349 CXXCtorInitializer **baseOrMemberInitializers =
2350 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002351 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002352 NumInitializers * sizeof(CXXCtorInitializer*));
2353 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002354
John McCalla6309952010-03-16 21:39:52 +00002355 // Constructors implicitly reference the base and member
2356 // destructors.
2357 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2358 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002359 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002360
2361 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002362}
2363
Eli Friedman952c15d2009-07-21 19:28:10 +00002364static void *GetKeyForTopLevelField(FieldDecl *Field) {
2365 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002366 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002367 if (RT->getDecl()->isAnonymousStructOrUnion())
2368 return static_cast<void *>(RT->getDecl());
2369 }
2370 return static_cast<void *>(Field);
2371}
2372
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002373static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002374 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002375}
2376
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002377static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002378 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002379 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002380 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002381
Eli Friedman952c15d2009-07-21 19:28:10 +00002382 // For fields injected into the class via declaration of an anonymous union,
2383 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002384 FieldDecl *Field = Member->getAnyMember();
2385
John McCall23eebd92010-04-10 09:28:51 +00002386 // If the field is a member of an anonymous struct or union, our key
2387 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002388 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002389 if (RD->isAnonymousStructOrUnion()) {
2390 while (true) {
2391 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2392 if (Parent->isAnonymousStructOrUnion())
2393 RD = Parent;
2394 else
2395 break;
2396 }
2397
Anders Carlsson83ac3122010-03-30 16:19:37 +00002398 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002399 }
Mike Stump11289f42009-09-09 15:08:12 +00002400
Anders Carlssona942dcd2010-03-30 15:39:27 +00002401 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002402}
2403
Anders Carlssone857b292010-04-02 03:37:03 +00002404static void
2405DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002406 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002407 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002408 unsigned NumInits) {
2409 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002410 return;
Mike Stump11289f42009-09-09 15:08:12 +00002411
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002412 // Don't check initializers order unless the warning is enabled at the
2413 // location of at least one initializer.
2414 bool ShouldCheckOrder = false;
2415 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002416 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002417 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2418 Init->getSourceLocation())
2419 != Diagnostic::Ignored) {
2420 ShouldCheckOrder = true;
2421 break;
2422 }
2423 }
2424 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002425 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002426
John McCallbb7b6582010-04-10 07:37:23 +00002427 // Build the list of bases and members in the order that they'll
2428 // actually be initialized. The explicit initializers should be in
2429 // this same order but may be missing things.
2430 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002431
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002432 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2433
John McCallbb7b6582010-04-10 07:37:23 +00002434 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002435 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002436 ClassDecl->vbases_begin(),
2437 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002438 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002439
John McCallbb7b6582010-04-10 07:37:23 +00002440 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002441 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002442 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002443 if (Base->isVirtual())
2444 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002445 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002446 }
Mike Stump11289f42009-09-09 15:08:12 +00002447
John McCallbb7b6582010-04-10 07:37:23 +00002448 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002449 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2450 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002451 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002452
John McCallbb7b6582010-04-10 07:37:23 +00002453 unsigned NumIdealInits = IdealInitKeys.size();
2454 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002455
Alexis Hunt1d792652011-01-08 20:30:50 +00002456 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002457 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002458 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002459 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002460
2461 // Scan forward to try to find this initializer in the idealized
2462 // initializers list.
2463 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2464 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002465 break;
John McCallbb7b6582010-04-10 07:37:23 +00002466
2467 // If we didn't find this initializer, it must be because we
2468 // scanned past it on a previous iteration. That can only
2469 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002470 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002471 Sema::SemaDiagnosticBuilder D =
2472 SemaRef.Diag(PrevInit->getSourceLocation(),
2473 diag::warn_initializer_out_of_order);
2474
Francois Pichetd583da02010-12-04 09:14:42 +00002475 if (PrevInit->isAnyMemberInitializer())
2476 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002477 else
2478 D << 1 << PrevInit->getBaseClassInfo()->getType();
2479
Francois Pichetd583da02010-12-04 09:14:42 +00002480 if (Init->isAnyMemberInitializer())
2481 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002482 else
2483 D << 1 << Init->getBaseClassInfo()->getType();
2484
2485 // Move back to the initializer's location in the ideal list.
2486 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2487 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002488 break;
John McCallbb7b6582010-04-10 07:37:23 +00002489
2490 assert(IdealIndex != NumIdealInits &&
2491 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002492 }
John McCallbb7b6582010-04-10 07:37:23 +00002493
2494 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002495 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002496}
2497
John McCall23eebd92010-04-10 09:28:51 +00002498namespace {
2499bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002500 CXXCtorInitializer *Init,
2501 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002502 if (!PrevInit) {
2503 PrevInit = Init;
2504 return false;
2505 }
2506
2507 if (FieldDecl *Field = Init->getMember())
2508 S.Diag(Init->getSourceLocation(),
2509 diag::err_multiple_mem_initialization)
2510 << Field->getDeclName()
2511 << Init->getSourceRange();
2512 else {
John McCall424cec92011-01-19 06:33:43 +00002513 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002514 assert(BaseClass && "neither field nor base");
2515 S.Diag(Init->getSourceLocation(),
2516 diag::err_multiple_base_initialization)
2517 << QualType(BaseClass, 0)
2518 << Init->getSourceRange();
2519 }
2520 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2521 << 0 << PrevInit->getSourceRange();
2522
2523 return true;
2524}
2525
Alexis Hunt1d792652011-01-08 20:30:50 +00002526typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002527typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2528
2529bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002530 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002531 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002532 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002533 RecordDecl *Parent = Field->getParent();
2534 if (!Parent->isAnonymousStructOrUnion())
2535 return false;
2536
2537 NamedDecl *Child = Field;
2538 do {
2539 if (Parent->isUnion()) {
2540 UnionEntry &En = Unions[Parent];
2541 if (En.first && En.first != Child) {
2542 S.Diag(Init->getSourceLocation(),
2543 diag::err_multiple_mem_union_initialization)
2544 << Field->getDeclName()
2545 << Init->getSourceRange();
2546 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2547 << 0 << En.second->getSourceRange();
2548 return true;
2549 } else if (!En.first) {
2550 En.first = Child;
2551 En.second = Init;
2552 }
2553 }
2554
2555 Child = Parent;
2556 Parent = cast<RecordDecl>(Parent->getDeclContext());
2557 } while (Parent->isAnonymousStructOrUnion());
2558
2559 return false;
2560}
2561}
2562
Anders Carlssone857b292010-04-02 03:37:03 +00002563/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002564void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002565 SourceLocation ColonLoc,
2566 MemInitTy **meminits, unsigned NumMemInits,
2567 bool AnyErrors) {
2568 if (!ConstructorDecl)
2569 return;
2570
2571 AdjustDeclIfTemplate(ConstructorDecl);
2572
2573 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002574 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002575
2576 if (!Constructor) {
2577 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2578 return;
2579 }
2580
Alexis Hunt1d792652011-01-08 20:30:50 +00002581 CXXCtorInitializer **MemInits =
2582 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002583
2584 // Mapping for the duplicate initializers check.
2585 // For member initializers, this is keyed with a FieldDecl*.
2586 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002587 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002588
2589 // Mapping for the inconsistent anonymous-union initializers check.
2590 RedundantUnionMap MemberUnions;
2591
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002592 bool HadError = false;
2593 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002594 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002595
Abramo Bagnara341d7832010-05-26 18:09:23 +00002596 // Set the source order index.
2597 Init->setSourceOrder(i);
2598
Francois Pichetd583da02010-12-04 09:14:42 +00002599 if (Init->isAnyMemberInitializer()) {
2600 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002601 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2602 CheckRedundantUnionInit(*this, Init, MemberUnions))
2603 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002604 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002605 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2606 if (CheckRedundantInit(*this, Init, Members[Key]))
2607 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002608 } else {
2609 assert(Init->isDelegatingInitializer());
2610 // This must be the only initializer
2611 if (i != 0 || NumMemInits > 1) {
2612 Diag(MemInits[0]->getSourceLocation(),
2613 diag::err_delegating_initializer_alone)
2614 << MemInits[0]->getSourceRange();
2615 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002616 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002617 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002618 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002619 // Return immediately as the initializer is set.
2620 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002621 }
Anders Carlssone857b292010-04-02 03:37:03 +00002622 }
2623
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002624 if (HadError)
2625 return;
2626
Anders Carlssone857b292010-04-02 03:37:03 +00002627 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002628
Alexis Hunt1d792652011-01-08 20:30:50 +00002629 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002630}
2631
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002632void
John McCalla6309952010-03-16 21:39:52 +00002633Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2634 CXXRecordDecl *ClassDecl) {
2635 // Ignore dependent contexts.
2636 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002637 return;
John McCall1064d7e2010-03-16 05:22:47 +00002638
2639 // FIXME: all the access-control diagnostics are positioned on the
2640 // field/base declaration. That's probably good; that said, the
2641 // user might reasonably want to know why the destructor is being
2642 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002643
Anders Carlssondee9a302009-11-17 04:44:12 +00002644 // Non-static data members.
2645 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2646 E = ClassDecl->field_end(); I != E; ++I) {
2647 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002648 if (Field->isInvalidDecl())
2649 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002650 QualType FieldType = Context.getBaseElementType(Field->getType());
2651
2652 const RecordType* RT = FieldType->getAs<RecordType>();
2653 if (!RT)
2654 continue;
2655
2656 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002657 if (FieldClassDecl->isInvalidDecl())
2658 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002659 if (FieldClassDecl->hasTrivialDestructor())
2660 continue;
2661
Douglas Gregore71edda2010-07-01 22:47:18 +00002662 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002663 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002664 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002665 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002666 << Field->getDeclName()
2667 << FieldType);
2668
John McCalla6309952010-03-16 21:39:52 +00002669 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002670 }
2671
John McCall1064d7e2010-03-16 05:22:47 +00002672 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2673
Anders Carlssondee9a302009-11-17 04:44:12 +00002674 // Bases.
2675 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2676 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002677 // Bases are always records in a well-formed non-dependent class.
2678 const RecordType *RT = Base->getType()->getAs<RecordType>();
2679
2680 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002681 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002682 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002683
John McCall1064d7e2010-03-16 05:22:47 +00002684 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002685 // If our base class is invalid, we probably can't get its dtor anyway.
2686 if (BaseClassDecl->isInvalidDecl())
2687 continue;
2688 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002689 if (BaseClassDecl->hasTrivialDestructor())
2690 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002691
Douglas Gregore71edda2010-07-01 22:47:18 +00002692 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002693 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002694
2695 // FIXME: caret should be on the start of the class name
2696 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002697 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002698 << Base->getType()
2699 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002700
John McCalla6309952010-03-16 21:39:52 +00002701 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002702 }
2703
2704 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002705 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2706 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002707
2708 // Bases are always records in a well-formed non-dependent class.
2709 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2710
2711 // Ignore direct virtual bases.
2712 if (DirectVirtualBases.count(RT))
2713 continue;
2714
John McCall1064d7e2010-03-16 05:22:47 +00002715 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002716 // If our base class is invalid, we probably can't get its dtor anyway.
2717 if (BaseClassDecl->isInvalidDecl())
2718 continue;
2719 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002720 if (BaseClassDecl->hasTrivialDestructor())
2721 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002722
Douglas Gregore71edda2010-07-01 22:47:18 +00002723 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002724 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002725 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002726 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002727 << VBase->getType());
2728
John McCalla6309952010-03-16 21:39:52 +00002729 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002730 }
2731}
2732
John McCall48871652010-08-21 09:40:31 +00002733void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002734 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002735 return;
Mike Stump11289f42009-09-09 15:08:12 +00002736
Mike Stump11289f42009-09-09 15:08:12 +00002737 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002738 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002739 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002740}
2741
Mike Stump11289f42009-09-09 15:08:12 +00002742bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002743 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002744 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002745 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002746 else
John McCall02db245d2010-08-18 09:41:07 +00002747 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002748}
2749
Anders Carlssoneabf7702009-08-27 00:13:57 +00002750bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002751 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002752 if (!getLangOptions().CPlusPlus)
2753 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002754
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002755 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002756 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002757
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002758 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002759 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002760 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002761 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002762
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002763 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002764 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002765 }
Mike Stump11289f42009-09-09 15:08:12 +00002766
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002767 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002768 if (!RT)
2769 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002770
John McCall67da35c2010-02-04 22:26:26 +00002771 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002772
John McCall02db245d2010-08-18 09:41:07 +00002773 // We can't answer whether something is abstract until it has a
2774 // definition. If it's currently being defined, we'll walk back
2775 // over all the declarations when we have a full definition.
2776 const CXXRecordDecl *Def = RD->getDefinition();
2777 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002778 return false;
2779
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002780 if (!RD->isAbstract())
2781 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002782
Anders Carlssoneabf7702009-08-27 00:13:57 +00002783 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002784 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002785
John McCall02db245d2010-08-18 09:41:07 +00002786 return true;
2787}
2788
2789void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2790 // Check if we've already emitted the list of pure virtual functions
2791 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002792 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002793 return;
Mike Stump11289f42009-09-09 15:08:12 +00002794
Douglas Gregor4165bd62010-03-23 23:47:56 +00002795 CXXFinalOverriderMap FinalOverriders;
2796 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002797
Anders Carlssona2f74f32010-06-03 01:00:02 +00002798 // Keep a set of seen pure methods so we won't diagnose the same method
2799 // more than once.
2800 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2801
Douglas Gregor4165bd62010-03-23 23:47:56 +00002802 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2803 MEnd = FinalOverriders.end();
2804 M != MEnd;
2805 ++M) {
2806 for (OverridingMethods::iterator SO = M->second.begin(),
2807 SOEnd = M->second.end();
2808 SO != SOEnd; ++SO) {
2809 // C++ [class.abstract]p4:
2810 // A class is abstract if it contains or inherits at least one
2811 // pure virtual function for which the final overrider is pure
2812 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002813
Douglas Gregor4165bd62010-03-23 23:47:56 +00002814 //
2815 if (SO->second.size() != 1)
2816 continue;
2817
2818 if (!SO->second.front().Method->isPure())
2819 continue;
2820
Anders Carlssona2f74f32010-06-03 01:00:02 +00002821 if (!SeenPureMethods.insert(SO->second.front().Method))
2822 continue;
2823
Douglas Gregor4165bd62010-03-23 23:47:56 +00002824 Diag(SO->second.front().Method->getLocation(),
2825 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002826 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002827 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002828 }
2829
2830 if (!PureVirtualClassDiagSet)
2831 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2832 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002833}
2834
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002835namespace {
John McCall02db245d2010-08-18 09:41:07 +00002836struct AbstractUsageInfo {
2837 Sema &S;
2838 CXXRecordDecl *Record;
2839 CanQualType AbstractType;
2840 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002841
John McCall02db245d2010-08-18 09:41:07 +00002842 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2843 : S(S), Record(Record),
2844 AbstractType(S.Context.getCanonicalType(
2845 S.Context.getTypeDeclType(Record))),
2846 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002847
John McCall02db245d2010-08-18 09:41:07 +00002848 void DiagnoseAbstractType() {
2849 if (Invalid) return;
2850 S.DiagnoseAbstractType(Record);
2851 Invalid = true;
2852 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002853
John McCall02db245d2010-08-18 09:41:07 +00002854 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2855};
2856
2857struct CheckAbstractUsage {
2858 AbstractUsageInfo &Info;
2859 const NamedDecl *Ctx;
2860
2861 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2862 : Info(Info), Ctx(Ctx) {}
2863
2864 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2865 switch (TL.getTypeLocClass()) {
2866#define ABSTRACT_TYPELOC(CLASS, PARENT)
2867#define TYPELOC(CLASS, PARENT) \
2868 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2869#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002870 }
John McCall02db245d2010-08-18 09:41:07 +00002871 }
Mike Stump11289f42009-09-09 15:08:12 +00002872
John McCall02db245d2010-08-18 09:41:07 +00002873 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2874 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2875 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002876 if (!TL.getArg(I))
2877 continue;
2878
John McCall02db245d2010-08-18 09:41:07 +00002879 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2880 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002881 }
John McCall02db245d2010-08-18 09:41:07 +00002882 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002883
John McCall02db245d2010-08-18 09:41:07 +00002884 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2885 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2886 }
Mike Stump11289f42009-09-09 15:08:12 +00002887
John McCall02db245d2010-08-18 09:41:07 +00002888 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2889 // Visit the type parameters from a permissive context.
2890 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2891 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2892 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2893 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2894 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2895 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002896 }
John McCall02db245d2010-08-18 09:41:07 +00002897 }
Mike Stump11289f42009-09-09 15:08:12 +00002898
John McCall02db245d2010-08-18 09:41:07 +00002899 // Visit pointee types from a permissive context.
2900#define CheckPolymorphic(Type) \
2901 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2902 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2903 }
2904 CheckPolymorphic(PointerTypeLoc)
2905 CheckPolymorphic(ReferenceTypeLoc)
2906 CheckPolymorphic(MemberPointerTypeLoc)
2907 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002908
John McCall02db245d2010-08-18 09:41:07 +00002909 /// Handle all the types we haven't given a more specific
2910 /// implementation for above.
2911 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2912 // Every other kind of type that we haven't called out already
2913 // that has an inner type is either (1) sugar or (2) contains that
2914 // inner type in some way as a subobject.
2915 if (TypeLoc Next = TL.getNextTypeLoc())
2916 return Visit(Next, Sel);
2917
2918 // If there's no inner type and we're in a permissive context,
2919 // don't diagnose.
2920 if (Sel == Sema::AbstractNone) return;
2921
2922 // Check whether the type matches the abstract type.
2923 QualType T = TL.getType();
2924 if (T->isArrayType()) {
2925 Sel = Sema::AbstractArrayType;
2926 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002927 }
John McCall02db245d2010-08-18 09:41:07 +00002928 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2929 if (CT != Info.AbstractType) return;
2930
2931 // It matched; do some magic.
2932 if (Sel == Sema::AbstractArrayType) {
2933 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2934 << T << TL.getSourceRange();
2935 } else {
2936 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2937 << Sel << T << TL.getSourceRange();
2938 }
2939 Info.DiagnoseAbstractType();
2940 }
2941};
2942
2943void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2944 Sema::AbstractDiagSelID Sel) {
2945 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2946}
2947
2948}
2949
2950/// Check for invalid uses of an abstract type in a method declaration.
2951static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2952 CXXMethodDecl *MD) {
2953 // No need to do the check on definitions, which require that
2954 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002955 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00002956 return;
2957
2958 // For safety's sake, just ignore it if we don't have type source
2959 // information. This should never happen for non-implicit methods,
2960 // but...
2961 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2962 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2963}
2964
2965/// Check for invalid uses of an abstract type within a class definition.
2966static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2967 CXXRecordDecl *RD) {
2968 for (CXXRecordDecl::decl_iterator
2969 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2970 Decl *D = *I;
2971 if (D->isImplicit()) continue;
2972
2973 // Methods and method templates.
2974 if (isa<CXXMethodDecl>(D)) {
2975 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2976 } else if (isa<FunctionTemplateDecl>(D)) {
2977 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2978 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2979
2980 // Fields and static variables.
2981 } else if (isa<FieldDecl>(D)) {
2982 FieldDecl *FD = cast<FieldDecl>(D);
2983 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2984 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2985 } else if (isa<VarDecl>(D)) {
2986 VarDecl *VD = cast<VarDecl>(D);
2987 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2988 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2989
2990 // Nested classes and class templates.
2991 } else if (isa<CXXRecordDecl>(D)) {
2992 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2993 } else if (isa<ClassTemplateDecl>(D)) {
2994 CheckAbstractClassUsage(Info,
2995 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2996 }
2997 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002998}
2999
Douglas Gregorc99f1552009-12-03 18:33:45 +00003000/// \brief Perform semantic checks on a class definition that has been
3001/// completing, introducing implicitly-declared members, checking for
3002/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003003void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003004 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003005 return;
3006
John McCall02db245d2010-08-18 09:41:07 +00003007 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3008 AbstractUsageInfo Info(*this, Record);
3009 CheckAbstractClassUsage(Info, Record);
3010 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003011
3012 // If this is not an aggregate type and has no user-declared constructor,
3013 // complain about any non-static data members of reference or const scalar
3014 // type, since they will never get initializers.
3015 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3016 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3017 bool Complained = false;
3018 for (RecordDecl::field_iterator F = Record->field_begin(),
3019 FEnd = Record->field_end();
3020 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003021 if (F->hasInClassInitializer())
3022 continue;
3023
Douglas Gregor454a5b62010-04-15 00:00:53 +00003024 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003025 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003026 if (!Complained) {
3027 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3028 << Record->getTagKind() << Record;
3029 Complained = true;
3030 }
3031
3032 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3033 << F->getType()->isReferenceType()
3034 << F->getDeclName();
3035 }
3036 }
3037 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003038
Anders Carlssone771e762011-01-25 18:08:22 +00003039 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003040 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003041
3042 if (Record->getIdentifier()) {
3043 // C++ [class.mem]p13:
3044 // If T is the name of a class, then each of the following shall have a
3045 // name different from T:
3046 // - every member of every anonymous union that is a member of class T.
3047 //
3048 // C++ [class.mem]p14:
3049 // In addition, if class T has a user-declared constructor (12.1), every
3050 // non-static data member of class T shall have a name different from T.
3051 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003052 R.first != R.second; ++R.first) {
3053 NamedDecl *D = *R.first;
3054 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3055 isa<IndirectFieldDecl>(D)) {
3056 Diag(D->getLocation(), diag::err_member_name_of_class)
3057 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003058 break;
3059 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003060 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003061 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003062
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003063 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003064 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003065 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003066 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003067 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3068 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3069 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003070
3071 // See if a method overloads virtual methods in a base
3072 /// class without overriding any.
3073 if (!Record->isDependentType()) {
3074 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3075 MEnd = Record->method_end();
3076 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003077 if (!(*M)->isStatic())
3078 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003079 }
3080 }
Sebastian Redl08905022011-02-05 19:23:19 +00003081
3082 // Declare inherited constructors. We do this eagerly here because:
3083 // - The standard requires an eager diagnostic for conflicting inherited
3084 // constructors from different classes.
3085 // - The lazy declaration of the other implicit constructors is so as to not
3086 // waste space and performance on classes that are not meant to be
3087 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3088 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003089 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003090
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003091 if (!Record->isDependentType())
3092 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003093}
3094
3095void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003096 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3097 ME = Record->method_end();
3098 MI != ME; ++MI) {
3099 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3100 switch (getSpecialMember(*MI)) {
3101 case CXXDefaultConstructor:
3102 CheckExplicitlyDefaultedDefaultConstructor(
3103 cast<CXXConstructorDecl>(*MI));
3104 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003105
Alexis Huntf91729462011-05-12 22:46:25 +00003106 case CXXDestructor:
3107 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3108 break;
3109
3110 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003111 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3112 break;
3113
Alexis Huntf91729462011-05-12 22:46:25 +00003114 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003115 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003116 break;
3117
Alexis Hunt119c10e2011-05-25 23:16:36 +00003118 case CXXMoveConstructor:
3119 case CXXMoveAssignment:
3120 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3121 break;
3122
Alexis Huntf91729462011-05-12 22:46:25 +00003123 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00003124 // FIXME: Do moves once they exist
Alexis Huntf91729462011-05-12 22:46:25 +00003125 llvm_unreachable("non-special member explicitly defaulted!");
3126 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003127 }
3128 }
3129
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003130}
3131
3132void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3133 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3134
3135 // Whether this was the first-declared instance of the constructor.
3136 // This affects whether we implicitly add an exception spec (and, eventually,
3137 // constexpr). It is also ill-formed to explicitly default a constructor such
3138 // that it would be deleted. (C++0x [decl.fct.def.default])
3139 bool First = CD == CD->getCanonicalDecl();
3140
Alexis Hunt913820d2011-05-13 06:10:58 +00003141 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003142 if (CD->getNumParams() != 0) {
3143 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3144 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003145 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003146 }
3147
3148 ImplicitExceptionSpecification Spec
3149 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3150 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003151 if (EPI.ExceptionSpecType == EST_Delayed) {
3152 // Exception specification depends on some deferred part of the class. We'll
3153 // try again when the class's definition has been fully processed.
3154 return;
3155 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003156 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3157 *ExceptionType = Context.getFunctionType(
3158 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3159
3160 if (CtorType->hasExceptionSpec()) {
3161 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003162 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003163 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003164 PDiag(),
3165 ExceptionType, SourceLocation(),
3166 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003167 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003168 }
3169 } else if (First) {
3170 // We set the declaration to have the computed exception spec here.
3171 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003172 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003173 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3174 }
Alexis Huntb3153022011-05-12 03:51:48 +00003175
Alexis Hunt913820d2011-05-13 06:10:58 +00003176 if (HadError) {
3177 CD->setInvalidDecl();
3178 return;
3179 }
3180
Alexis Huntb3153022011-05-12 03:51:48 +00003181 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003182 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003183 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003184 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003185 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003186 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003187 CD->setInvalidDecl();
3188 }
3189 }
3190}
3191
3192void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3193 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3194
3195 // Whether this was the first-declared instance of the constructor.
3196 bool First = CD == CD->getCanonicalDecl();
3197
3198 bool HadError = false;
3199 if (CD->getNumParams() != 1) {
3200 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3201 << CD->getSourceRange();
3202 HadError = true;
3203 }
3204
3205 ImplicitExceptionSpecification Spec(Context);
3206 bool Const;
3207 llvm::tie(Spec, Const) =
3208 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3209
3210 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3211 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3212 *ExceptionType = Context.getFunctionType(
3213 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3214
3215 // Check for parameter type matching.
3216 // This is a copy ctor so we know it's a cv-qualified reference to T.
3217 QualType ArgType = CtorType->getArgType(0);
3218 if (ArgType->getPointeeType().isVolatileQualified()) {
3219 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3220 HadError = true;
3221 }
3222 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3223 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3224 HadError = true;
3225 }
3226
3227 if (CtorType->hasExceptionSpec()) {
3228 if (CheckEquivalentExceptionSpec(
3229 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003230 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003231 PDiag(),
3232 ExceptionType, SourceLocation(),
3233 CtorType, CD->getLocation())) {
3234 HadError = true;
3235 }
3236 } else if (First) {
3237 // We set the declaration to have the computed exception spec here.
3238 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003239 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003240 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3241 }
3242
3243 if (HadError) {
3244 CD->setInvalidDecl();
3245 return;
3246 }
3247
3248 if (ShouldDeleteCopyConstructor(CD)) {
3249 if (First) {
3250 CD->setDeletedAsWritten();
3251 } else {
3252 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003253 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003254 CD->setInvalidDecl();
3255 }
Alexis Huntb3153022011-05-12 03:51:48 +00003256 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003257}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003258
Alexis Huntc9a55732011-05-14 05:23:28 +00003259void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3260 assert(MD->isExplicitlyDefaulted());
3261
3262 // Whether this was the first-declared instance of the operator
3263 bool First = MD == MD->getCanonicalDecl();
3264
3265 bool HadError = false;
3266 if (MD->getNumParams() != 1) {
3267 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3268 << MD->getSourceRange();
3269 HadError = true;
3270 }
3271
3272 QualType ReturnType =
3273 MD->getType()->getAs<FunctionType>()->getResultType();
3274 if (!ReturnType->isLValueReferenceType() ||
3275 !Context.hasSameType(
3276 Context.getCanonicalType(ReturnType->getPointeeType()),
3277 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3278 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3279 HadError = true;
3280 }
3281
3282 ImplicitExceptionSpecification Spec(Context);
3283 bool Const;
3284 llvm::tie(Spec, Const) =
3285 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3286
3287 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3288 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3289 *ExceptionType = Context.getFunctionType(
3290 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3291
Alexis Huntc9a55732011-05-14 05:23:28 +00003292 QualType ArgType = OperType->getArgType(0);
Alexis Hunt604aeb32011-05-17 20:44:43 +00003293 if (!ArgType->isReferenceType()) {
3294 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003295 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003296 } else {
3297 if (ArgType->getPointeeType().isVolatileQualified()) {
3298 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3299 HadError = true;
3300 }
3301 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3302 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3303 HadError = true;
3304 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003305 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003306
Alexis Huntc9a55732011-05-14 05:23:28 +00003307 if (OperType->getTypeQuals()) {
3308 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3309 HadError = true;
3310 }
3311
3312 if (OperType->hasExceptionSpec()) {
3313 if (CheckEquivalentExceptionSpec(
3314 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003315 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003316 PDiag(),
3317 ExceptionType, SourceLocation(),
3318 OperType, MD->getLocation())) {
3319 HadError = true;
3320 }
3321 } else if (First) {
3322 // We set the declaration to have the computed exception spec here.
3323 // We duplicate the one parameter type.
3324 EPI.RefQualifier = OperType->getRefQualifier();
3325 EPI.ExtInfo = OperType->getExtInfo();
3326 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3327 }
3328
3329 if (HadError) {
3330 MD->setInvalidDecl();
3331 return;
3332 }
3333
3334 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3335 if (First) {
3336 MD->setDeletedAsWritten();
3337 } else {
3338 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003339 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003340 MD->setInvalidDecl();
3341 }
3342 }
3343}
3344
Alexis Huntf91729462011-05-12 22:46:25 +00003345void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3346 assert(DD->isExplicitlyDefaulted());
3347
3348 // Whether this was the first-declared instance of the destructor.
3349 bool First = DD == DD->getCanonicalDecl();
3350
3351 ImplicitExceptionSpecification Spec
3352 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3353 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3354 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3355 *ExceptionType = Context.getFunctionType(
3356 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3357
3358 if (DtorType->hasExceptionSpec()) {
3359 if (CheckEquivalentExceptionSpec(
3360 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003361 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00003362 PDiag(),
3363 ExceptionType, SourceLocation(),
3364 DtorType, DD->getLocation())) {
3365 DD->setInvalidDecl();
3366 return;
3367 }
3368 } else if (First) {
3369 // We set the declaration to have the computed exception spec here.
3370 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003371 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003372 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3373 }
3374
3375 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003376 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003377 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003378 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003379 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003380 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003381 DD->setInvalidDecl();
3382 }
Alexis Huntf91729462011-05-12 22:46:25 +00003383 }
Alexis Huntf91729462011-05-12 22:46:25 +00003384}
3385
Alexis Huntea6f0322011-05-11 22:34:38 +00003386bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3387 CXXRecordDecl *RD = CD->getParent();
3388 assert(!RD->isDependentType() && "do deletion after instantiation");
3389 if (!LangOpts.CPlusPlus0x)
3390 return false;
3391
Alexis Hunte77a28f2011-05-18 03:41:58 +00003392 SourceLocation Loc = CD->getLocation();
3393
Alexis Huntea6f0322011-05-11 22:34:38 +00003394 // Do access control from the constructor
3395 ContextRAII CtorContext(*this, CD);
3396
3397 bool Union = RD->isUnion();
3398 bool AllConst = true;
3399
Alexis Huntea6f0322011-05-11 22:34:38 +00003400 // We do this because we should never actually use an anonymous
3401 // union's constructor.
3402 if (Union && RD->isAnonymousStructOrUnion())
3403 return false;
3404
3405 // FIXME: We should put some diagnostic logic right into this function.
3406
3407 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00003408 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00003409
3410 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3411 BE = RD->bases_end();
3412 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003413 // We'll handle this one later
3414 if (BI->isVirtual())
3415 continue;
3416
Alexis Huntea6f0322011-05-11 22:34:38 +00003417 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3418 assert(BaseDecl && "base isn't a CXXRecordDecl");
3419
3420 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00003421 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00003422 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3423 if (BaseDtor->isDeleted())
3424 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003425 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003426 AR_accessible)
3427 return true;
3428
Alexis Huntea6f0322011-05-11 22:34:38 +00003429 // -- any [direct base class either] has no default constructor or
3430 // overload resolution as applied to [its] default constructor
3431 // results in an ambiguity or in a function that is deleted or
3432 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003433 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3434 if (!BaseDefault || BaseDefault->isDeleted())
3435 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003436
Alexis Hunteef8ee02011-06-10 03:50:41 +00003437 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3438 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003439 return true;
3440 }
3441
3442 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3443 BE = RD->vbases_end();
3444 BI != BE; ++BI) {
3445 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3446 assert(BaseDecl && "base isn't a CXXRecordDecl");
3447
3448 // -- any [virtual base class] has a type with a destructor that is
3449 // delete or inaccessible from the defaulted default constructor
3450 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3451 if (BaseDtor->isDeleted())
3452 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003453 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003454 AR_accessible)
3455 return true;
3456
3457 // -- any [virtual base class either] has no default constructor or
3458 // overload resolution as applied to [its] default constructor
3459 // results in an ambiguity or in a function that is deleted or
3460 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003461 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3462 if (!BaseDefault || BaseDefault->isDeleted())
3463 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003464
Alexis Hunteef8ee02011-06-10 03:50:41 +00003465 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3466 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003467 return true;
3468 }
3469
3470 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3471 FE = RD->field_end();
3472 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00003473 if (FI->isInvalidDecl())
3474 continue;
3475
Alexis Huntea6f0322011-05-11 22:34:38 +00003476 QualType FieldType = Context.getBaseElementType(FI->getType());
3477 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00003478
Alexis Huntea6f0322011-05-11 22:34:38 +00003479 // -- any non-static data member with no brace-or-equal-initializer is of
3480 // reference type
Richard Smith938f40b2011-06-11 17:19:42 +00003481 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Alexis Huntea6f0322011-05-11 22:34:38 +00003482 return true;
3483
3484 // -- X is a union and all its variant members are of const-qualified type
3485 // (or array thereof)
3486 if (Union && !FieldType.isConstQualified())
3487 AllConst = false;
3488
3489 if (FieldRecord) {
3490 // -- X is a union-like class that has a variant member with a non-trivial
3491 // default constructor
3492 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3493 return true;
3494
3495 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3496 if (FieldDtor->isDeleted())
3497 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003498 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003499 AR_accessible)
3500 return true;
3501
3502 // -- any non-variant non-static data member of const-qualified type (or
3503 // array thereof) with no brace-or-equal-initializer does not have a
3504 // user-provided default constructor
3505 if (FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003506 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00003507 !FieldRecord->hasUserProvidedDefaultConstructor())
3508 return true;
3509
3510 if (!Union && FieldRecord->isUnion() &&
3511 FieldRecord->isAnonymousStructOrUnion()) {
3512 // We're okay to reuse AllConst here since we only care about the
3513 // value otherwise if we're in a union.
3514 AllConst = true;
3515
3516 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3517 UE = FieldRecord->field_end();
3518 UI != UE; ++UI) {
3519 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3520 CXXRecordDecl *UnionFieldRecord =
3521 UnionFieldType->getAsCXXRecordDecl();
3522
3523 if (!UnionFieldType.isConstQualified())
3524 AllConst = false;
3525
3526 if (UnionFieldRecord &&
3527 !UnionFieldRecord->hasTrivialDefaultConstructor())
3528 return true;
3529 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003530
Alexis Huntea6f0322011-05-11 22:34:38 +00003531 if (AllConst)
3532 return true;
3533
3534 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003535 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003536 continue;
3537 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003538
Richard Smith938f40b2011-06-11 17:19:42 +00003539 // -- any non-static data member with no brace-or-equal-initializer has
3540 // class type M (or array thereof) and either M has no default
3541 // constructor or overload resolution as applied to M's default
3542 // constructor results in an ambiguity or in a function that is deleted
3543 // or inaccessible from the defaulted default constructor.
3544 if (!FI->hasInClassInitializer()) {
3545 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3546 if (!FieldDefault || FieldDefault->isDeleted())
3547 return true;
3548 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3549 PDiag()) != AR_accessible)
3550 return true;
3551 }
3552 } else if (!Union && FieldType.isConstQualified() &&
3553 !FI->hasInClassInitializer()) {
Alexis Hunta671bca2011-05-20 21:43:47 +00003554 // -- any non-variant non-static data member of const-qualified type (or
3555 // array thereof) with no brace-or-equal-initializer does not have a
3556 // user-provided default constructor
3557 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003558 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003559 }
3560
3561 if (Union && AllConst)
3562 return true;
3563
3564 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003565}
3566
Alexis Hunt913820d2011-05-13 06:10:58 +00003567bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003568 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003569 assert(!RD->isDependentType() && "do deletion after instantiation");
3570 if (!LangOpts.CPlusPlus0x)
3571 return false;
3572
Alexis Hunte77a28f2011-05-18 03:41:58 +00003573 SourceLocation Loc = CD->getLocation();
3574
Alexis Hunt913820d2011-05-13 06:10:58 +00003575 // Do access control from the constructor
3576 ContextRAII CtorContext(*this, CD);
3577
Alexis Hunt899bd442011-06-10 04:44:37 +00003578 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003579
Alexis Huntc9a55732011-05-14 05:23:28 +00003580 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3581 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00003582 unsigned ArgQuals =
3583 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3584 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00003585
3586 // We do this because we should never actually use an anonymous
3587 // union's constructor.
3588 if (Union && RD->isAnonymousStructOrUnion())
3589 return false;
3590
3591 // FIXME: We should put some diagnostic logic right into this function.
3592
3593 // C++0x [class.copy]/11
3594 // A defaulted [copy] constructor for class X is defined as delete if X has:
3595
3596 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3597 BE = RD->bases_end();
3598 BI != BE; ++BI) {
3599 // We'll handle this one later
3600 if (BI->isVirtual())
3601 continue;
3602
3603 QualType BaseType = BI->getType();
3604 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3605 assert(BaseDecl && "base isn't a CXXRecordDecl");
3606
3607 // -- any [direct base class] of a type with a destructor that is deleted or
3608 // inaccessible from the defaulted constructor
3609 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3610 if (BaseDtor->isDeleted())
3611 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003612 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003613 AR_accessible)
3614 return true;
3615
3616 // -- a [direct base class] B that cannot be [copied] because overload
3617 // resolution, as applied to B's [copy] constructor, results in an
3618 // ambiguity or a function that is deleted or inaccessible from the
3619 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003620 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003621 if (!BaseCtor || BaseCtor->isDeleted())
3622 return true;
3623 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3624 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003625 return true;
3626 }
3627
3628 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3629 BE = RD->vbases_end();
3630 BI != BE; ++BI) {
3631 QualType BaseType = BI->getType();
3632 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3633 assert(BaseDecl && "base isn't a CXXRecordDecl");
3634
Alexis Hunteef8ee02011-06-10 03:50:41 +00003635 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00003636 // inaccessible from the defaulted constructor
3637 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3638 if (BaseDtor->isDeleted())
3639 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003640 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003641 AR_accessible)
3642 return true;
3643
3644 // -- a [virtual base class] B that cannot be [copied] because overload
3645 // resolution, as applied to B's [copy] constructor, results in an
3646 // ambiguity or a function that is deleted or inaccessible from the
3647 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003648 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003649 if (!BaseCtor || BaseCtor->isDeleted())
3650 return true;
3651 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3652 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003653 return true;
3654 }
3655
3656 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3657 FE = RD->field_end();
3658 FI != FE; ++FI) {
3659 QualType FieldType = Context.getBaseElementType(FI->getType());
3660
3661 // -- for a copy constructor, a non-static data member of rvalue reference
3662 // type
3663 if (FieldType->isRValueReferenceType())
3664 return true;
3665
3666 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3667
3668 if (FieldRecord) {
3669 // This is an anonymous union
3670 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3671 // Anonymous unions inside unions do not variant members create
3672 if (!Union) {
3673 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3674 UE = FieldRecord->field_end();
3675 UI != UE; ++UI) {
3676 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3677 CXXRecordDecl *UnionFieldRecord =
3678 UnionFieldType->getAsCXXRecordDecl();
3679
3680 // -- a variant member with a non-trivial [copy] constructor and X
3681 // is a union-like class
3682 if (UnionFieldRecord &&
3683 !UnionFieldRecord->hasTrivialCopyConstructor())
3684 return true;
3685 }
3686 }
3687
3688 // Don't try to initalize an anonymous union
3689 continue;
3690 } else {
3691 // -- a variant member with a non-trivial [copy] constructor and X is a
3692 // union-like class
3693 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3694 return true;
3695
3696 // -- any [non-static data member] of a type with a destructor that is
3697 // deleted or inaccessible from the defaulted constructor
3698 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3699 if (FieldDtor->isDeleted())
3700 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003701 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003702 AR_accessible)
3703 return true;
3704 }
Alexis Hunt899bd442011-06-10 04:44:37 +00003705
3706 // -- a [non-static data member of class type (or array thereof)] B that
3707 // cannot be [copied] because overload resolution, as applied to B's
3708 // [copy] constructor, results in an ambiguity or a function that is
3709 // deleted or inaccessible from the defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003710 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3711 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003712 if (!FieldCtor || FieldCtor->isDeleted())
3713 return true;
3714 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3715 PDiag()) != AR_accessible)
3716 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00003717 }
Alexis Hunt913820d2011-05-13 06:10:58 +00003718 }
3719
3720 return false;
3721}
3722
Alexis Huntb2f27802011-05-14 05:23:24 +00003723bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3724 CXXRecordDecl *RD = MD->getParent();
3725 assert(!RD->isDependentType() && "do deletion after instantiation");
3726 if (!LangOpts.CPlusPlus0x)
3727 return false;
3728
Alexis Hunte77a28f2011-05-18 03:41:58 +00003729 SourceLocation Loc = MD->getLocation();
3730
Alexis Huntb2f27802011-05-14 05:23:24 +00003731 // Do access control from the constructor
3732 ContextRAII MethodContext(*this, MD);
3733
3734 bool Union = RD->isUnion();
3735
Alexis Hunt491ec602011-06-21 23:42:56 +00003736 unsigned ArgQuals =
3737 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3738 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00003739
3740 // We do this because we should never actually use an anonymous
3741 // union's constructor.
3742 if (Union && RD->isAnonymousStructOrUnion())
3743 return false;
3744
Alexis Huntb2f27802011-05-14 05:23:24 +00003745 // FIXME: We should put some diagnostic logic right into this function.
3746
3747 // C++0x [class.copy]/11
3748 // A defaulted [copy] assignment operator for class X is defined as deleted
3749 // if X has:
3750
3751 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3752 BE = RD->bases_end();
3753 BI != BE; ++BI) {
3754 // We'll handle this one later
3755 if (BI->isVirtual())
3756 continue;
3757
3758 QualType BaseType = BI->getType();
3759 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3760 assert(BaseDecl && "base isn't a CXXRecordDecl");
3761
3762 // -- a [direct base class] B that cannot be [copied] because overload
3763 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00003764 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00003765 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00003766 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3767 0);
3768 if (!CopyOper || CopyOper->isDeleted())
3769 return true;
3770 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00003771 return true;
3772 }
3773
3774 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3775 BE = RD->vbases_end();
3776 BI != BE; ++BI) {
3777 QualType BaseType = BI->getType();
3778 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3779 assert(BaseDecl && "base isn't a CXXRecordDecl");
3780
Alexis Huntb2f27802011-05-14 05:23:24 +00003781 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00003782 // resolution, as applied to B's [copy] assignment operator, results in
3783 // an ambiguity or a function that is deleted or inaccessible from the
3784 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00003785 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3786 0);
3787 if (!CopyOper || CopyOper->isDeleted())
3788 return true;
3789 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00003790 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00003791 }
3792
3793 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3794 FE = RD->field_end();
3795 FI != FE; ++FI) {
3796 QualType FieldType = Context.getBaseElementType(FI->getType());
3797
3798 // -- a non-static data member of reference type
3799 if (FieldType->isReferenceType())
3800 return true;
3801
3802 // -- a non-static data member of const non-class type (or array thereof)
3803 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3804 return true;
3805
3806 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3807
3808 if (FieldRecord) {
3809 // This is an anonymous union
3810 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3811 // Anonymous unions inside unions do not variant members create
3812 if (!Union) {
3813 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3814 UE = FieldRecord->field_end();
3815 UI != UE; ++UI) {
3816 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3817 CXXRecordDecl *UnionFieldRecord =
3818 UnionFieldType->getAsCXXRecordDecl();
3819
3820 // -- a variant member with a non-trivial [copy] assignment operator
3821 // and X is a union-like class
3822 if (UnionFieldRecord &&
3823 !UnionFieldRecord->hasTrivialCopyAssignment())
3824 return true;
3825 }
3826 }
3827
3828 // Don't try to initalize an anonymous union
3829 continue;
3830 // -- a variant member with a non-trivial [copy] assignment operator
3831 // and X is a union-like class
3832 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3833 return true;
3834 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003835
Alexis Hunt491ec602011-06-21 23:42:56 +00003836 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
3837 false, 0);
3838 if (!CopyOper || CopyOper->isDeleted())
3839 return false;
3840 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3841 return false;
Alexis Huntc9a55732011-05-14 05:23:28 +00003842 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003843 }
3844
3845 return false;
3846}
3847
Alexis Huntf91729462011-05-12 22:46:25 +00003848bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3849 CXXRecordDecl *RD = DD->getParent();
3850 assert(!RD->isDependentType() && "do deletion after instantiation");
3851 if (!LangOpts.CPlusPlus0x)
3852 return false;
3853
Alexis Hunte77a28f2011-05-18 03:41:58 +00003854 SourceLocation Loc = DD->getLocation();
3855
Alexis Huntf91729462011-05-12 22:46:25 +00003856 // Do access control from the destructor
3857 ContextRAII CtorContext(*this, DD);
3858
3859 bool Union = RD->isUnion();
3860
Alexis Hunt913820d2011-05-13 06:10:58 +00003861 // We do this because we should never actually use an anonymous
3862 // union's destructor.
3863 if (Union && RD->isAnonymousStructOrUnion())
3864 return false;
3865
Alexis Huntf91729462011-05-12 22:46:25 +00003866 // C++0x [class.dtor]p5
3867 // A defaulted destructor for a class X is defined as deleted if:
3868 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3869 BE = RD->bases_end();
3870 BI != BE; ++BI) {
3871 // We'll handle this one later
3872 if (BI->isVirtual())
3873 continue;
3874
3875 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3876 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3877 assert(BaseDtor && "base has no destructor");
3878
3879 // -- any direct or virtual base class has a deleted destructor or
3880 // a destructor that is inaccessible from the defaulted destructor
3881 if (BaseDtor->isDeleted())
3882 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003883 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003884 AR_accessible)
3885 return true;
3886 }
3887
3888 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3889 BE = RD->vbases_end();
3890 BI != BE; ++BI) {
3891 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3892 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3893 assert(BaseDtor && "base has no destructor");
3894
3895 // -- any direct or virtual base class has a deleted destructor or
3896 // a destructor that is inaccessible from the defaulted destructor
3897 if (BaseDtor->isDeleted())
3898 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003899 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003900 AR_accessible)
3901 return true;
3902 }
3903
3904 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3905 FE = RD->field_end();
3906 FI != FE; ++FI) {
3907 QualType FieldType = Context.getBaseElementType(FI->getType());
3908 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3909 if (FieldRecord) {
3910 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3911 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3912 UE = FieldRecord->field_end();
3913 UI != UE; ++UI) {
3914 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3915 CXXRecordDecl *UnionFieldRecord =
3916 UnionFieldType->getAsCXXRecordDecl();
3917
3918 // -- X is a union-like class that has a variant member with a non-
3919 // trivial destructor.
3920 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3921 return true;
3922 }
3923 // Technically we are supposed to do this next check unconditionally.
3924 // But that makes absolutely no sense.
3925 } else {
3926 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3927
3928 // -- any of the non-static data members has class type M (or array
3929 // thereof) and M has a deleted destructor or a destructor that is
3930 // inaccessible from the defaulted destructor
3931 if (FieldDtor->isDeleted())
3932 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003933 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003934 AR_accessible)
3935 return true;
3936
3937 // -- X is a union-like class that has a variant member with a non-
3938 // trivial destructor.
3939 if (Union && !FieldDtor->isTrivial())
3940 return true;
3941 }
3942 }
3943 }
3944
3945 if (DD->isVirtual()) {
3946 FunctionDecl *OperatorDelete = 0;
3947 DeclarationName Name =
3948 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00003949 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00003950 false))
3951 return true;
3952 }
3953
3954
3955 return false;
3956}
3957
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003958/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00003959namespace {
3960 struct FindHiddenVirtualMethodData {
3961 Sema *S;
3962 CXXMethodDecl *Method;
3963 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3964 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3965 };
3966}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003967
3968/// \brief Member lookup function that determines whether a given C++
3969/// method overloads virtual methods in a base class without overriding any,
3970/// to be used with CXXRecordDecl::lookupInBases().
3971static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3972 CXXBasePath &Path,
3973 void *UserData) {
3974 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3975
3976 FindHiddenVirtualMethodData &Data
3977 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3978
3979 DeclarationName Name = Data.Method->getDeclName();
3980 assert(Name.getNameKind() == DeclarationName::Identifier);
3981
3982 bool foundSameNameMethod = false;
3983 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3984 for (Path.Decls = BaseRecord->lookup(Name);
3985 Path.Decls.first != Path.Decls.second;
3986 ++Path.Decls.first) {
3987 NamedDecl *D = *Path.Decls.first;
3988 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003989 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003990 foundSameNameMethod = true;
3991 // Interested only in hidden virtual methods.
3992 if (!MD->isVirtual())
3993 continue;
3994 // If the method we are checking overrides a method from its base
3995 // don't warn about the other overloaded methods.
3996 if (!Data.S->IsOverload(Data.Method, MD, false))
3997 return true;
3998 // Collect the overload only if its hidden.
3999 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4000 overloadedMethods.push_back(MD);
4001 }
4002 }
4003
4004 if (foundSameNameMethod)
4005 Data.OverloadedMethods.append(overloadedMethods.begin(),
4006 overloadedMethods.end());
4007 return foundSameNameMethod;
4008}
4009
4010/// \brief See if a method overloads virtual methods in a base class without
4011/// overriding any.
4012void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4013 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4014 MD->getLocation()) == Diagnostic::Ignored)
4015 return;
4016 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4017 return;
4018
4019 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4020 /*bool RecordPaths=*/false,
4021 /*bool DetectVirtual=*/false);
4022 FindHiddenVirtualMethodData Data;
4023 Data.Method = MD;
4024 Data.S = this;
4025
4026 // Keep the base methods that were overriden or introduced in the subclass
4027 // by 'using' in a set. A base method not in this set is hidden.
4028 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4029 res.first != res.second; ++res.first) {
4030 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4031 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4032 E = MD->end_overridden_methods();
4033 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004034 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004035 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4036 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004037 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004038 }
4039
4040 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4041 !Data.OverloadedMethods.empty()) {
4042 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4043 << MD << (Data.OverloadedMethods.size() > 1);
4044
4045 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4046 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4047 Diag(overloadedMD->getLocation(),
4048 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4049 }
4050 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004051}
4052
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004053void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004054 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004055 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004056 SourceLocation RBrac,
4057 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004058 if (!TagDecl)
4059 return;
Mike Stump11289f42009-09-09 15:08:12 +00004060
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004061 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004062
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004063 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00004064 // strict aliasing violation!
4065 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004066 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004067
Douglas Gregor0be31a22010-07-02 17:43:08 +00004068 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004069 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004070}
4071
Douglas Gregor05379422008-11-03 17:51:48 +00004072/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4073/// special functions, such as the default constructor, copy
4074/// constructor, or destructor, to the given C++ class (C++
4075/// [special]p1). This routine can only be executed just before the
4076/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004077void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004078 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004079 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004080
Douglas Gregor54be3392010-07-01 17:57:27 +00004081 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004082 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004083
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004084 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4085 ++ASTContext::NumImplicitCopyAssignmentOperators;
4086
4087 // If we have a dynamic class, then the copy assignment operator may be
4088 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4089 // it shows up in the right place in the vtable and that we diagnose
4090 // problems with the implicit exception specification.
4091 if (ClassDecl->isDynamicClass())
4092 DeclareImplicitCopyAssignment(ClassDecl);
4093 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004094
Douglas Gregor7454c562010-07-02 20:37:36 +00004095 if (!ClassDecl->hasUserDeclaredDestructor()) {
4096 ++ASTContext::NumImplicitDestructors;
4097
4098 // If we have a dynamic class, then the destructor may be virtual, so we
4099 // have to declare the destructor immediately. This ensures that, e.g., it
4100 // shows up in the right place in the vtable and that we diagnose problems
4101 // with the implicit exception specification.
4102 if (ClassDecl->isDynamicClass())
4103 DeclareImplicitDestructor(ClassDecl);
4104 }
Douglas Gregor05379422008-11-03 17:51:48 +00004105}
4106
Francois Pichet1c229c02011-04-22 22:18:13 +00004107void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4108 if (!D)
4109 return;
4110
4111 int NumParamList = D->getNumTemplateParameterLists();
4112 for (int i = 0; i < NumParamList; i++) {
4113 TemplateParameterList* Params = D->getTemplateParameterList(i);
4114 for (TemplateParameterList::iterator Param = Params->begin(),
4115 ParamEnd = Params->end();
4116 Param != ParamEnd; ++Param) {
4117 NamedDecl *Named = cast<NamedDecl>(*Param);
4118 if (Named->getDeclName()) {
4119 S->AddDecl(Named);
4120 IdResolver.AddDecl(Named);
4121 }
4122 }
4123 }
4124}
4125
John McCall48871652010-08-21 09:40:31 +00004126void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004127 if (!D)
4128 return;
4129
4130 TemplateParameterList *Params = 0;
4131 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4132 Params = Template->getTemplateParameters();
4133 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4134 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4135 Params = PartialSpec->getTemplateParameters();
4136 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004137 return;
4138
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004139 for (TemplateParameterList::iterator Param = Params->begin(),
4140 ParamEnd = Params->end();
4141 Param != ParamEnd; ++Param) {
4142 NamedDecl *Named = cast<NamedDecl>(*Param);
4143 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004144 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004145 IdResolver.AddDecl(Named);
4146 }
4147 }
4148}
4149
John McCall48871652010-08-21 09:40:31 +00004150void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004151 if (!RecordD) return;
4152 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004153 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004154 PushDeclContext(S, Record);
4155}
4156
John McCall48871652010-08-21 09:40:31 +00004157void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004158 if (!RecordD) return;
4159 PopDeclContext();
4160}
4161
Douglas Gregor4d87df52008-12-16 21:30:33 +00004162/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4163/// parsing a top-level (non-nested) C++ class, and we are now
4164/// parsing those parts of the given Method declaration that could
4165/// not be parsed earlier (C++ [class.mem]p2), such as default
4166/// arguments. This action should enter the scope of the given
4167/// Method declaration as if we had just parsed the qualified method
4168/// name. However, it should not bring the parameters into scope;
4169/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004170void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004171}
4172
4173/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4174/// C++ method declaration. We're (re-)introducing the given
4175/// function parameter into scope for use in parsing later parts of
4176/// the method declaration. For example, we could see an
4177/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004178void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004179 if (!ParamD)
4180 return;
Mike Stump11289f42009-09-09 15:08:12 +00004181
John McCall48871652010-08-21 09:40:31 +00004182 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004183
4184 // If this parameter has an unparsed default argument, clear it out
4185 // to make way for the parsed default argument.
4186 if (Param->hasUnparsedDefaultArg())
4187 Param->setDefaultArg(0);
4188
John McCall48871652010-08-21 09:40:31 +00004189 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004190 if (Param->getDeclName())
4191 IdResolver.AddDecl(Param);
4192}
4193
4194/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4195/// processing the delayed method declaration for Method. The method
4196/// declaration is now considered finished. There may be a separate
4197/// ActOnStartOfFunctionDef action later (not necessarily
4198/// immediately!) for this method, if it was also defined inside the
4199/// class body.
John McCall48871652010-08-21 09:40:31 +00004200void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004201 if (!MethodD)
4202 return;
Mike Stump11289f42009-09-09 15:08:12 +00004203
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004204 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004205
John McCall48871652010-08-21 09:40:31 +00004206 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004207
4208 // Now that we have our default arguments, check the constructor
4209 // again. It could produce additional diagnostics or affect whether
4210 // the class has implicitly-declared destructors, among other
4211 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004212 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4213 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004214
4215 // Check the default arguments, which we may have added.
4216 if (!Method->isInvalidDecl())
4217 CheckCXXDefaultArguments(Method);
4218}
4219
Douglas Gregor831c93f2008-11-05 20:51:48 +00004220/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004221/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004222/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004223/// emit diagnostics and set the invalid bit to true. In any case, the type
4224/// will be updated to reflect a well-formed type for the constructor and
4225/// returned.
4226QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004227 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004228 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004229
4230 // C++ [class.ctor]p3:
4231 // A constructor shall not be virtual (10.3) or static (9.4). A
4232 // constructor can be invoked for a const, volatile or const
4233 // volatile object. A constructor shall not be declared const,
4234 // volatile, or const volatile (9.3.2).
4235 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004236 if (!D.isInvalidType())
4237 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4238 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4239 << SourceRange(D.getIdentifierLoc());
4240 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004241 }
John McCall8e7d6562010-08-26 03:08:43 +00004242 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004243 if (!D.isInvalidType())
4244 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4245 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4246 << SourceRange(D.getIdentifierLoc());
4247 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004248 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004249 }
Mike Stump11289f42009-09-09 15:08:12 +00004250
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004251 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004252 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004253 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004254 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4255 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004256 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004257 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4258 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004259 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004260 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4261 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004262 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004263 }
Mike Stump11289f42009-09-09 15:08:12 +00004264
Douglas Gregordb9d6642011-01-26 05:01:58 +00004265 // C++0x [class.ctor]p4:
4266 // A constructor shall not be declared with a ref-qualifier.
4267 if (FTI.hasRefQualifier()) {
4268 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4269 << FTI.RefQualifierIsLValueRef
4270 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4271 D.setInvalidType();
4272 }
4273
Douglas Gregor831c93f2008-11-05 20:51:48 +00004274 // Rebuild the function type "R" without any type qualifiers (in
4275 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004276 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004277 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004278 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4279 return R;
4280
4281 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4282 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004283 EPI.RefQualifier = RQ_None;
4284
Chris Lattner38378bf2009-04-25 08:28:21 +00004285 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004286 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004287}
4288
Douglas Gregor4d87df52008-12-16 21:30:33 +00004289/// CheckConstructor - Checks a fully-formed constructor for
4290/// well-formedness, issuing any diagnostics required. Returns true if
4291/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004292void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004293 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004294 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4295 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004296 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004297
4298 // C++ [class.copy]p3:
4299 // A declaration of a constructor for a class X is ill-formed if
4300 // its first parameter is of type (optionally cv-qualified) X and
4301 // either there are no other parameters or else all other
4302 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004303 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004304 ((Constructor->getNumParams() == 1) ||
4305 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004306 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4307 Constructor->getTemplateSpecializationKind()
4308 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004309 QualType ParamType = Constructor->getParamDecl(0)->getType();
4310 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4311 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004312 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004313 const char *ConstRef
4314 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4315 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004316 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004317 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004318
4319 // FIXME: Rather that making the constructor invalid, we should endeavor
4320 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004321 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004322 }
4323 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004324}
4325
John McCalldeb646e2010-08-04 01:04:25 +00004326/// CheckDestructor - Checks a fully-formed destructor definition for
4327/// well-formedness, issuing any diagnostics required. Returns true
4328/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004329bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004330 CXXRecordDecl *RD = Destructor->getParent();
4331
4332 if (Destructor->isVirtual()) {
4333 SourceLocation Loc;
4334
4335 if (!Destructor->isImplicit())
4336 Loc = Destructor->getLocation();
4337 else
4338 Loc = RD->getLocation();
4339
4340 // If we have a virtual destructor, look up the deallocation function
4341 FunctionDecl *OperatorDelete = 0;
4342 DeclarationName Name =
4343 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004344 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004345 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004346
4347 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004348
4349 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004350 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004351
4352 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004353}
4354
Mike Stump11289f42009-09-09 15:08:12 +00004355static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004356FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4357 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4358 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004359 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004360}
4361
Douglas Gregor831c93f2008-11-05 20:51:48 +00004362/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4363/// the well-formednes of the destructor declarator @p D with type @p
4364/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004365/// emit diagnostics and set the declarator to invalid. Even if this happens,
4366/// will be updated to reflect a well-formed type for the destructor and
4367/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004368QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004369 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004370 // C++ [class.dtor]p1:
4371 // [...] A typedef-name that names a class is a class-name
4372 // (7.1.3); however, a typedef-name that names a class shall not
4373 // be used as the identifier in the declarator for a destructor
4374 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004375 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004376 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004377 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004378 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004379 else if (const TemplateSpecializationType *TST =
4380 DeclaratorType->getAs<TemplateSpecializationType>())
4381 if (TST->isTypeAlias())
4382 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4383 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004384
4385 // C++ [class.dtor]p2:
4386 // A destructor is used to destroy objects of its class type. A
4387 // destructor takes no parameters, and no return type can be
4388 // specified for it (not even void). The address of a destructor
4389 // shall not be taken. A destructor shall not be static. A
4390 // destructor can be invoked for a const, volatile or const
4391 // volatile object. A destructor shall not be declared const,
4392 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004393 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004394 if (!D.isInvalidType())
4395 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4396 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004397 << SourceRange(D.getIdentifierLoc())
4398 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4399
John McCall8e7d6562010-08-26 03:08:43 +00004400 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004401 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004402 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004403 // Destructors don't have return types, but the parser will
4404 // happily parse something like:
4405 //
4406 // class X {
4407 // float ~X();
4408 // };
4409 //
4410 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004411 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4412 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4413 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004414 }
Mike Stump11289f42009-09-09 15:08:12 +00004415
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004416 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004417 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004418 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004419 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4420 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004421 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004422 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4423 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004424 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004425 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4426 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00004427 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004428 }
4429
Douglas Gregordb9d6642011-01-26 05:01:58 +00004430 // C++0x [class.dtor]p2:
4431 // A destructor shall not be declared with a ref-qualifier.
4432 if (FTI.hasRefQualifier()) {
4433 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4434 << FTI.RefQualifierIsLValueRef
4435 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4436 D.setInvalidType();
4437 }
4438
Douglas Gregor831c93f2008-11-05 20:51:48 +00004439 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00004440 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004441 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4442
4443 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00004444 FTI.freeArgs();
4445 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004446 }
4447
Mike Stump11289f42009-09-09 15:08:12 +00004448 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00004449 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004450 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00004451 D.setInvalidType();
4452 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00004453
4454 // Rebuild the function type "R" without any type qualifiers or
4455 // parameters (in case any of the errors above fired) and with
4456 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00004457 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00004458 if (!D.isInvalidType())
4459 return R;
4460
Douglas Gregor95755162010-07-01 05:10:53 +00004461 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004462 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4463 EPI.Variadic = false;
4464 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004465 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004466 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004467}
4468
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004469/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4470/// well-formednes of the conversion function declarator @p D with
4471/// type @p R. If there are any errors in the declarator, this routine
4472/// will emit diagnostics and return true. Otherwise, it will return
4473/// false. Either way, the type @p R will be updated to reflect a
4474/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004475void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00004476 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004477 // C++ [class.conv.fct]p1:
4478 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00004479 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00004480 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00004481 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004482 if (!D.isInvalidType())
4483 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4484 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4485 << SourceRange(D.getIdentifierLoc());
4486 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004487 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004488 }
John McCall212fa2e2010-04-13 00:04:31 +00004489
4490 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4491
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004492 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004493 // Conversion functions don't have return types, but the parser will
4494 // happily parse something like:
4495 //
4496 // class X {
4497 // float operator bool();
4498 // };
4499 //
4500 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00004501 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4502 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4503 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00004504 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004505 }
4506
John McCall212fa2e2010-04-13 00:04:31 +00004507 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4508
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004509 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00004510 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004511 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4512
4513 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004514 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004515 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00004516 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004517 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004518 D.setInvalidType();
4519 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004520
John McCall212fa2e2010-04-13 00:04:31 +00004521 // Diagnose "&operator bool()" and other such nonsense. This
4522 // is actually a gcc extension which we don't support.
4523 if (Proto->getResultType() != ConvType) {
4524 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4525 << Proto->getResultType();
4526 D.setInvalidType();
4527 ConvType = Proto->getResultType();
4528 }
4529
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004530 // C++ [class.conv.fct]p4:
4531 // The conversion-type-id shall not represent a function type nor
4532 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004533 if (ConvType->isArrayType()) {
4534 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4535 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004536 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004537 } else if (ConvType->isFunctionType()) {
4538 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4539 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004540 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004541 }
4542
4543 // Rebuild the function type "R" without any parameters (in case any
4544 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00004545 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00004546 if (D.isInvalidType())
4547 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004548
Douglas Gregor5fb53972009-01-14 15:45:31 +00004549 // C++0x explicit conversion operators.
4550 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00004551 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00004552 diag::warn_explicit_conversion_functions)
4553 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004554}
4555
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004556/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4557/// the declaration of the given C++ conversion function. This routine
4558/// is responsible for recording the conversion function in the C++
4559/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00004560Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004561 assert(Conversion && "Expected to receive a conversion function declaration");
4562
Douglas Gregor4287b372008-12-12 08:25:50 +00004563 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004564
4565 // Make sure we aren't redeclaring the conversion function.
4566 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004567
4568 // C++ [class.conv.fct]p1:
4569 // [...] A conversion function is never used to convert a
4570 // (possibly cv-qualified) object to the (possibly cv-qualified)
4571 // same object type (or a reference to it), to a (possibly
4572 // cv-qualified) base class of that type (or a reference to it),
4573 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00004574 // FIXME: Suppress this warning if the conversion function ends up being a
4575 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00004576 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004577 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004578 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004579 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004580 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4581 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00004582 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004583 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004584 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4585 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004586 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004587 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004588 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004589 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004590 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004591 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004592 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004593 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004594 }
4595
Douglas Gregor457104e2010-09-29 04:25:11 +00004596 if (FunctionTemplateDecl *ConversionTemplate
4597 = Conversion->getDescribedFunctionTemplate())
4598 return ConversionTemplate;
4599
John McCall48871652010-08-21 09:40:31 +00004600 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004601}
4602
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004603//===----------------------------------------------------------------------===//
4604// Namespace Handling
4605//===----------------------------------------------------------------------===//
4606
John McCallb1be5232010-08-26 09:15:37 +00004607
4608
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004609/// ActOnStartNamespaceDef - This is called at the start of a namespace
4610/// definition.
John McCall48871652010-08-21 09:40:31 +00004611Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00004612 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004613 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00004614 SourceLocation IdentLoc,
4615 IdentifierInfo *II,
4616 SourceLocation LBrace,
4617 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004618 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4619 // For anonymous namespace, take the location of the left brace.
4620 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00004621 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004622 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004623 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004624
4625 Scope *DeclRegionScope = NamespcScope->getParent();
4626
Anders Carlssona7bcade2010-02-07 01:09:23 +00004627 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4628
John McCall2faf32c2010-12-10 02:59:44 +00004629 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4630 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00004631
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004632 if (II) {
4633 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00004634 // The identifier in an original-namespace-definition shall not
4635 // have been previously defined in the declarative region in
4636 // which the original-namespace-definition appears. The
4637 // identifier in an original-namespace-definition is the name of
4638 // the namespace. Subsequently in that declarative region, it is
4639 // treated as an original-namespace-name.
4640 //
4641 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00004642 // look through using directives, just look for any ordinary names.
4643
4644 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4645 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4646 Decl::IDNS_Namespace;
4647 NamedDecl *PrevDecl = 0;
4648 for (DeclContext::lookup_result R
4649 = CurContext->getRedeclContext()->lookup(II);
4650 R.first != R.second; ++R.first) {
4651 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4652 PrevDecl = *R.first;
4653 break;
4654 }
4655 }
4656
Douglas Gregor91f84212008-12-11 16:49:14 +00004657 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4658 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004659 if (Namespc->isInline() != OrigNS->isInline()) {
4660 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00004661 if (OrigNS->isInline()) {
4662 // The user probably just forgot the 'inline', so suggest that it
4663 // be added back.
4664 Diag(Namespc->getLocation(),
4665 diag::warn_inline_namespace_reopened_noninline)
4666 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4667 } else {
4668 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4669 << Namespc->isInline();
4670 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004671 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00004672
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004673 // Recover by ignoring the new namespace's inline status.
4674 Namespc->setInline(OrigNS->isInline());
4675 }
4676
Douglas Gregor91f84212008-12-11 16:49:14 +00004677 // Attach this namespace decl to the chain of extended namespace
4678 // definitions.
4679 OrigNS->setNextNamespace(Namespc);
4680 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004681
Mike Stump11289f42009-09-09 15:08:12 +00004682 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00004683 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00004684 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00004685 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004686 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004687 } else if (PrevDecl) {
4688 // This is an invalid name redefinition.
4689 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4690 << Namespc->getDeclName();
4691 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4692 Namespc->setInvalidDecl();
4693 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00004694 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004695 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004696 // This is the first "real" definition of the namespace "std", so update
4697 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004698 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004699 // We had already defined a dummy namespace "std". Link this new
4700 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004701 StdNS->setNextNamespace(Namespc);
4702 StdNS->setLocation(IdentLoc);
4703 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00004704 }
4705
4706 // Make our StdNamespace cache point at the first real definition of the
4707 // "std" namespace.
4708 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00004709 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004710
4711 PushOnScopeChains(Namespc, DeclRegionScope);
4712 } else {
John McCall4fa53422009-10-01 00:25:31 +00004713 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00004714 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00004715
4716 // Link the anonymous namespace into its parent.
4717 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00004718 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00004719 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4720 PrevDecl = TU->getAnonymousNamespace();
4721 TU->setAnonymousNamespace(Namespc);
4722 } else {
4723 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4724 PrevDecl = ND->getAnonymousNamespace();
4725 ND->setAnonymousNamespace(Namespc);
4726 }
4727
4728 // Link the anonymous namespace with its previous declaration.
4729 if (PrevDecl) {
4730 assert(PrevDecl->isAnonymousNamespace());
4731 assert(!PrevDecl->getNextNamespace());
4732 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4733 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004734
4735 if (Namespc->isInline() != PrevDecl->isInline()) {
4736 // inline-ness must match
4737 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4738 << Namespc->isInline();
4739 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4740 Namespc->setInvalidDecl();
4741 // Recover by ignoring the new namespace's inline status.
4742 Namespc->setInline(PrevDecl->isInline());
4743 }
John McCall0db42252009-12-16 02:06:49 +00004744 }
John McCall4fa53422009-10-01 00:25:31 +00004745
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00004746 CurContext->addDecl(Namespc);
4747
John McCall4fa53422009-10-01 00:25:31 +00004748 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4749 // behaves as if it were replaced by
4750 // namespace unique { /* empty body */ }
4751 // using namespace unique;
4752 // namespace unique { namespace-body }
4753 // where all occurrences of 'unique' in a translation unit are
4754 // replaced by the same identifier and this identifier differs
4755 // from all other identifiers in the entire program.
4756
4757 // We just create the namespace with an empty name and then add an
4758 // implicit using declaration, just like the standard suggests.
4759 //
4760 // CodeGen enforces the "universally unique" aspect by giving all
4761 // declarations semantically contained within an anonymous
4762 // namespace internal linkage.
4763
John McCall0db42252009-12-16 02:06:49 +00004764 if (!PrevDecl) {
4765 UsingDirectiveDecl* UD
4766 = UsingDirectiveDecl::Create(Context, CurContext,
4767 /* 'using' */ LBrace,
4768 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00004769 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00004770 /* identifier */ SourceLocation(),
4771 Namespc,
4772 /* Ancestor */ CurContext);
4773 UD->setImplicit();
4774 CurContext->addDecl(UD);
4775 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004776 }
4777
4778 // Although we could have an invalid decl (i.e. the namespace name is a
4779 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00004780 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4781 // for the namespace has the declarations that showed up in that particular
4782 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00004783 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00004784 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004785}
4786
Sebastian Redla6602e92009-11-23 15:34:23 +00004787/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4788/// is a namespace alias, returns the namespace it points to.
4789static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4790 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4791 return AD->getNamespace();
4792 return dyn_cast_or_null<NamespaceDecl>(D);
4793}
4794
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004795/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4796/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00004797void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004798 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4799 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004800 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004801 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00004802 if (Namespc->hasAttr<VisibilityAttr>())
4803 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004804}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004805
John McCall28a0cf72010-08-25 07:42:41 +00004806CXXRecordDecl *Sema::getStdBadAlloc() const {
4807 return cast_or_null<CXXRecordDecl>(
4808 StdBadAlloc.get(Context.getExternalSource()));
4809}
4810
4811NamespaceDecl *Sema::getStdNamespace() const {
4812 return cast_or_null<NamespaceDecl>(
4813 StdNamespace.get(Context.getExternalSource()));
4814}
4815
Douglas Gregorcdf87022010-06-29 17:53:46 +00004816/// \brief Retrieve the special "std" namespace, which may require us to
4817/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004818NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00004819 if (!StdNamespace) {
4820 // The "std" namespace has not yet been defined, so build one implicitly.
4821 StdNamespace = NamespaceDecl::Create(Context,
4822 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004823 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00004824 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004825 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004826 }
4827
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004828 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004829}
4830
Douglas Gregora172e082011-03-26 22:25:30 +00004831/// \brief Determine whether a using statement is in a context where it will be
4832/// apply in all contexts.
4833static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4834 switch (CurContext->getDeclKind()) {
4835 case Decl::TranslationUnit:
4836 return true;
4837 case Decl::LinkageSpec:
4838 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4839 default:
4840 return false;
4841 }
4842}
4843
John McCall48871652010-08-21 09:40:31 +00004844Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00004845 SourceLocation UsingLoc,
4846 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004847 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004848 SourceLocation IdentLoc,
4849 IdentifierInfo *NamespcName,
4850 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00004851 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4852 assert(NamespcName && "Invalid NamespcName.");
4853 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00004854
4855 // This can only happen along a recovery path.
4856 while (S->getFlags() & Scope::TemplateParamScope)
4857 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00004858 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00004859
Douglas Gregor889ceb72009-02-03 19:21:40 +00004860 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00004861 NestedNameSpecifier *Qualifier = 0;
4862 if (SS.isSet())
4863 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4864
Douglas Gregor34074322009-01-14 22:20:51 +00004865 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004866 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4867 LookupParsedName(R, S, &SS);
4868 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004869 return 0;
John McCall27b18f82009-11-17 02:14:36 +00004870
Douglas Gregorcdf87022010-06-29 17:53:46 +00004871 if (R.empty()) {
4872 // Allow "using namespace std;" or "using namespace ::std;" even if
4873 // "std" hasn't been defined yet, for GCC compatibility.
4874 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4875 NamespcName->isStr("std")) {
4876 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004877 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00004878 R.resolveKind();
4879 }
4880 // Otherwise, attempt typo correction.
4881 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4882 CTC_NoKeywords, 0)) {
4883 if (R.getAsSingle<NamespaceDecl>() ||
4884 R.getAsSingle<NamespaceAliasDecl>()) {
4885 if (DeclContext *DC = computeDeclContext(SS, false))
4886 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4887 << NamespcName << DC << Corrected << SS.getRange()
4888 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4889 else
4890 Diag(IdentLoc, diag::err_using_directive_suggest)
4891 << NamespcName << Corrected
4892 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4893 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4894 << Corrected;
4895
4896 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004897 } else {
4898 R.clear();
4899 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004900 }
4901 }
4902 }
4903
John McCall9f3059a2009-10-09 21:13:30 +00004904 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00004905 NamedDecl *Named = R.getFoundDecl();
4906 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4907 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00004908 // C++ [namespace.udir]p1:
4909 // A using-directive specifies that the names in the nominated
4910 // namespace can be used in the scope in which the
4911 // using-directive appears after the using-directive. During
4912 // unqualified name lookup (3.4.1), the names appear as if they
4913 // were declared in the nearest enclosing namespace which
4914 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00004915 // namespace. [Note: in this context, "contains" means "contains
4916 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00004917
4918 // Find enclosing context containing both using-directive and
4919 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00004920 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004921 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4922 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4923 CommonAncestor = CommonAncestor->getParent();
4924
Sebastian Redla6602e92009-11-23 15:34:23 +00004925 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00004926 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00004927 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004928
Douglas Gregora172e082011-03-26 22:25:30 +00004929 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00004930 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004931 Diag(IdentLoc, diag::warn_using_directive_in_header);
4932 }
4933
Douglas Gregor889ceb72009-02-03 19:21:40 +00004934 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004935 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00004936 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00004937 }
4938
Douglas Gregor889ceb72009-02-03 19:21:40 +00004939 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00004940 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00004941}
4942
4943void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4944 // If scope has associated entity, then using directive is at namespace
4945 // or translation unit scope. We add UsingDirectiveDecls, into
4946 // it's lookup structure.
4947 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004948 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004949 else
4950 // Otherwise it is block-sope. using-directives will affect lookup
4951 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00004952 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004953}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004954
Douglas Gregorfec52632009-06-20 00:51:54 +00004955
John McCall48871652010-08-21 09:40:31 +00004956Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00004957 AccessSpecifier AS,
4958 bool HasUsingKeyword,
4959 SourceLocation UsingLoc,
4960 CXXScopeSpec &SS,
4961 UnqualifiedId &Name,
4962 AttributeList *AttrList,
4963 bool IsTypeName,
4964 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004965 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004966
Douglas Gregor220f4272009-11-04 16:30:06 +00004967 switch (Name.getKind()) {
4968 case UnqualifiedId::IK_Identifier:
4969 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004970 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004971 case UnqualifiedId::IK_ConversionFunctionId:
4972 break;
4973
4974 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004975 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004976 // C++0x inherited constructors.
4977 if (getLangOptions().CPlusPlus0x) break;
4978
Douglas Gregor220f4272009-11-04 16:30:06 +00004979 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4980 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004981 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004982
4983 case UnqualifiedId::IK_DestructorName:
4984 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4985 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004986 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004987
4988 case UnqualifiedId::IK_TemplateId:
4989 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4990 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00004991 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004992 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004993
4994 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4995 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00004996 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00004997 return 0;
John McCall3969e302009-12-08 07:46:18 +00004998
John McCalla0097262009-12-11 02:10:03 +00004999 // Warn about using declarations.
5000 // TODO: store that the declaration was written without 'using' and
5001 // talk about access decls instead of using decls in the
5002 // diagnostics.
5003 if (!HasUsingKeyword) {
5004 UsingLoc = Name.getSourceRange().getBegin();
5005
5006 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005007 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005008 }
5009
Douglas Gregorc4356532010-12-16 00:46:58 +00005010 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5011 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5012 return 0;
5013
John McCall3f746822009-11-17 05:59:44 +00005014 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005015 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005016 /* IsInstantiation */ false,
5017 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005018 if (UD)
5019 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005020
John McCall48871652010-08-21 09:40:31 +00005021 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005022}
5023
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005024/// \brief Determine whether a using declaration considers the given
5025/// declarations as "equivalent", e.g., if they are redeclarations of
5026/// the same entity or are both typedefs of the same type.
5027static bool
5028IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5029 bool &SuppressRedeclaration) {
5030 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5031 SuppressRedeclaration = false;
5032 return true;
5033 }
5034
Richard Smithdda56e42011-04-15 14:24:37 +00005035 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5036 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005037 SuppressRedeclaration = true;
5038 return Context.hasSameType(TD1->getUnderlyingType(),
5039 TD2->getUnderlyingType());
5040 }
5041
5042 return false;
5043}
5044
5045
John McCall84d87672009-12-10 09:41:52 +00005046/// Determines whether to create a using shadow decl for a particular
5047/// decl, given the set of decls existing prior to this using lookup.
5048bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5049 const LookupResult &Previous) {
5050 // Diagnose finding a decl which is not from a base class of the
5051 // current class. We do this now because there are cases where this
5052 // function will silently decide not to build a shadow decl, which
5053 // will pre-empt further diagnostics.
5054 //
5055 // We don't need to do this in C++0x because we do the check once on
5056 // the qualifier.
5057 //
5058 // FIXME: diagnose the following if we care enough:
5059 // struct A { int foo; };
5060 // struct B : A { using A::foo; };
5061 // template <class T> struct C : A {};
5062 // template <class T> struct D : C<T> { using B::foo; } // <---
5063 // This is invalid (during instantiation) in C++03 because B::foo
5064 // resolves to the using decl in B, which is not a base class of D<T>.
5065 // We can't diagnose it immediately because C<T> is an unknown
5066 // specialization. The UsingShadowDecl in D<T> then points directly
5067 // to A::foo, which will look well-formed when we instantiate.
5068 // The right solution is to not collapse the shadow-decl chain.
5069 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5070 DeclContext *OrigDC = Orig->getDeclContext();
5071
5072 // Handle enums and anonymous structs.
5073 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5074 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5075 while (OrigRec->isAnonymousStructOrUnion())
5076 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5077
5078 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5079 if (OrigDC == CurContext) {
5080 Diag(Using->getLocation(),
5081 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005082 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005083 Diag(Orig->getLocation(), diag::note_using_decl_target);
5084 return true;
5085 }
5086
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005087 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005088 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005089 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005090 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005091 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005092 Diag(Orig->getLocation(), diag::note_using_decl_target);
5093 return true;
5094 }
5095 }
5096
5097 if (Previous.empty()) return false;
5098
5099 NamedDecl *Target = Orig;
5100 if (isa<UsingShadowDecl>(Target))
5101 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5102
John McCalla17e83e2009-12-11 02:33:26 +00005103 // If the target happens to be one of the previous declarations, we
5104 // don't have a conflict.
5105 //
5106 // FIXME: but we might be increasing its access, in which case we
5107 // should redeclare it.
5108 NamedDecl *NonTag = 0, *Tag = 0;
5109 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5110 I != E; ++I) {
5111 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005112 bool Result;
5113 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5114 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005115
5116 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5117 }
5118
John McCall84d87672009-12-10 09:41:52 +00005119 if (Target->isFunctionOrFunctionTemplate()) {
5120 FunctionDecl *FD;
5121 if (isa<FunctionTemplateDecl>(Target))
5122 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5123 else
5124 FD = cast<FunctionDecl>(Target);
5125
5126 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005127 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005128 case Ovl_Overload:
5129 return false;
5130
5131 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005132 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005133 break;
5134
5135 // We found a decl with the exact signature.
5136 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005137 // If we're in a record, we want to hide the target, so we
5138 // return true (without a diagnostic) to tell the caller not to
5139 // build a shadow decl.
5140 if (CurContext->isRecord())
5141 return true;
5142
5143 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005144 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005145 break;
5146 }
5147
5148 Diag(Target->getLocation(), diag::note_using_decl_target);
5149 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5150 return true;
5151 }
5152
5153 // Target is not a function.
5154
John McCall84d87672009-12-10 09:41:52 +00005155 if (isa<TagDecl>(Target)) {
5156 // No conflict between a tag and a non-tag.
5157 if (!Tag) return false;
5158
John McCalle29c5cd2009-12-10 19:51:03 +00005159 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005160 Diag(Target->getLocation(), diag::note_using_decl_target);
5161 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5162 return true;
5163 }
5164
5165 // No conflict between a tag and a non-tag.
5166 if (!NonTag) return false;
5167
John McCalle29c5cd2009-12-10 19:51:03 +00005168 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005169 Diag(Target->getLocation(), diag::note_using_decl_target);
5170 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5171 return true;
5172}
5173
John McCall3f746822009-11-17 05:59:44 +00005174/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005175UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005176 UsingDecl *UD,
5177 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005178
5179 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005180 NamedDecl *Target = Orig;
5181 if (isa<UsingShadowDecl>(Target)) {
5182 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5183 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005184 }
5185
5186 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005187 = UsingShadowDecl::Create(Context, CurContext,
5188 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005189 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005190
5191 Shadow->setAccess(UD->getAccess());
5192 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5193 Shadow->setInvalidDecl();
5194
John McCall3f746822009-11-17 05:59:44 +00005195 if (S)
John McCall3969e302009-12-08 07:46:18 +00005196 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005197 else
John McCall3969e302009-12-08 07:46:18 +00005198 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005199
John McCall3969e302009-12-08 07:46:18 +00005200
John McCall84d87672009-12-10 09:41:52 +00005201 return Shadow;
5202}
John McCall3969e302009-12-08 07:46:18 +00005203
John McCall84d87672009-12-10 09:41:52 +00005204/// Hides a using shadow declaration. This is required by the current
5205/// using-decl implementation when a resolvable using declaration in a
5206/// class is followed by a declaration which would hide or override
5207/// one or more of the using decl's targets; for example:
5208///
5209/// struct Base { void foo(int); };
5210/// struct Derived : Base {
5211/// using Base::foo;
5212/// void foo(int);
5213/// };
5214///
5215/// The governing language is C++03 [namespace.udecl]p12:
5216///
5217/// When a using-declaration brings names from a base class into a
5218/// derived class scope, member functions in the derived class
5219/// override and/or hide member functions with the same name and
5220/// parameter types in a base class (rather than conflicting).
5221///
5222/// There are two ways to implement this:
5223/// (1) optimistically create shadow decls when they're not hidden
5224/// by existing declarations, or
5225/// (2) don't create any shadow decls (or at least don't make them
5226/// visible) until we've fully parsed/instantiated the class.
5227/// The problem with (1) is that we might have to retroactively remove
5228/// a shadow decl, which requires several O(n) operations because the
5229/// decl structures are (very reasonably) not designed for removal.
5230/// (2) avoids this but is very fiddly and phase-dependent.
5231void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005232 if (Shadow->getDeclName().getNameKind() ==
5233 DeclarationName::CXXConversionFunctionName)
5234 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5235
John McCall84d87672009-12-10 09:41:52 +00005236 // Remove it from the DeclContext...
5237 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005238
John McCall84d87672009-12-10 09:41:52 +00005239 // ...and the scope, if applicable...
5240 if (S) {
John McCall48871652010-08-21 09:40:31 +00005241 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005242 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005243 }
5244
John McCall84d87672009-12-10 09:41:52 +00005245 // ...and the using decl.
5246 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5247
5248 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005249 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005250}
5251
John McCalle61f2ba2009-11-18 02:36:19 +00005252/// Builds a using declaration.
5253///
5254/// \param IsInstantiation - Whether this call arises from an
5255/// instantiation of an unresolved using declaration. We treat
5256/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005257NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5258 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005259 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005260 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005261 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005262 bool IsInstantiation,
5263 bool IsTypeName,
5264 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005265 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005266 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005267 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005268
Anders Carlssonf038fc22009-08-28 05:49:21 +00005269 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005270
Anders Carlsson59140b32009-08-28 03:16:11 +00005271 if (SS.isEmpty()) {
5272 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005273 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005274 }
Mike Stump11289f42009-09-09 15:08:12 +00005275
John McCall84d87672009-12-10 09:41:52 +00005276 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005277 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005278 ForRedeclaration);
5279 Previous.setHideTags(false);
5280 if (S) {
5281 LookupName(Previous, S);
5282
5283 // It is really dumb that we have to do this.
5284 LookupResult::Filter F = Previous.makeFilter();
5285 while (F.hasNext()) {
5286 NamedDecl *D = F.next();
5287 if (!isDeclInScope(D, CurContext, S))
5288 F.erase();
5289 }
5290 F.done();
5291 } else {
5292 assert(IsInstantiation && "no scope in non-instantiation");
5293 assert(CurContext->isRecord() && "scope not record in instantiation");
5294 LookupQualifiedName(Previous, CurContext);
5295 }
5296
John McCall84d87672009-12-10 09:41:52 +00005297 // Check for invalid redeclarations.
5298 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5299 return 0;
5300
5301 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005302 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5303 return 0;
5304
John McCall84c16cf2009-11-12 03:15:40 +00005305 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005306 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005307 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005308 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005309 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005310 // FIXME: not all declaration name kinds are legal here
5311 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5312 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005313 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005314 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005315 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005316 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5317 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005318 }
John McCallb96ec562009-12-04 22:46:56 +00005319 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005320 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5321 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005322 }
John McCallb96ec562009-12-04 22:46:56 +00005323 D->setAccess(AS);
5324 CurContext->addDecl(D);
5325
5326 if (!LookupContext) return D;
5327 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005328
John McCall0b66eb32010-05-01 00:40:08 +00005329 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005330 UD->setInvalidDecl();
5331 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005332 }
5333
Sebastian Redl08905022011-02-05 19:23:19 +00005334 // Constructor inheriting using decls get special treatment.
5335 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005336 if (CheckInheritedConstructorUsingDecl(UD))
5337 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005338 return UD;
5339 }
5340
5341 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005342
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005343 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetefb1af92011-05-23 03:43:44 +00005344 R.setUsingDeclaration(true);
John McCalle61f2ba2009-11-18 02:36:19 +00005345
John McCall3969e302009-12-08 07:46:18 +00005346 // Unlike most lookups, we don't always want to hide tag
5347 // declarations: tag names are visible through the using declaration
5348 // even if hidden by ordinary names, *except* in a dependent context
5349 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005350 if (!IsInstantiation)
5351 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005352
John McCall27b18f82009-11-17 02:14:36 +00005353 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005354
John McCall9f3059a2009-10-09 21:13:30 +00005355 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005356 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005357 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005358 UD->setInvalidDecl();
5359 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005360 }
5361
John McCallb96ec562009-12-04 22:46:56 +00005362 if (R.isAmbiguous()) {
5363 UD->setInvalidDecl();
5364 return UD;
5365 }
Mike Stump11289f42009-09-09 15:08:12 +00005366
John McCalle61f2ba2009-11-18 02:36:19 +00005367 if (IsTypeName) {
5368 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005369 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005370 Diag(IdentLoc, diag::err_using_typename_non_type);
5371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5372 Diag((*I)->getUnderlyingDecl()->getLocation(),
5373 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005374 UD->setInvalidDecl();
5375 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005376 }
5377 } else {
5378 // If we asked for a non-typename and we got a type, error out,
5379 // but only if this is an instantiation of an unresolved using
5380 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005381 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005382 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5383 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005384 UD->setInvalidDecl();
5385 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005386 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005387 }
5388
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005389 // C++0x N2914 [namespace.udecl]p6:
5390 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005391 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005392 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5393 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005394 UD->setInvalidDecl();
5395 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005396 }
Mike Stump11289f42009-09-09 15:08:12 +00005397
John McCall84d87672009-12-10 09:41:52 +00005398 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5399 if (!CheckUsingShadowDecl(UD, *I, Previous))
5400 BuildUsingShadowDecl(S, UD, *I);
5401 }
John McCall3f746822009-11-17 05:59:44 +00005402
5403 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005404}
5405
Sebastian Redl08905022011-02-05 19:23:19 +00005406/// Additional checks for a using declaration referring to a constructor name.
5407bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5408 if (UD->isTypeName()) {
5409 // FIXME: Cannot specify typename when specifying constructor
5410 return true;
5411 }
5412
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005413 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00005414 assert(SourceType &&
5415 "Using decl naming constructor doesn't have type in scope spec.");
5416 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5417
5418 // Check whether the named type is a direct base class.
5419 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5420 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5421 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5422 BaseIt != BaseE; ++BaseIt) {
5423 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5424 if (CanonicalSourceType == BaseType)
5425 break;
5426 }
5427
5428 if (BaseIt == BaseE) {
5429 // Did not find SourceType in the bases.
5430 Diag(UD->getUsingLocation(),
5431 diag::err_using_decl_constructor_not_in_direct_base)
5432 << UD->getNameInfo().getSourceRange()
5433 << QualType(SourceType, 0) << TargetClass;
5434 return true;
5435 }
5436
5437 BaseIt->setInheritConstructors();
5438
5439 return false;
5440}
5441
John McCall84d87672009-12-10 09:41:52 +00005442/// Checks that the given using declaration is not an invalid
5443/// redeclaration. Note that this is checking only for the using decl
5444/// itself, not for any ill-formedness among the UsingShadowDecls.
5445bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5446 bool isTypeName,
5447 const CXXScopeSpec &SS,
5448 SourceLocation NameLoc,
5449 const LookupResult &Prev) {
5450 // C++03 [namespace.udecl]p8:
5451 // C++0x [namespace.udecl]p10:
5452 // A using-declaration is a declaration and can therefore be used
5453 // repeatedly where (and only where) multiple declarations are
5454 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00005455 //
John McCall032092f2010-11-29 18:01:58 +00005456 // That's in non-member contexts.
5457 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00005458 return false;
5459
5460 NestedNameSpecifier *Qual
5461 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5462
5463 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5464 NamedDecl *D = *I;
5465
5466 bool DTypename;
5467 NestedNameSpecifier *DQual;
5468 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5469 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005470 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005471 } else if (UnresolvedUsingValueDecl *UD
5472 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5473 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005474 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005475 } else if (UnresolvedUsingTypenameDecl *UD
5476 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5477 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005478 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005479 } else continue;
5480
5481 // using decls differ if one says 'typename' and the other doesn't.
5482 // FIXME: non-dependent using decls?
5483 if (isTypeName != DTypename) continue;
5484
5485 // using decls differ if they name different scopes (but note that
5486 // template instantiation can cause this check to trigger when it
5487 // didn't before instantiation).
5488 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5489 Context.getCanonicalNestedNameSpecifier(DQual))
5490 continue;
5491
5492 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00005493 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00005494 return true;
5495 }
5496
5497 return false;
5498}
5499
John McCall3969e302009-12-08 07:46:18 +00005500
John McCallb96ec562009-12-04 22:46:56 +00005501/// Checks that the given nested-name qualifier used in a using decl
5502/// in the current context is appropriately related to the current
5503/// scope. If an error is found, diagnoses it and returns true.
5504bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5505 const CXXScopeSpec &SS,
5506 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00005507 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005508
John McCall3969e302009-12-08 07:46:18 +00005509 if (!CurContext->isRecord()) {
5510 // C++03 [namespace.udecl]p3:
5511 // C++0x [namespace.udecl]p8:
5512 // A using-declaration for a class member shall be a member-declaration.
5513
5514 // If we weren't able to compute a valid scope, it must be a
5515 // dependent class scope.
5516 if (!NamedContext || NamedContext->isRecord()) {
5517 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5518 << SS.getRange();
5519 return true;
5520 }
5521
5522 // Otherwise, everything is known to be fine.
5523 return false;
5524 }
5525
5526 // The current scope is a record.
5527
5528 // If the named context is dependent, we can't decide much.
5529 if (!NamedContext) {
5530 // FIXME: in C++0x, we can diagnose if we can prove that the
5531 // nested-name-specifier does not refer to a base class, which is
5532 // still possible in some cases.
5533
5534 // Otherwise we have to conservatively report that things might be
5535 // okay.
5536 return false;
5537 }
5538
5539 if (!NamedContext->isRecord()) {
5540 // Ideally this would point at the last name in the specifier,
5541 // but we don't have that level of source info.
5542 Diag(SS.getRange().getBegin(),
5543 diag::err_using_decl_nested_name_specifier_is_not_class)
5544 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5545 return true;
5546 }
5547
Douglas Gregor7c842292010-12-21 07:41:49 +00005548 if (!NamedContext->isDependentContext() &&
5549 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5550 return true;
5551
John McCall3969e302009-12-08 07:46:18 +00005552 if (getLangOptions().CPlusPlus0x) {
5553 // C++0x [namespace.udecl]p3:
5554 // In a using-declaration used as a member-declaration, the
5555 // nested-name-specifier shall name a base class of the class
5556 // being defined.
5557
5558 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5559 cast<CXXRecordDecl>(NamedContext))) {
5560 if (CurContext == NamedContext) {
5561 Diag(NameLoc,
5562 diag::err_using_decl_nested_name_specifier_is_current_class)
5563 << SS.getRange();
5564 return true;
5565 }
5566
5567 Diag(SS.getRange().getBegin(),
5568 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5569 << (NestedNameSpecifier*) SS.getScopeRep()
5570 << cast<CXXRecordDecl>(CurContext)
5571 << SS.getRange();
5572 return true;
5573 }
5574
5575 return false;
5576 }
5577
5578 // C++03 [namespace.udecl]p4:
5579 // A using-declaration used as a member-declaration shall refer
5580 // to a member of a base class of the class being defined [etc.].
5581
5582 // Salient point: SS doesn't have to name a base class as long as
5583 // lookup only finds members from base classes. Therefore we can
5584 // diagnose here only if we can prove that that can't happen,
5585 // i.e. if the class hierarchies provably don't intersect.
5586
5587 // TODO: it would be nice if "definitely valid" results were cached
5588 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5589 // need to be repeated.
5590
5591 struct UserData {
5592 llvm::DenseSet<const CXXRecordDecl*> Bases;
5593
5594 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5595 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5596 Data->Bases.insert(Base);
5597 return true;
5598 }
5599
5600 bool hasDependentBases(const CXXRecordDecl *Class) {
5601 return !Class->forallBases(collect, this);
5602 }
5603
5604 /// Returns true if the base is dependent or is one of the
5605 /// accumulated base classes.
5606 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5607 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5608 return !Data->Bases.count(Base);
5609 }
5610
5611 bool mightShareBases(const CXXRecordDecl *Class) {
5612 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5613 }
5614 };
5615
5616 UserData Data;
5617
5618 // Returns false if we find a dependent base.
5619 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5620 return false;
5621
5622 // Returns false if the class has a dependent base or if it or one
5623 // of its bases is present in the base set of the current context.
5624 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5625 return false;
5626
5627 Diag(SS.getRange().getBegin(),
5628 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5629 << (NestedNameSpecifier*) SS.getScopeRep()
5630 << cast<CXXRecordDecl>(CurContext)
5631 << SS.getRange();
5632
5633 return true;
John McCallb96ec562009-12-04 22:46:56 +00005634}
5635
Richard Smithdda56e42011-04-15 14:24:37 +00005636Decl *Sema::ActOnAliasDeclaration(Scope *S,
5637 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005638 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00005639 SourceLocation UsingLoc,
5640 UnqualifiedId &Name,
5641 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00005642 // Skip up to the relevant declaration scope.
5643 while (S->getFlags() & Scope::TemplateParamScope)
5644 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00005645 assert((S->getFlags() & Scope::DeclScope) &&
5646 "got alias-declaration outside of declaration scope");
5647
5648 if (Type.isInvalid())
5649 return 0;
5650
5651 bool Invalid = false;
5652 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5653 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00005654 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00005655
5656 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5657 return 0;
5658
5659 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005660 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00005661 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005662 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5663 TInfo->getTypeLoc().getBeginLoc());
5664 }
Richard Smithdda56e42011-04-15 14:24:37 +00005665
5666 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5667 LookupName(Previous, S);
5668
5669 // Warn about shadowing the name of a template parameter.
5670 if (Previous.isSingleResult() &&
5671 Previous.getFoundDecl()->isTemplateParameter()) {
5672 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5673 Previous.getFoundDecl()))
5674 Invalid = true;
5675 Previous.clear();
5676 }
5677
5678 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5679 "name in alias declaration must be an identifier");
5680 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5681 Name.StartLocation,
5682 Name.Identifier, TInfo);
5683
5684 NewTD->setAccess(AS);
5685
5686 if (Invalid)
5687 NewTD->setInvalidDecl();
5688
Richard Smith3f1b5d02011-05-05 21:57:07 +00005689 CheckTypedefForVariablyModifiedType(S, NewTD);
5690 Invalid |= NewTD->isInvalidDecl();
5691
Richard Smithdda56e42011-04-15 14:24:37 +00005692 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005693
5694 NamedDecl *NewND;
5695 if (TemplateParamLists.size()) {
5696 TypeAliasTemplateDecl *OldDecl = 0;
5697 TemplateParameterList *OldTemplateParams = 0;
5698
5699 if (TemplateParamLists.size() != 1) {
5700 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5701 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5702 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5703 }
5704 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5705
5706 // Only consider previous declarations in the same scope.
5707 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5708 /*ExplicitInstantiationOrSpecialization*/false);
5709 if (!Previous.empty()) {
5710 Redeclaration = true;
5711
5712 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5713 if (!OldDecl && !Invalid) {
5714 Diag(UsingLoc, diag::err_redefinition_different_kind)
5715 << Name.Identifier;
5716
5717 NamedDecl *OldD = Previous.getRepresentativeDecl();
5718 if (OldD->getLocation().isValid())
5719 Diag(OldD->getLocation(), diag::note_previous_definition);
5720
5721 Invalid = true;
5722 }
5723
5724 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5725 if (TemplateParameterListsAreEqual(TemplateParams,
5726 OldDecl->getTemplateParameters(),
5727 /*Complain=*/true,
5728 TPL_TemplateMatch))
5729 OldTemplateParams = OldDecl->getTemplateParameters();
5730 else
5731 Invalid = true;
5732
5733 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5734 if (!Invalid &&
5735 !Context.hasSameType(OldTD->getUnderlyingType(),
5736 NewTD->getUnderlyingType())) {
5737 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5738 // but we can't reasonably accept it.
5739 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5740 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5741 if (OldTD->getLocation().isValid())
5742 Diag(OldTD->getLocation(), diag::note_previous_definition);
5743 Invalid = true;
5744 }
5745 }
5746 }
5747
5748 // Merge any previous default template arguments into our parameters,
5749 // and check the parameter list.
5750 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5751 TPC_TypeAliasTemplate))
5752 return 0;
5753
5754 TypeAliasTemplateDecl *NewDecl =
5755 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5756 Name.Identifier, TemplateParams,
5757 NewTD);
5758
5759 NewDecl->setAccess(AS);
5760
5761 if (Invalid)
5762 NewDecl->setInvalidDecl();
5763 else if (OldDecl)
5764 NewDecl->setPreviousDeclaration(OldDecl);
5765
5766 NewND = NewDecl;
5767 } else {
5768 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5769 NewND = NewTD;
5770 }
Richard Smithdda56e42011-04-15 14:24:37 +00005771
5772 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00005773 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00005774
Richard Smith3f1b5d02011-05-05 21:57:07 +00005775 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00005776}
5777
John McCall48871652010-08-21 09:40:31 +00005778Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005779 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005780 SourceLocation AliasLoc,
5781 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005782 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005783 SourceLocation IdentLoc,
5784 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00005785
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005786 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005787 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5788 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005789
Anders Carlssondca83c42009-03-28 06:23:46 +00005790 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00005791 NamedDecl *PrevDecl
5792 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5793 ForRedeclaration);
5794 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5795 PrevDecl = 0;
5796
5797 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005798 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00005799 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005800 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00005801 // FIXME: At some point, we'll want to create the (redundant)
5802 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00005803 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00005804 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00005805 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005806 }
Mike Stump11289f42009-09-09 15:08:12 +00005807
Anders Carlssondca83c42009-03-28 06:23:46 +00005808 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5809 diag::err_redefinition_different_kind;
5810 Diag(AliasLoc, DiagID) << Alias;
5811 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00005812 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00005813 }
5814
John McCall27b18f82009-11-17 02:14:36 +00005815 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005816 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005817
John McCall9f3059a2009-10-09 21:13:30 +00005818 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005819 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5820 CTC_NoKeywords, 0)) {
5821 if (R.getAsSingle<NamespaceDecl>() ||
5822 R.getAsSingle<NamespaceAliasDecl>()) {
5823 if (DeclContext *DC = computeDeclContext(SS, false))
5824 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5825 << Ident << DC << Corrected << SS.getRange()
5826 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5827 else
5828 Diag(IdentLoc, diag::err_using_directive_suggest)
5829 << Ident << Corrected
5830 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5831
5832 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5833 << Corrected;
5834
5835 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00005836 } else {
5837 R.clear();
5838 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005839 }
5840 }
5841
5842 if (R.empty()) {
5843 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005844 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005845 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00005846 }
Mike Stump11289f42009-09-09 15:08:12 +00005847
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005848 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00005849 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00005850 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00005851 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00005852
John McCalld8d0d432010-02-16 06:53:13 +00005853 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00005854 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00005855}
5856
Douglas Gregora57478e2010-05-01 15:04:51 +00005857namespace {
5858 /// \brief Scoped object used to handle the state changes required in Sema
5859 /// to implicitly define the body of a C++ member function;
5860 class ImplicitlyDefinedFunctionScope {
5861 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00005862 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00005863
5864 public:
5865 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00005866 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00005867 {
Douglas Gregora57478e2010-05-01 15:04:51 +00005868 S.PushFunctionScope();
5869 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5870 }
5871
5872 ~ImplicitlyDefinedFunctionScope() {
5873 S.PopExpressionEvaluationContext();
5874 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00005875 }
5876 };
5877}
5878
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005879Sema::ImplicitExceptionSpecification
5880Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00005881 // C++ [except.spec]p14:
5882 // An implicitly declared special member function (Clause 12) shall have an
5883 // exception-specification. [...]
5884 ImplicitExceptionSpecification ExceptSpec(Context);
5885
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005886 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005887 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5888 BEnd = ClassDecl->bases_end();
5889 B != BEnd; ++B) {
5890 if (B->isVirtual()) // Handled below.
5891 continue;
5892
Douglas Gregor9672f922010-07-03 00:47:00 +00005893 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5894 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005895 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5896 // If this is a deleted function, add it anyway. This might be conformant
5897 // with the standard. This might not. I'm not sure. It might not matter.
5898 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005899 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005900 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005901 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005902
5903 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005904 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5905 BEnd = ClassDecl->vbases_end();
5906 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00005907 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5908 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005909 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5910 // If this is a deleted function, add it anyway. This might be conformant
5911 // with the standard. This might not. I'm not sure. It might not matter.
5912 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005913 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005914 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005915 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005916
5917 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005918 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5919 FEnd = ClassDecl->field_end();
5920 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00005921 if (F->hasInClassInitializer()) {
5922 if (Expr *E = F->getInClassInitializer())
5923 ExceptSpec.CalledExpr(E);
5924 else if (!F->isInvalidDecl())
5925 ExceptSpec.SetDelayed();
5926 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00005927 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00005928 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5929 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5930 // If this is a deleted function, add it anyway. This might be conformant
5931 // with the standard. This might not. I'm not sure. It might not matter.
5932 // In particular, the problem is that this function never gets called. It
5933 // might just be ill-formed because this function attempts to refer to
5934 // a deleted function here.
5935 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005936 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005937 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005938 }
John McCalldb40c7f2010-12-14 08:05:40 +00005939
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005940 return ExceptSpec;
5941}
5942
5943CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5944 CXXRecordDecl *ClassDecl) {
5945 // C++ [class.ctor]p5:
5946 // A default constructor for a class X is a constructor of class X
5947 // that can be called without an argument. If there is no
5948 // user-declared constructor for class X, a default constructor is
5949 // implicitly declared. An implicitly-declared default constructor
5950 // is an inline public member of its class.
5951 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5952 "Should not build implicit default constructor!");
5953
5954 ImplicitExceptionSpecification Spec =
5955 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5956 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005957
Douglas Gregor6d880b12010-07-01 22:31:05 +00005958 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005959 CanQualType ClassType
5960 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005961 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005962 DeclarationName Name
5963 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005964 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005965 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00005966 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005967 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005968 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005969 /*TInfo=*/0,
5970 /*isExplicit=*/false,
5971 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005972 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005973 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00005974 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005975 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00005976 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00005977
5978 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00005979 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5980
Douglas Gregor0be31a22010-07-02 17:43:08 +00005981 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00005982 PushOnScopeChains(DefaultCon, S, false);
5983 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00005984
5985 if (ShouldDeleteDefaultConstructor(DefaultCon))
5986 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00005987
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005988 return DefaultCon;
5989}
5990
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005991void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5992 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00005993 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00005994 !Constructor->doesThisDeclarationHaveABody() &&
5995 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00005996 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005997
Anders Carlsson423f5d82010-04-23 16:04:08 +00005998 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00005999 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006000
Douglas Gregora57478e2010-05-01 15:04:51 +00006001 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006002 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006003 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006004 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006005 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006006 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006007 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006008 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006009 }
Douglas Gregor73193272010-09-20 16:48:21 +00006010
6011 SourceLocation Loc = Constructor->getLocation();
6012 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6013
6014 Constructor->setUsed();
6015 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006016
6017 if (ASTMutationListener *L = getASTMutationListener()) {
6018 L->CompletedImplicitDefinition(Constructor);
6019 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006020}
6021
Richard Smith938f40b2011-06-11 17:19:42 +00006022/// Get any existing defaulted default constructor for the given class. Do not
6023/// implicitly define one if it does not exist.
6024static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6025 CXXRecordDecl *D) {
6026 ASTContext &Context = Self.Context;
6027 QualType ClassType = Context.getTypeDeclType(D);
6028 DeclarationName ConstructorName
6029 = Context.DeclarationNames.getCXXConstructorName(
6030 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6031
6032 DeclContext::lookup_const_iterator Con, ConEnd;
6033 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6034 Con != ConEnd; ++Con) {
6035 // A function template cannot be defaulted.
6036 if (isa<FunctionTemplateDecl>(*Con))
6037 continue;
6038
6039 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6040 if (Constructor->isDefaultConstructor())
6041 return Constructor->isDefaulted() ? Constructor : 0;
6042 }
6043 return 0;
6044}
6045
6046void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6047 if (!D) return;
6048 AdjustDeclIfTemplate(D);
6049
6050 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6051 CXXConstructorDecl *CtorDecl
6052 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6053
6054 if (!CtorDecl) return;
6055
6056 // Compute the exception specification for the default constructor.
6057 const FunctionProtoType *CtorTy =
6058 CtorDecl->getType()->castAs<FunctionProtoType>();
6059 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6060 ImplicitExceptionSpecification Spec =
6061 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6062 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6063 assert(EPI.ExceptionSpecType != EST_Delayed);
6064
6065 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6066 }
6067
6068 // If the default constructor is explicitly defaulted, checking the exception
6069 // specification is deferred until now.
6070 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6071 !ClassDecl->isDependentType())
6072 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6073}
6074
Sebastian Redl08905022011-02-05 19:23:19 +00006075void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6076 // We start with an initial pass over the base classes to collect those that
6077 // inherit constructors from. If there are none, we can forgo all further
6078 // processing.
6079 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6080 BasesVector BasesToInheritFrom;
6081 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6082 BaseE = ClassDecl->bases_end();
6083 BaseIt != BaseE; ++BaseIt) {
6084 if (BaseIt->getInheritConstructors()) {
6085 QualType Base = BaseIt->getType();
6086 if (Base->isDependentType()) {
6087 // If we inherit constructors from anything that is dependent, just
6088 // abort processing altogether. We'll get another chance for the
6089 // instantiations.
6090 return;
6091 }
6092 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6093 }
6094 }
6095 if (BasesToInheritFrom.empty())
6096 return;
6097
6098 // Now collect the constructors that we already have in the current class.
6099 // Those take precedence over inherited constructors.
6100 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6101 // unless there is a user-declared constructor with the same signature in
6102 // the class where the using-declaration appears.
6103 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6104 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6105 CtorE = ClassDecl->ctor_end();
6106 CtorIt != CtorE; ++CtorIt) {
6107 ExistingConstructors.insert(
6108 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6109 }
6110
6111 Scope *S = getScopeForContext(ClassDecl);
6112 DeclarationName CreatedCtorName =
6113 Context.DeclarationNames.getCXXConstructorName(
6114 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6115
6116 // Now comes the true work.
6117 // First, we keep a map from constructor types to the base that introduced
6118 // them. Needed for finding conflicting constructors. We also keep the
6119 // actually inserted declarations in there, for pretty diagnostics.
6120 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6121 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6122 ConstructorToSourceMap InheritedConstructors;
6123 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6124 BaseE = BasesToInheritFrom.end();
6125 BaseIt != BaseE; ++BaseIt) {
6126 const RecordType *Base = *BaseIt;
6127 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6128 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6129 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6130 CtorE = BaseDecl->ctor_end();
6131 CtorIt != CtorE; ++CtorIt) {
6132 // Find the using declaration for inheriting this base's constructors.
6133 DeclarationName Name =
6134 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6135 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6136 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6137 SourceLocation UsingLoc = UD ? UD->getLocation() :
6138 ClassDecl->getLocation();
6139
6140 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6141 // from the class X named in the using-declaration consists of actual
6142 // constructors and notional constructors that result from the
6143 // transformation of defaulted parameters as follows:
6144 // - all non-template default constructors of X, and
6145 // - for each non-template constructor of X that has at least one
6146 // parameter with a default argument, the set of constructors that
6147 // results from omitting any ellipsis parameter specification and
6148 // successively omitting parameters with a default argument from the
6149 // end of the parameter-type-list.
6150 CXXConstructorDecl *BaseCtor = *CtorIt;
6151 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6152 const FunctionProtoType *BaseCtorType =
6153 BaseCtor->getType()->getAs<FunctionProtoType>();
6154
6155 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6156 maxParams = BaseCtor->getNumParams();
6157 params <= maxParams; ++params) {
6158 // Skip default constructors. They're never inherited.
6159 if (params == 0)
6160 continue;
6161 // Skip copy and move constructors for the same reason.
6162 if (CanBeCopyOrMove && params == 1)
6163 continue;
6164
6165 // Build up a function type for this particular constructor.
6166 // FIXME: The working paper does not consider that the exception spec
6167 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00006168 // source. This code doesn't yet, either. When it does, this code will
6169 // need to be delayed until after exception specifications and in-class
6170 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00006171 const Type *NewCtorType;
6172 if (params == maxParams)
6173 NewCtorType = BaseCtorType;
6174 else {
6175 llvm::SmallVector<QualType, 16> Args;
6176 for (unsigned i = 0; i < params; ++i) {
6177 Args.push_back(BaseCtorType->getArgType(i));
6178 }
6179 FunctionProtoType::ExtProtoInfo ExtInfo =
6180 BaseCtorType->getExtProtoInfo();
6181 ExtInfo.Variadic = false;
6182 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6183 Args.data(), params, ExtInfo)
6184 .getTypePtr();
6185 }
6186 const Type *CanonicalNewCtorType =
6187 Context.getCanonicalType(NewCtorType);
6188
6189 // Now that we have the type, first check if the class already has a
6190 // constructor with this signature.
6191 if (ExistingConstructors.count(CanonicalNewCtorType))
6192 continue;
6193
6194 // Then we check if we have already declared an inherited constructor
6195 // with this signature.
6196 std::pair<ConstructorToSourceMap::iterator, bool> result =
6197 InheritedConstructors.insert(std::make_pair(
6198 CanonicalNewCtorType,
6199 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6200 if (!result.second) {
6201 // Already in the map. If it came from a different class, that's an
6202 // error. Not if it's from the same.
6203 CanQualType PreviousBase = result.first->second.first;
6204 if (CanonicalBase != PreviousBase) {
6205 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6206 const CXXConstructorDecl *PrevBaseCtor =
6207 PrevCtor->getInheritedConstructor();
6208 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6209
6210 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6211 Diag(BaseCtor->getLocation(),
6212 diag::note_using_decl_constructor_conflict_current_ctor);
6213 Diag(PrevBaseCtor->getLocation(),
6214 diag::note_using_decl_constructor_conflict_previous_ctor);
6215 Diag(PrevCtor->getLocation(),
6216 diag::note_using_decl_constructor_conflict_previous_using);
6217 }
6218 continue;
6219 }
6220
6221 // OK, we're there, now add the constructor.
6222 // C++0x [class.inhctor]p8: [...] that would be performed by a
6223 // user-writtern inline constructor [...]
6224 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6225 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006226 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6227 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006228 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00006229 NewCtor->setAccess(BaseCtor->getAccess());
6230
6231 // Build up the parameter decls and add them.
6232 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6233 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006234 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6235 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006236 /*IdentifierInfo=*/0,
6237 BaseCtorType->getArgType(i),
6238 /*TInfo=*/0, SC_None,
6239 SC_None, /*DefaultArg=*/0));
6240 }
6241 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6242 NewCtor->setInheritedConstructor(BaseCtor);
6243
6244 PushOnScopeChains(NewCtor, S, false);
6245 ClassDecl->addDecl(NewCtor);
6246 result.first->second.second = NewCtor;
6247 }
6248 }
6249 }
6250}
6251
Alexis Huntf91729462011-05-12 22:46:25 +00006252Sema::ImplicitExceptionSpecification
6253Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006254 // C++ [except.spec]p14:
6255 // An implicitly declared special member function (Clause 12) shall have
6256 // an exception-specification.
6257 ImplicitExceptionSpecification ExceptSpec(Context);
6258
6259 // Direct base-class destructors.
6260 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6261 BEnd = ClassDecl->bases_end();
6262 B != BEnd; ++B) {
6263 if (B->isVirtual()) // Handled below.
6264 continue;
6265
6266 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6267 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006268 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006269 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006270
Douglas Gregorf1203042010-07-01 19:09:28 +00006271 // Virtual base-class destructors.
6272 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6273 BEnd = ClassDecl->vbases_end();
6274 B != BEnd; ++B) {
6275 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6276 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006277 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006278 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006279
Douglas Gregorf1203042010-07-01 19:09:28 +00006280 // Field destructors.
6281 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6282 FEnd = ClassDecl->field_end();
6283 F != FEnd; ++F) {
6284 if (const RecordType *RecordTy
6285 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6286 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006287 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006288 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006289
Alexis Huntf91729462011-05-12 22:46:25 +00006290 return ExceptSpec;
6291}
6292
6293CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6294 // C++ [class.dtor]p2:
6295 // If a class has no user-declared destructor, a destructor is
6296 // declared implicitly. An implicitly-declared destructor is an
6297 // inline public member of its class.
6298
6299 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006300 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006301 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6302
Douglas Gregor7454c562010-07-02 20:37:36 +00006303 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006304 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006305
Douglas Gregorf1203042010-07-01 19:09:28 +00006306 CanQualType ClassType
6307 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006308 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006309 DeclarationName Name
6310 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006311 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006312 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006313 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6314 /*isInline=*/true,
6315 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006316 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006317 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006318 Destructor->setImplicit();
6319 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006320
6321 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006322 ++ASTContext::NumImplicitDestructorsDeclared;
6323
6324 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006325 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006326 PushOnScopeChains(Destructor, S, false);
6327 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006328
6329 // This could be uniqued if it ever proves significant.
6330 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006331
6332 if (ShouldDeleteDestructor(Destructor))
6333 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006334
6335 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006336
Douglas Gregorf1203042010-07-01 19:09:28 +00006337 return Destructor;
6338}
6339
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006340void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006341 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006342 assert((Destructor->isDefaulted() &&
6343 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006344 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006345 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006346 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006347
Douglas Gregor54818f02010-05-12 16:39:35 +00006348 if (Destructor->isInvalidDecl())
6349 return;
6350
Douglas Gregora57478e2010-05-01 15:04:51 +00006351 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006352
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006353 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006354 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6355 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006356
Douglas Gregor54818f02010-05-12 16:39:35 +00006357 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006358 Diag(CurrentLocation, diag::note_member_synthesized_at)
6359 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6360
6361 Destructor->setInvalidDecl();
6362 return;
6363 }
6364
Douglas Gregor73193272010-09-20 16:48:21 +00006365 SourceLocation Loc = Destructor->getLocation();
6366 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6367
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006368 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006369 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006370
6371 if (ASTMutationListener *L = getASTMutationListener()) {
6372 L->CompletedImplicitDefinition(Destructor);
6373 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006374}
6375
Sebastian Redl623ea822011-05-19 05:13:44 +00006376void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6377 CXXDestructorDecl *destructor) {
6378 // C++11 [class.dtor]p3:
6379 // A declaration of a destructor that does not have an exception-
6380 // specification is implicitly considered to have the same exception-
6381 // specification as an implicit declaration.
6382 const FunctionProtoType *dtorType = destructor->getType()->
6383 getAs<FunctionProtoType>();
6384 if (dtorType->hasExceptionSpec())
6385 return;
6386
6387 ImplicitExceptionSpecification exceptSpec =
6388 ComputeDefaultedDtorExceptionSpec(classDecl);
6389
6390 // Replace the destructor's type.
6391 FunctionProtoType::ExtProtoInfo epi;
6392 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6393 epi.NumExceptions = exceptSpec.size();
6394 epi.Exceptions = exceptSpec.data();
6395 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6396
6397 destructor->setType(ty);
6398
6399 // FIXME: If the destructor has a body that could throw, and the newly created
6400 // spec doesn't allow exceptions, we should emit a warning, because this
6401 // change in behavior can break conforming C++03 programs at runtime.
6402 // However, we don't have a body yet, so it needs to be done somewhere else.
6403}
6404
Douglas Gregorb139cd52010-05-01 20:49:11 +00006405/// \brief Builds a statement that copies the given entity from \p From to
6406/// \c To.
6407///
6408/// This routine is used to copy the members of a class with an
6409/// implicitly-declared copy assignment operator. When the entities being
6410/// copied are arrays, this routine builds for loops to copy them.
6411///
6412/// \param S The Sema object used for type-checking.
6413///
6414/// \param Loc The location where the implicit copy is being generated.
6415///
6416/// \param T The type of the expressions being copied. Both expressions must
6417/// have this type.
6418///
6419/// \param To The expression we are copying to.
6420///
6421/// \param From The expression we are copying from.
6422///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006423/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6424/// Otherwise, it's a non-static member subobject.
6425///
Douglas Gregorb139cd52010-05-01 20:49:11 +00006426/// \param Depth Internal parameter recording the depth of the recursion.
6427///
6428/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00006429static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00006430BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00006431 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006432 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006433 // C++0x [class.copy]p30:
6434 // Each subobject is assigned in the manner appropriate to its type:
6435 //
6436 // - if the subobject is of class type, the copy assignment operator
6437 // for the class is used (as if by explicit qualification; that is,
6438 // ignoring any possible virtual overriding functions in more derived
6439 // classes);
6440 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6441 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6442
6443 // Look for operator=.
6444 DeclarationName Name
6445 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6446 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6447 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6448
6449 // Filter out any result that isn't a copy-assignment operator.
6450 LookupResult::Filter F = OpLookup.makeFilter();
6451 while (F.hasNext()) {
6452 NamedDecl *D = F.next();
6453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6454 if (Method->isCopyAssignmentOperator())
6455 continue;
6456
6457 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00006458 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006459 F.done();
6460
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006461 // Suppress the protected check (C++ [class.protected]) for each of the
6462 // assignment operators we found. This strange dance is required when
6463 // we're assigning via a base classes's copy-assignment operator. To
6464 // ensure that we're getting the right base class subobject (without
6465 // ambiguities), we need to cast "this" to that subobject type; to
6466 // ensure that we don't go through the virtual call mechanism, we need
6467 // to qualify the operator= name with the base class (see below). However,
6468 // this means that if the base class has a protected copy assignment
6469 // operator, the protected member access check will fail. So, we
6470 // rewrite "protected" access to "public" access in this case, since we
6471 // know by construction that we're calling from a derived class.
6472 if (CopyingBaseSubobject) {
6473 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6474 L != LEnd; ++L) {
6475 if (L.getAccess() == AS_protected)
6476 L.setAccess(AS_public);
6477 }
6478 }
6479
Douglas Gregorb139cd52010-05-01 20:49:11 +00006480 // Create the nested-name-specifier that will be used to qualify the
6481 // reference to operator=; this is required to suppress the virtual
6482 // call mechanism.
6483 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006484 SS.MakeTrivial(S.Context,
6485 NestedNameSpecifier::Create(S.Context, 0, false,
6486 T.getTypePtr()),
6487 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006488
6489 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00006490 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00006491 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006492 /*FirstQualifierInScope=*/0, OpLookup,
6493 /*TemplateArgs=*/0,
6494 /*SuppressQualifierCheck=*/true);
6495 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006496 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006497
6498 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00006499
John McCalldadc5752010-08-24 06:29:42 +00006500 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006501 OpEqualRef.takeAs<Expr>(),
6502 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006503 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006504 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006505
6506 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006507 }
John McCallab8c2732010-03-16 06:11:48 +00006508
Douglas Gregorb139cd52010-05-01 20:49:11 +00006509 // - if the subobject is of scalar type, the built-in assignment
6510 // operator is used.
6511 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6512 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00006513 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006514 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006515 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006516
6517 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006518 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006519
6520 // - if the subobject is an array, each element is assigned, in the
6521 // manner appropriate to the element type;
6522
6523 // Construct a loop over the array bounds, e.g.,
6524 //
6525 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6526 //
6527 // that will copy each of the array elements.
6528 QualType SizeType = S.Context.getSizeType();
6529
6530 // Create the iteration variable.
6531 IdentifierInfo *IterationVarName = 0;
6532 {
6533 llvm::SmallString<8> Str;
6534 llvm::raw_svector_ostream OS(Str);
6535 OS << "__i" << Depth;
6536 IterationVarName = &S.Context.Idents.get(OS.str());
6537 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00006538 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006539 IterationVarName, SizeType,
6540 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006541 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006542
6543 // Initialize the iteration variable to zero.
6544 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006545 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006546
6547 // Create a reference to the iteration variable; we'll use this several
6548 // times throughout.
6549 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00006550 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006551 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6552
6553 // Create the DeclStmt that holds the iteration variable.
6554 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6555
6556 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006557 llvm::APInt Upper
6558 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00006559 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00006560 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00006561 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6562 BO_NE, S.Context.BoolTy,
6563 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006564
6565 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006566 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00006567 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6568 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006569
6570 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006571 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6572 IterationVarRef, Loc));
6573 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6574 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006575
6576 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00006577 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6578 To, From, CopyingBaseSubobject,
6579 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00006580 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006581 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006582
6583 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00006584 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006585 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00006586 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00006587 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006588}
6589
Alexis Hunt119f3652011-05-14 05:23:20 +00006590std::pair<Sema::ImplicitExceptionSpecification, bool>
6591Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6592 CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006593 // C++ [class.copy]p10:
6594 // If the class definition does not explicitly declare a copy
6595 // assignment operator, one is declared implicitly.
6596 // The implicitly-defined copy assignment operator for a class X
6597 // will have the form
6598 //
6599 // X& X::operator=(const X&)
6600 //
6601 // if
6602 bool HasConstCopyAssignment = true;
6603
6604 // -- each direct base class B of X has a copy assignment operator
6605 // whose parameter is of type const B&, const volatile B& or B,
6606 // and
6607 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6608 BaseEnd = ClassDecl->bases_end();
6609 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00006610 // We'll handle this below
6611 if (LangOpts.CPlusPlus0x && Base->isVirtual())
6612 continue;
6613
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006614 assert(!Base->getType()->isDependentType() &&
6615 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00006616 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6617 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6618 &HasConstCopyAssignment);
6619 }
6620
6621 // In C++0x, the above citation has "or virtual added"
6622 if (LangOpts.CPlusPlus0x) {
6623 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6624 BaseEnd = ClassDecl->vbases_end();
6625 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6626 assert(!Base->getType()->isDependentType() &&
6627 "Cannot generate implicit members for class with dependent bases.");
6628 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6629 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6630 &HasConstCopyAssignment);
6631 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006632 }
6633
6634 // -- for all the nonstatic data members of X that are of a class
6635 // type M (or array thereof), each such class type has a copy
6636 // assignment operator whose parameter is of type const M&,
6637 // const volatile M& or M.
6638 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6639 FieldEnd = ClassDecl->field_end();
6640 HasConstCopyAssignment && Field != FieldEnd;
6641 ++Field) {
6642 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00006643 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6644 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
6645 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006646 }
6647 }
6648
6649 // Otherwise, the implicitly declared copy assignment operator will
6650 // have the form
6651 //
6652 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006653
Douglas Gregor68e11362010-07-01 17:48:08 +00006654 // C++ [except.spec]p14:
6655 // An implicitly declared special member function (Clause 12) shall have an
6656 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00006657
6658 // It is unspecified whether or not an implicit copy assignment operator
6659 // attempts to deduplicate calls to assignment operators of virtual bases are
6660 // made. As such, this exception specification is effectively unspecified.
6661 // Based on a similar decision made for constness in C++0x, we're erring on
6662 // the side of assuming such calls to be made regardless of whether they
6663 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00006664 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00006665 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00006666 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6667 BaseEnd = ClassDecl->bases_end();
6668 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00006669 if (Base->isVirtual())
6670 continue;
6671
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006672 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006673 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00006674 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6675 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00006676 ExceptSpec.CalledDecl(CopyAssign);
6677 }
Alexis Hunt491ec602011-06-21 23:42:56 +00006678
6679 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6680 BaseEnd = ClassDecl->vbases_end();
6681 Base != BaseEnd; ++Base) {
6682 CXXRecordDecl *BaseClassDecl
6683 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6684 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6685 ArgQuals, false, 0))
6686 ExceptSpec.CalledDecl(CopyAssign);
6687 }
6688
Douglas Gregor68e11362010-07-01 17:48:08 +00006689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6690 FieldEnd = ClassDecl->field_end();
6691 Field != FieldEnd;
6692 ++Field) {
6693 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00006694 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6695 if (CXXMethodDecl *CopyAssign =
6696 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
6697 ExceptSpec.CalledDecl(CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00006698 }
6699 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006700
Alexis Hunt119f3652011-05-14 05:23:20 +00006701 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6702}
6703
6704CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6705 // Note: The following rules are largely analoguous to the copy
6706 // constructor rules. Note that virtual bases are not taken into account
6707 // for determining the argument type of the operator. Note also that
6708 // operators taking an object instead of a reference are allowed.
6709
6710 ImplicitExceptionSpecification Spec(Context);
6711 bool Const;
6712 llvm::tie(Spec, Const) =
6713 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6714
6715 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6716 QualType RetType = Context.getLValueReferenceType(ArgType);
6717 if (Const)
6718 ArgType = ArgType.withConst();
6719 ArgType = Context.getLValueReferenceType(ArgType);
6720
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006721 // An implicitly-declared copy assignment operator is an inline public
6722 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00006723 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006724 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006725 SourceLocation ClassLoc = ClassDecl->getLocation();
6726 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006727 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00006728 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00006729 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006730 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00006731 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00006732 /*isInline=*/true,
6733 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006734 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00006735 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006736 CopyAssignment->setImplicit();
6737 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006738
6739 // Add the parameter to the operator.
6740 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006741 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006742 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006743 SC_None,
6744 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006745 CopyAssignment->setParams(&FromParam, 1);
6746
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006747 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006748 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00006749
Douglas Gregor0be31a22010-07-02 17:43:08 +00006750 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006751 PushOnScopeChains(CopyAssignment, S, false);
6752 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006753
Alexis Huntd74c85f2011-06-22 01:05:13 +00006754 // C++0x [class.copy]p18:
6755 // ... If the class definition declares a move constructor or move
6756 // assignment operator, the implicitly declared copy assignment operator is
6757 // defined as deleted; ...
6758 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
6759 ClassDecl->hasUserDeclaredMoveAssignment() ||
6760 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00006761 CopyAssignment->setDeletedAsWritten();
6762
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006763 AddOverriddenMethods(ClassDecl, CopyAssignment);
6764 return CopyAssignment;
6765}
6766
Douglas Gregorb139cd52010-05-01 20:49:11 +00006767void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6768 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00006769 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006770 CopyAssignOperator->isOverloadedOperator() &&
6771 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006772 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006773 "DefineImplicitCopyAssignment called for wrong function");
6774
6775 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6776
6777 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6778 CopyAssignOperator->setInvalidDecl();
6779 return;
6780 }
6781
6782 CopyAssignOperator->setUsed();
6783
6784 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006785 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006786
6787 // C++0x [class.copy]p30:
6788 // The implicitly-defined or explicitly-defaulted copy assignment operator
6789 // for a non-union class X performs memberwise copy assignment of its
6790 // subobjects. The direct base classes of X are assigned first, in the
6791 // order of their declaration in the base-specifier-list, and then the
6792 // immediate non-static data members of X are assigned, in the order in
6793 // which they were declared in the class definition.
6794
6795 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00006796 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006797
6798 // The parameter for the "other" object, which we are copying from.
6799 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6800 Qualifiers OtherQuals = Other->getType().getQualifiers();
6801 QualType OtherRefType = Other->getType();
6802 if (const LValueReferenceType *OtherRef
6803 = OtherRefType->getAs<LValueReferenceType>()) {
6804 OtherRefType = OtherRef->getPointeeType();
6805 OtherQuals = OtherRefType.getQualifiers();
6806 }
6807
6808 // Our location for everything implicitly-generated.
6809 SourceLocation Loc = CopyAssignOperator->getLocation();
6810
6811 // Construct a reference to the "other" object. We'll be using this
6812 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00006813 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006814 assert(OtherRef && "Reference to parameter cannot fail!");
6815
6816 // Construct the "this" pointer. We'll be using this throughout the generated
6817 // ASTs.
6818 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6819 assert(This && "Reference to this cannot fail!");
6820
6821 // Assign base classes.
6822 bool Invalid = false;
6823 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6824 E = ClassDecl->bases_end(); Base != E; ++Base) {
6825 // Form the assignment:
6826 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6827 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00006828 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006829 Invalid = true;
6830 continue;
6831 }
6832
John McCallcf142162010-08-07 06:22:56 +00006833 CXXCastPath BasePath;
6834 BasePath.push_back(Base);
6835
Douglas Gregorb139cd52010-05-01 20:49:11 +00006836 // Construct the "from" expression, which is an implicit cast to the
6837 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00006838 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00006839 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6840 CK_UncheckedDerivedToBase,
6841 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006842
6843 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00006844 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006845
6846 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00006847 To = ImpCastExprToType(To.take(),
6848 Context.getCVRQualifiedType(BaseType,
6849 CopyAssignOperator->getTypeQualifiers()),
6850 CK_UncheckedDerivedToBase,
6851 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006852
6853 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00006854 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00006855 To.get(), From,
6856 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006857 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006858 Diag(CurrentLocation, diag::note_member_synthesized_at)
6859 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6860 CopyAssignOperator->setInvalidDecl();
6861 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006862 }
6863
6864 // Success! Record the copy.
6865 Statements.push_back(Copy.takeAs<Expr>());
6866 }
6867
6868 // \brief Reference to the __builtin_memcpy function.
6869 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006870 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006871 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006872
6873 // Assign non-static members.
6874 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6875 FieldEnd = ClassDecl->field_end();
6876 Field != FieldEnd; ++Field) {
6877 // Check for members of reference type; we can't copy those.
6878 if (Field->getType()->isReferenceType()) {
6879 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6880 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6881 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006882 Diag(CurrentLocation, diag::note_member_synthesized_at)
6883 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006884 Invalid = true;
6885 continue;
6886 }
6887
6888 // Check for members of const-qualified, non-class type.
6889 QualType BaseType = Context.getBaseElementType(Field->getType());
6890 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6891 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6892 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6893 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006894 Diag(CurrentLocation, diag::note_member_synthesized_at)
6895 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006896 Invalid = true;
6897 continue;
6898 }
John McCall1b1a1db2011-06-17 00:18:42 +00006899
6900 // Suppress assigning zero-width bitfields.
6901 if (const Expr *Width = Field->getBitWidth())
6902 if (Width->EvaluateAsInt(Context) == 0)
6903 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006904
6905 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00006906 if (FieldType->isIncompleteArrayType()) {
6907 assert(ClassDecl->hasFlexibleArrayMember() &&
6908 "Incomplete array type is not valid");
6909 continue;
6910 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006911
6912 // Build references to the field in the object we're copying from and to.
6913 CXXScopeSpec SS; // Intentionally empty
6914 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6915 LookupMemberName);
6916 MemberLookup.addDecl(*Field);
6917 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00006918 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00006919 Loc, /*IsArrow=*/false,
6920 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00006921 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00006922 Loc, /*IsArrow=*/true,
6923 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006924 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6925 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6926
6927 // If the field should be copied with __builtin_memcpy rather than via
6928 // explicit assignments, do so. This optimization only applies for arrays
6929 // of scalars and arrays of class type with trivial copy-assignment
6930 // operators.
John McCall31168b02011-06-15 23:02:42 +00006931 if (FieldType->isArrayType() &&
6932 BaseType.hasTrivialCopyAssignment(Context)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006933 // Compute the size of the memory buffer to be copied.
6934 QualType SizeType = Context.getSizeType();
6935 llvm::APInt Size(Context.getTypeSize(SizeType),
6936 Context.getTypeSizeInChars(BaseType).getQuantity());
6937 for (const ConstantArrayType *Array
6938 = Context.getAsConstantArrayType(FieldType);
6939 Array;
6940 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00006941 llvm::APInt ArraySize
6942 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006943 Size *= ArraySize;
6944 }
6945
6946 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00006947 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6948 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006949
6950 bool NeedsCollectableMemCpy =
6951 (BaseType->isRecordType() &&
6952 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6953
6954 if (NeedsCollectableMemCpy) {
6955 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006956 // Create a reference to the __builtin_objc_memmove_collectable function.
6957 LookupResult R(*this,
6958 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006959 Loc, LookupOrdinaryName);
6960 LookupName(R, TUScope, true);
6961
6962 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6963 if (!CollectableMemCpy) {
6964 // Something went horribly wrong earlier, and we will have
6965 // complained about it.
6966 Invalid = true;
6967 continue;
6968 }
6969
6970 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6971 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006972 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006973 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6974 }
6975 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006976 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006977 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006978 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6979 LookupOrdinaryName);
6980 LookupName(R, TUScope, true);
6981
6982 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6983 if (!BuiltinMemCpy) {
6984 // Something went horribly wrong earlier, and we will have complained
6985 // about it.
6986 Invalid = true;
6987 continue;
6988 }
6989
6990 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6991 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006992 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006993 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6994 }
6995
John McCall37ad5512010-08-23 06:44:23 +00006996 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006997 CallArgs.push_back(To.takeAs<Expr>());
6998 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006999 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00007000 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007001 if (NeedsCollectableMemCpy)
7002 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007003 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007004 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007005 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007006 else
7007 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007008 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007009 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007010 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007011
Douglas Gregorb139cd52010-05-01 20:49:11 +00007012 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7013 Statements.push_back(Call.takeAs<Expr>());
7014 continue;
7015 }
7016
7017 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00007018 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00007019 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007020 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007021 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007022 Diag(CurrentLocation, diag::note_member_synthesized_at)
7023 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7024 CopyAssignOperator->setInvalidDecl();
7025 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007026 }
7027
7028 // Success! Record the copy.
7029 Statements.push_back(Copy.takeAs<Stmt>());
7030 }
7031
7032 if (!Invalid) {
7033 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007034 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007035
John McCalldadc5752010-08-24 06:29:42 +00007036 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007037 if (Return.isInvalid())
7038 Invalid = true;
7039 else {
7040 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007041
7042 if (Trap.hasErrorOccurred()) {
7043 Diag(CurrentLocation, diag::note_member_synthesized_at)
7044 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7045 Invalid = true;
7046 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007047 }
7048 }
7049
7050 if (Invalid) {
7051 CopyAssignOperator->setInvalidDecl();
7052 return;
7053 }
7054
John McCalldadc5752010-08-24 06:29:42 +00007055 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007056 /*isStmtExpr=*/false);
7057 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7058 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007059
7060 if (ASTMutationListener *L = getASTMutationListener()) {
7061 L->CompletedImplicitDefinition(CopyAssignOperator);
7062 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007063}
7064
Alexis Hunt913820d2011-05-13 06:10:58 +00007065std::pair<Sema::ImplicitExceptionSpecification, bool>
7066Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00007067 // C++ [class.copy]p5:
7068 // The implicitly-declared copy constructor for a class X will
7069 // have the form
7070 //
7071 // X::X(const X&)
7072 //
7073 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00007074 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00007075 bool HasConstCopyConstructor = true;
7076
7077 // -- each direct or virtual base class B of X has a copy
7078 // constructor whose first parameter is of type const B& or
7079 // const volatile B&, and
7080 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7081 BaseEnd = ClassDecl->bases_end();
7082 HasConstCopyConstructor && Base != BaseEnd;
7083 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007084 // Virtual bases are handled below.
7085 if (Base->isVirtual())
7086 continue;
7087
Douglas Gregora6d69502010-07-02 23:41:54 +00007088 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007089 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007090 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7091 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00007092 }
7093
7094 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7095 BaseEnd = ClassDecl->vbases_end();
7096 HasConstCopyConstructor && Base != BaseEnd;
7097 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007098 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00007099 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007100 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7101 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007102 }
7103
7104 // -- for all the nonstatic data members of X that are of a
7105 // class type M (or array thereof), each such class type
7106 // has a copy constructor whose first parameter is of type
7107 // const M& or const volatile M&.
7108 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7109 FieldEnd = ClassDecl->field_end();
7110 HasConstCopyConstructor && Field != FieldEnd;
7111 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007112 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007113 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007114 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
7115 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007116 }
7117 }
Douglas Gregor54be3392010-07-01 17:57:27 +00007118 // Otherwise, the implicitly declared copy constructor will have
7119 // the form
7120 //
7121 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00007122
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007123 // C++ [except.spec]p14:
7124 // An implicitly declared special member function (Clause 12) shall have an
7125 // exception-specification. [...]
7126 ImplicitExceptionSpecification ExceptSpec(Context);
7127 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7128 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7129 BaseEnd = ClassDecl->bases_end();
7130 Base != BaseEnd;
7131 ++Base) {
7132 // Virtual bases are handled below.
7133 if (Base->isVirtual())
7134 continue;
7135
Douglas Gregora6d69502010-07-02 23:41:54 +00007136 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007137 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007138 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007139 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007140 ExceptSpec.CalledDecl(CopyConstructor);
7141 }
7142 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7143 BaseEnd = ClassDecl->vbases_end();
7144 Base != BaseEnd;
7145 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007146 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007147 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007148 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007149 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007150 ExceptSpec.CalledDecl(CopyConstructor);
7151 }
7152 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7153 FieldEnd = ClassDecl->field_end();
7154 Field != FieldEnd;
7155 ++Field) {
7156 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007157 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7158 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007159 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00007160 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007161 }
7162 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007163
Alexis Hunt913820d2011-05-13 06:10:58 +00007164 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7165}
7166
7167CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7168 CXXRecordDecl *ClassDecl) {
7169 // C++ [class.copy]p4:
7170 // If the class definition does not explicitly declare a copy
7171 // constructor, one is declared implicitly.
7172
7173 ImplicitExceptionSpecification Spec(Context);
7174 bool Const;
7175 llvm::tie(Spec, Const) =
7176 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7177
7178 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7179 QualType ArgType = ClassType;
7180 if (Const)
7181 ArgType = ArgType.withConst();
7182 ArgType = Context.getLValueReferenceType(ArgType);
7183
7184 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7185
Douglas Gregor54be3392010-07-01 17:57:27 +00007186 DeclarationName Name
7187 = Context.DeclarationNames.getCXXConstructorName(
7188 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007189 SourceLocation ClassLoc = ClassDecl->getLocation();
7190 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00007191
7192 // An implicitly-declared copy constructor is an inline public
7193 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00007194 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00007195 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00007196 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00007197 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00007198 /*TInfo=*/0,
7199 /*isExplicit=*/false,
7200 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00007201 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00007202 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00007203 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00007204 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7205
Douglas Gregora6d69502010-07-02 23:41:54 +00007206 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00007207 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7208
Douglas Gregor54be3392010-07-01 17:57:27 +00007209 // Add the parameter to the constructor.
7210 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007211 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00007212 /*IdentifierInfo=*/0,
7213 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007214 SC_None,
7215 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00007216 CopyConstructor->setParams(&FromParam, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00007217
Douglas Gregor0be31a22010-07-02 17:43:08 +00007218 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00007219 PushOnScopeChains(CopyConstructor, S, false);
7220 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007221
Alexis Huntd74c85f2011-06-22 01:05:13 +00007222 // C++0x [class.copy]p7:
7223 // ... If the class definition declares a move constructor or move
7224 // assignment operator, the implicitly declared constructor is defined as
7225 // deleted; ...
7226 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7227 ClassDecl->hasUserDeclaredMoveAssignment() ||
7228 ShouldDeleteCopyConstructor(CopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007229 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00007230
7231 return CopyConstructor;
7232}
7233
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007234void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00007235 CXXConstructorDecl *CopyConstructor) {
7236 assert((CopyConstructor->isDefaulted() &&
7237 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007238 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007239 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007240
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00007241 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007242 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007243
Douglas Gregora57478e2010-05-01 15:04:51 +00007244 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007245 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007246
Alexis Hunt1d792652011-01-08 20:30:50 +00007247 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007248 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00007249 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00007250 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00007251 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00007252 } else {
7253 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7254 CopyConstructor->getLocation(),
7255 MultiStmtArg(*this, 0, 0),
7256 /*isStmtExpr=*/false)
7257 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00007258 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00007259
7260 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00007261
7262 if (ASTMutationListener *L = getASTMutationListener()) {
7263 L->CompletedImplicitDefinition(CopyConstructor);
7264 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007265}
7266
John McCalldadc5752010-08-24 06:29:42 +00007267ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007268Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00007269 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007270 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007271 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007272 unsigned ConstructKind,
7273 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00007274 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00007275
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007276 // C++0x [class.copy]p34:
7277 // When certain criteria are met, an implementation is allowed to
7278 // omit the copy/move construction of a class object, even if the
7279 // copy/move constructor and/or destructor for the object have
7280 // side effects. [...]
7281 // - when a temporary class object that has not been bound to a
7282 // reference (12.2) would be copied/moved to a class object
7283 // with the same cv-unqualified type, the copy/move operation
7284 // can be omitted by constructing the temporary object
7285 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00007286 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00007287 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007288 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00007289 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00007290 }
Mike Stump11289f42009-09-09 15:08:12 +00007291
7292 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007293 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007294 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00007295}
7296
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007297/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7298/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00007299ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007300Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7301 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007302 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007303 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007304 unsigned ConstructKind,
7305 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007306 unsigned NumExprs = ExprArgs.size();
7307 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00007308
Nick Lewyckyd4693212011-03-25 01:44:32 +00007309 for (specific_attr_iterator<NonNullAttr>
7310 i = Constructor->specific_attr_begin<NonNullAttr>(),
7311 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7312 const NonNullAttr *NonNull = *i;
7313 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7314 }
7315
Douglas Gregor27381f32009-11-23 12:27:39 +00007316 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00007317 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007318 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00007319 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007320 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7321 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007322}
7323
Mike Stump11289f42009-09-09 15:08:12 +00007324bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007325 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007326 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00007327 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00007328 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00007329 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00007330 move(Exprs), false, CXXConstructExpr::CK_Complete,
7331 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007332 if (TempResult.isInvalid())
7333 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007334
Anders Carlsson6eb55572009-08-25 05:12:04 +00007335 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00007336 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00007337 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00007338 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00007339 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00007340
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007341 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00007342}
7343
John McCall03c48482010-02-02 09:10:11 +00007344void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00007345 if (VD->isInvalidDecl()) return;
7346
John McCall03c48482010-02-02 09:10:11 +00007347 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00007348 if (ClassDecl->isInvalidDecl()) return;
7349 if (ClassDecl->hasTrivialDestructor()) return;
7350 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00007351
Chandler Carruth86d17d32011-03-27 21:26:48 +00007352 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7353 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7354 CheckDestructorAccess(VD->getLocation(), Destructor,
7355 PDiag(diag::err_access_dtor_var)
7356 << VD->getDeclName()
7357 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00007358
Chandler Carruth86d17d32011-03-27 21:26:48 +00007359 if (!VD->hasGlobalStorage()) return;
7360
7361 // Emit warning for non-trivial dtor in global scope (a real global,
7362 // class-static, function-static).
7363 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7364
7365 // TODO: this should be re-enabled for static locals by !CXAAtExit
7366 if (!VD->isStaticLocal())
7367 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007368}
7369
Mike Stump11289f42009-09-09 15:08:12 +00007370/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007371/// ActOnDeclarator, when a C++ direct initializer is present.
7372/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00007373void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007374 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007375 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00007376 SourceLocation RParenLoc,
7377 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00007378 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007379
7380 // If there is no declaration, there was an error parsing it. Just ignore
7381 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00007382 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007383 return;
Mike Stump11289f42009-09-09 15:08:12 +00007384
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007385 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7386 if (!VDecl) {
7387 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7388 RealDecl->setInvalidDecl();
7389 return;
7390 }
7391
Richard Smith30482bc2011-02-20 03:19:35 +00007392 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7393 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00007394 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7395 if (Exprs.size() > 1) {
7396 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7397 diag::err_auto_var_init_multiple_expressions)
7398 << VDecl->getDeclName() << VDecl->getType()
7399 << VDecl->getSourceRange();
7400 RealDecl->setInvalidDecl();
7401 return;
7402 }
7403
7404 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00007405 TypeSourceInfo *DeducedType = 0;
7406 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00007407 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7408 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7409 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00007410 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00007411 RealDecl->setInvalidDecl();
7412 return;
7413 }
Richard Smith9647d3c2011-03-17 16:11:59 +00007414 VDecl->setTypeSourceInfo(DeducedType);
7415 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00007416
John McCall31168b02011-06-15 23:02:42 +00007417 // In ARC, infer lifetime.
7418 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7419 VDecl->setInvalidDecl();
7420
Richard Smith30482bc2011-02-20 03:19:35 +00007421 // If this is a redeclaration, check that the type we just deduced matches
7422 // the previously declared type.
7423 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7424 MergeVarDeclTypes(VDecl, Old);
7425 }
7426
Douglas Gregor402250f2009-08-26 21:14:46 +00007427 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007428 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007429 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7430 //
7431 // Clients that want to distinguish between the two forms, can check for
7432 // direct initializer using VarDecl::hasCXXDirectInitializer().
7433 // A major benefit is that clients that don't particularly care about which
7434 // exactly form was it (like the CodeGen) can handle both cases without
7435 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007436
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007437 // C++ 8.5p11:
7438 // The form of initialization (using parentheses or '=') is generally
7439 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007440 // class type.
7441
Douglas Gregor50dc2192010-02-11 22:55:30 +00007442 if (!VDecl->getType()->isDependentType() &&
7443 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00007444 diag::err_typecheck_decl_incomplete_type)) {
7445 VDecl->setInvalidDecl();
7446 return;
7447 }
7448
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007449 // The variable can not have an abstract class type.
7450 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7451 diag::err_abstract_type_in_decl,
7452 AbstractVariableType))
7453 VDecl->setInvalidDecl();
7454
Sebastian Redl5ca79842010-02-01 20:16:42 +00007455 const VarDecl *Def;
7456 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007457 Diag(VDecl->getLocation(), diag::err_redefinition)
7458 << VDecl->getDeclName();
7459 Diag(Def->getLocation(), diag::note_previous_definition);
7460 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007461 return;
7462 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00007463
Douglas Gregorf0f83692010-08-24 05:27:49 +00007464 // C++ [class.static.data]p4
7465 // If a static data member is of const integral or const
7466 // enumeration type, its declaration in the class definition can
7467 // specify a constant-initializer which shall be an integral
7468 // constant expression (5.19). In that case, the member can appear
7469 // in integral constant expressions. The member shall still be
7470 // defined in a namespace scope if it is used in the program and the
7471 // namespace scope definition shall not contain an initializer.
7472 //
7473 // We already performed a redefinition check above, but for static
7474 // data members we also need to check whether there was an in-class
7475 // declaration with an initializer.
7476 const VarDecl* PrevInit = 0;
7477 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7478 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7479 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7480 return;
7481 }
7482
Douglas Gregor71f39c92010-12-16 01:31:22 +00007483 bool IsDependent = false;
7484 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7485 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7486 VDecl->setInvalidDecl();
7487 return;
7488 }
7489
7490 if (Exprs.get()[I]->isTypeDependent())
7491 IsDependent = true;
7492 }
7493
Douglas Gregor50dc2192010-02-11 22:55:30 +00007494 // If either the declaration has a dependent type or if any of the
7495 // expressions is type-dependent, we represent the initialization
7496 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00007497 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00007498 // Let clients know that initialization was done with a direct initializer.
7499 VDecl->setCXXDirectInitializer(true);
7500
7501 // Store the initialization expressions as a ParenListExpr.
7502 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00007503 VDecl->setInit(new (Context) ParenListExpr(
7504 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
7505 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00007506 return;
7507 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007508
7509 // Capture the variable that is being initialized and the style of
7510 // initialization.
7511 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7512
7513 // FIXME: Poor source location information.
7514 InitializationKind Kind
7515 = InitializationKind::CreateDirect(VDecl->getLocation(),
7516 LParenLoc, RParenLoc);
7517
7518 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00007519 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00007520 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007521 if (Result.isInvalid()) {
7522 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007523 return;
7524 }
John McCallacf0ee52010-10-08 02:01:28 +00007525
7526 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007527
Douglas Gregora40433a2010-12-07 00:41:46 +00007528 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00007529 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007530 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007531
John McCall8b7fd8f12011-01-19 11:48:09 +00007532 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007533}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007534
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007535/// \brief Given a constructor and the set of arguments provided for the
7536/// constructor, convert the arguments and add any required default arguments
7537/// to form a proper call to this constructor.
7538///
7539/// \returns true if an error occurred, false otherwise.
7540bool
7541Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7542 MultiExprArg ArgsPtr,
7543 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00007544 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007545 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7546 unsigned NumArgs = ArgsPtr.size();
7547 Expr **Args = (Expr **)ArgsPtr.get();
7548
7549 const FunctionProtoType *Proto
7550 = Constructor->getType()->getAs<FunctionProtoType>();
7551 assert(Proto && "Constructor without a prototype?");
7552 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007553
7554 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007555 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007556 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007557 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007558 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007559
7560 VariadicCallType CallType =
7561 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7562 llvm::SmallVector<Expr *, 8> AllArgs;
7563 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7564 Proto, 0, Args, NumArgs, AllArgs,
7565 CallType);
7566 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7567 ConvertedArgs.push_back(AllArgs[i]);
7568 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00007569}
7570
Anders Carlssone363c8e2009-12-12 00:32:00 +00007571static inline bool
7572CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7573 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007574 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00007575 if (isa<NamespaceDecl>(DC)) {
7576 return SemaRef.Diag(FnDecl->getLocation(),
7577 diag::err_operator_new_delete_declared_in_namespace)
7578 << FnDecl->getDeclName();
7579 }
7580
7581 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00007582 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007583 return SemaRef.Diag(FnDecl->getLocation(),
7584 diag::err_operator_new_delete_declared_static)
7585 << FnDecl->getDeclName();
7586 }
7587
Anders Carlsson60659a82009-12-12 02:43:16 +00007588 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00007589}
7590
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007591static inline bool
7592CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7593 CanQualType ExpectedResultType,
7594 CanQualType ExpectedFirstParamType,
7595 unsigned DependentParamTypeDiag,
7596 unsigned InvalidParamTypeDiag) {
7597 QualType ResultType =
7598 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7599
7600 // Check that the result type is not dependent.
7601 if (ResultType->isDependentType())
7602 return SemaRef.Diag(FnDecl->getLocation(),
7603 diag::err_operator_new_delete_dependent_result_type)
7604 << FnDecl->getDeclName() << ExpectedResultType;
7605
7606 // Check that the result type is what we expect.
7607 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7608 return SemaRef.Diag(FnDecl->getLocation(),
7609 diag::err_operator_new_delete_invalid_result_type)
7610 << FnDecl->getDeclName() << ExpectedResultType;
7611
7612 // A function template must have at least 2 parameters.
7613 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7614 return SemaRef.Diag(FnDecl->getLocation(),
7615 diag::err_operator_new_delete_template_too_few_parameters)
7616 << FnDecl->getDeclName();
7617
7618 // The function decl must have at least 1 parameter.
7619 if (FnDecl->getNumParams() == 0)
7620 return SemaRef.Diag(FnDecl->getLocation(),
7621 diag::err_operator_new_delete_too_few_parameters)
7622 << FnDecl->getDeclName();
7623
7624 // Check the the first parameter type is not dependent.
7625 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7626 if (FirstParamType->isDependentType())
7627 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7628 << FnDecl->getDeclName() << ExpectedFirstParamType;
7629
7630 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00007631 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007632 ExpectedFirstParamType)
7633 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7634 << FnDecl->getDeclName() << ExpectedFirstParamType;
7635
7636 return false;
7637}
7638
Anders Carlsson12308f42009-12-11 23:23:22 +00007639static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007640CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007641 // C++ [basic.stc.dynamic.allocation]p1:
7642 // A program is ill-formed if an allocation function is declared in a
7643 // namespace scope other than global scope or declared static in global
7644 // scope.
7645 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7646 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007647
7648 CanQualType SizeTy =
7649 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7650
7651 // C++ [basic.stc.dynamic.allocation]p1:
7652 // The return type shall be void*. The first parameter shall have type
7653 // std::size_t.
7654 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7655 SizeTy,
7656 diag::err_operator_new_dependent_param_type,
7657 diag::err_operator_new_param_type))
7658 return true;
7659
7660 // C++ [basic.stc.dynamic.allocation]p1:
7661 // The first parameter shall not have an associated default argument.
7662 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00007663 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007664 diag::err_operator_new_default_arg)
7665 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7666
7667 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00007668}
7669
7670static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00007671CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7672 // C++ [basic.stc.dynamic.deallocation]p1:
7673 // A program is ill-formed if deallocation functions are declared in a
7674 // namespace scope other than global scope or declared static in global
7675 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00007676 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7677 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007678
7679 // C++ [basic.stc.dynamic.deallocation]p2:
7680 // Each deallocation function shall return void and its first parameter
7681 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007682 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7683 SemaRef.Context.VoidPtrTy,
7684 diag::err_operator_delete_dependent_param_type,
7685 diag::err_operator_delete_param_type))
7686 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007687
Anders Carlsson12308f42009-12-11 23:23:22 +00007688 return false;
7689}
7690
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007691/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7692/// of this overloaded operator is well-formed. If so, returns false;
7693/// otherwise, emits appropriate diagnostics and returns true.
7694bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00007695 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007696 "Expected an overloaded operator declaration");
7697
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007698 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7699
Mike Stump11289f42009-09-09 15:08:12 +00007700 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007701 // The allocation and deallocation functions, operator new,
7702 // operator new[], operator delete and operator delete[], are
7703 // described completely in 3.7.3. The attributes and restrictions
7704 // found in the rest of this subclause do not apply to them unless
7705 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00007706 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00007707 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00007708
Anders Carlsson22f443f2009-12-12 00:26:23 +00007709 if (Op == OO_New || Op == OO_Array_New)
7710 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007711
7712 // C++ [over.oper]p6:
7713 // An operator function shall either be a non-static member
7714 // function or be a non-member function and have at least one
7715 // parameter whose type is a class, a reference to a class, an
7716 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00007717 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7718 if (MethodDecl->isStatic())
7719 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007720 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007721 } else {
7722 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00007723 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7724 ParamEnd = FnDecl->param_end();
7725 Param != ParamEnd; ++Param) {
7726 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00007727 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7728 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007729 ClassOrEnumParam = true;
7730 break;
7731 }
7732 }
7733
Douglas Gregord69246b2008-11-17 16:14:12 +00007734 if (!ClassOrEnumParam)
7735 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007736 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007737 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007738 }
7739
7740 // C++ [over.oper]p8:
7741 // An operator function cannot have default arguments (8.3.6),
7742 // except where explicitly stated below.
7743 //
Mike Stump11289f42009-09-09 15:08:12 +00007744 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007745 // (C++ [over.call]p1).
7746 if (Op != OO_Call) {
7747 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7748 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007749 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00007750 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00007751 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007752 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007753 }
7754 }
7755
Douglas Gregor6cf08062008-11-10 13:38:07 +00007756 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7757 { false, false, false }
7758#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7759 , { Unary, Binary, MemberOnly }
7760#include "clang/Basic/OperatorKinds.def"
7761 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007762
Douglas Gregor6cf08062008-11-10 13:38:07 +00007763 bool CanBeUnaryOperator = OperatorUses[Op][0];
7764 bool CanBeBinaryOperator = OperatorUses[Op][1];
7765 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007766
7767 // C++ [over.oper]p8:
7768 // [...] Operator functions cannot have more or fewer parameters
7769 // than the number required for the corresponding operator, as
7770 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00007771 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00007772 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007773 if (Op != OO_Call &&
7774 ((NumParams == 1 && !CanBeUnaryOperator) ||
7775 (NumParams == 2 && !CanBeBinaryOperator) ||
7776 (NumParams < 1) || (NumParams > 2))) {
7777 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007778 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00007779 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007780 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00007781 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007782 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007783 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00007784 assert(CanBeBinaryOperator &&
7785 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007786 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007787 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007788
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007789 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007790 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007791 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007792
Douglas Gregord69246b2008-11-17 16:14:12 +00007793 // Overloaded operators other than operator() cannot be variadic.
7794 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00007795 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007796 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007797 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007798 }
7799
7800 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00007801 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7802 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007803 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007804 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007805 }
7806
7807 // C++ [over.inc]p1:
7808 // The user-defined function called operator++ implements the
7809 // prefix and postfix ++ operator. If this function is a member
7810 // function with no parameters, or a non-member function with one
7811 // parameter of class or enumeration type, it defines the prefix
7812 // increment operator ++ for objects of that type. If the function
7813 // is a member function with one parameter (which shall be of type
7814 // int) or a non-member function with two parameters (the second
7815 // of which shall be of type int), it defines the postfix
7816 // increment operator ++ for objects of that type.
7817 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7818 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7819 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00007820 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007821 ParamIsInt = BT->getKind() == BuiltinType::Int;
7822
Chris Lattner2b786902008-11-21 07:50:02 +00007823 if (!ParamIsInt)
7824 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00007825 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007826 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007827 }
7828
Douglas Gregord69246b2008-11-17 16:14:12 +00007829 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007830}
Chris Lattner3b024a32008-12-17 07:09:26 +00007831
Alexis Huntc88db062010-01-13 09:01:02 +00007832/// CheckLiteralOperatorDeclaration - Check whether the declaration
7833/// of this literal operator function is well-formed. If so, returns
7834/// false; otherwise, emits appropriate diagnostics and returns true.
7835bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7836 DeclContext *DC = FnDecl->getDeclContext();
7837 Decl::Kind Kind = DC->getDeclKind();
7838 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7839 Kind != Decl::LinkageSpec) {
7840 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7841 << FnDecl->getDeclName();
7842 return true;
7843 }
7844
7845 bool Valid = false;
7846
Alexis Hunt7dd26172010-04-07 23:11:06 +00007847 // template <char...> type operator "" name() is the only valid template
7848 // signature, and the only valid signature with no parameters.
7849 if (FnDecl->param_size() == 0) {
7850 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7851 // Must have only one template parameter
7852 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7853 if (Params->size() == 1) {
7854 NonTypeTemplateParmDecl *PmDecl =
7855 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00007856
Alexis Hunt7dd26172010-04-07 23:11:06 +00007857 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00007858 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7859 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7860 Valid = true;
7861 }
7862 }
7863 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00007864 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00007865 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7866
Alexis Huntc88db062010-01-13 09:01:02 +00007867 QualType T = (*Param)->getType();
7868
Alexis Hunt079a6f72010-04-07 22:57:35 +00007869 // unsigned long long int, long double, and any character type are allowed
7870 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00007871 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7872 Context.hasSameType(T, Context.LongDoubleTy) ||
7873 Context.hasSameType(T, Context.CharTy) ||
7874 Context.hasSameType(T, Context.WCharTy) ||
7875 Context.hasSameType(T, Context.Char16Ty) ||
7876 Context.hasSameType(T, Context.Char32Ty)) {
7877 if (++Param == FnDecl->param_end())
7878 Valid = true;
7879 goto FinishedParams;
7880 }
7881
Alexis Hunt079a6f72010-04-07 22:57:35 +00007882 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00007883 const PointerType *PT = T->getAs<PointerType>();
7884 if (!PT)
7885 goto FinishedParams;
7886 T = PT->getPointeeType();
7887 if (!T.isConstQualified())
7888 goto FinishedParams;
7889 T = T.getUnqualifiedType();
7890
7891 // Move on to the second parameter;
7892 ++Param;
7893
7894 // If there is no second parameter, the first must be a const char *
7895 if (Param == FnDecl->param_end()) {
7896 if (Context.hasSameType(T, Context.CharTy))
7897 Valid = true;
7898 goto FinishedParams;
7899 }
7900
7901 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7902 // are allowed as the first parameter to a two-parameter function
7903 if (!(Context.hasSameType(T, Context.CharTy) ||
7904 Context.hasSameType(T, Context.WCharTy) ||
7905 Context.hasSameType(T, Context.Char16Ty) ||
7906 Context.hasSameType(T, Context.Char32Ty)))
7907 goto FinishedParams;
7908
7909 // The second and final parameter must be an std::size_t
7910 T = (*Param)->getType().getUnqualifiedType();
7911 if (Context.hasSameType(T, Context.getSizeType()) &&
7912 ++Param == FnDecl->param_end())
7913 Valid = true;
7914 }
7915
7916 // FIXME: This diagnostic is absolutely terrible.
7917FinishedParams:
7918 if (!Valid) {
7919 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7920 << FnDecl->getDeclName();
7921 return true;
7922 }
7923
7924 return false;
7925}
7926
Douglas Gregor07665a62009-01-05 19:45:36 +00007927/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7928/// linkage specification, including the language and (if present)
7929/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7930/// the location of the language string literal, which is provided
7931/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7932/// the '{' brace. Otherwise, this linkage specification does not
7933/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00007934Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7935 SourceLocation LangLoc,
7936 llvm::StringRef Lang,
7937 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00007938 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007939 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007940 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007941 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007942 Language = LinkageSpecDecl::lang_cxx;
7943 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00007944 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00007945 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00007946 }
Mike Stump11289f42009-09-09 15:08:12 +00007947
Chris Lattner438e5012008-12-17 07:13:27 +00007948 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00007949
Douglas Gregor07665a62009-01-05 19:45:36 +00007950 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007951 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007952 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00007953 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00007954 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00007955}
7956
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00007957/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00007958/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7959/// valid, it's the position of the closing '}' brace in a linkage
7960/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00007961Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007962 Decl *LinkageSpec,
7963 SourceLocation RBraceLoc) {
7964 if (LinkageSpec) {
7965 if (RBraceLoc.isValid()) {
7966 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7967 LSDecl->setRBraceLoc(RBraceLoc);
7968 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007969 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007970 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007971 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00007972}
7973
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007974/// \brief Perform semantic analysis for the variable declaration that
7975/// occurs within a C++ catch clause, returning the newly-created
7976/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007977VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00007978 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007979 SourceLocation StartLoc,
7980 SourceLocation Loc,
7981 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007982 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007983 QualType ExDeclType = TInfo->getType();
7984
Sebastian Redl54c04d42008-12-22 19:15:10 +00007985 // Arrays and functions decay.
7986 if (ExDeclType->isArrayType())
7987 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7988 else if (ExDeclType->isFunctionType())
7989 ExDeclType = Context.getPointerType(ExDeclType);
7990
7991 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7992 // The exception-declaration shall not denote a pointer or reference to an
7993 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00007994 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00007995 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007996 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00007997 Invalid = true;
7998 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007999
Douglas Gregor104ee002010-03-08 01:47:36 +00008000 // GCC allows catching pointers and references to incomplete types
8001 // as an extension; so do we, but we warn by default.
8002
Sebastian Redl54c04d42008-12-22 19:15:10 +00008003 QualType BaseType = ExDeclType;
8004 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00008005 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00008006 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008007 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008008 BaseType = Ptr->getPointeeType();
8009 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00008010 DK = diag::ext_catch_incomplete_ptr;
8011 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00008012 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00008013 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008014 BaseType = Ref->getPointeeType();
8015 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00008016 DK = diag::ext_catch_incomplete_ref;
8017 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008018 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00008019 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00008020 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8021 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00008022 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008023
Mike Stump11289f42009-09-09 15:08:12 +00008024 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008025 RequireNonAbstractType(Loc, ExDeclType,
8026 diag::err_abstract_type_in_decl,
8027 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00008028 Invalid = true;
8029
John McCall2ca705e2010-07-24 00:37:23 +00008030 // Only the non-fragile NeXT runtime currently supports C++ catches
8031 // of ObjC types, and no runtime supports catching ObjC types by value.
8032 if (!Invalid && getLangOptions().ObjC1) {
8033 QualType T = ExDeclType;
8034 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8035 T = RT->getPointeeType();
8036
8037 if (T->isObjCObjectType()) {
8038 Diag(Loc, diag::err_objc_object_catch);
8039 Invalid = true;
8040 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00008041 if (!getLangOptions().ObjCNonFragileABI)
8042 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00008043 }
8044 }
8045
Abramo Bagnaradff19302011-03-08 08:55:46 +00008046 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8047 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00008048 ExDecl->setExceptionVariable(true);
8049
Douglas Gregor6de584c2010-03-05 23:38:39 +00008050 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00008051 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00008052 // C++ [except.handle]p16:
8053 // The object declared in an exception-declaration or, if the
8054 // exception-declaration does not specify a name, a temporary (12.2) is
8055 // copy-initialized (8.5) from the exception object. [...]
8056 // The object is destroyed when the handler exits, after the destruction
8057 // of any automatic objects initialized within the handler.
8058 //
8059 // We just pretend to initialize the object with itself, then make sure
8060 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00008061 QualType initType = ExDeclType;
8062
8063 InitializedEntity entity =
8064 InitializedEntity::InitializeVariable(ExDecl);
8065 InitializationKind initKind =
8066 InitializationKind::CreateCopy(Loc, SourceLocation());
8067
8068 Expr *opaqueValue =
8069 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8070 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8071 ExprResult result = sequence.Perform(*this, entity, initKind,
8072 MultiExprArg(&opaqueValue, 1));
8073 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00008074 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00008075 else {
8076 // If the constructor used was non-trivial, set this as the
8077 // "initializer".
8078 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8079 if (!construct->getConstructor()->isTrivial()) {
8080 Expr *init = MaybeCreateExprWithCleanups(construct);
8081 ExDecl->setInit(init);
8082 }
8083
8084 // And make sure it's destructable.
8085 FinalizeVarWithDestructor(ExDecl, recordType);
8086 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00008087 }
8088 }
8089
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008090 if (Invalid)
8091 ExDecl->setInvalidDecl();
8092
8093 return ExDecl;
8094}
8095
8096/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8097/// handler.
John McCall48871652010-08-21 09:40:31 +00008098Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00008099 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00008100 bool Invalid = D.isInvalidType();
8101
8102 // Check for unexpanded parameter packs.
8103 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8104 UPPC_ExceptionType)) {
8105 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8106 D.getIdentifierLoc());
8107 Invalid = true;
8108 }
8109
Sebastian Redl54c04d42008-12-22 19:15:10 +00008110 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008111 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00008112 LookupOrdinaryName,
8113 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008114 // The scope should be freshly made just for us. There is just no way
8115 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00008116 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00008117 if (PrevDecl->isTemplateParameter()) {
8118 // Maybe we will complain about the shadowed template parameter.
8119 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008120 }
8121 }
8122
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008123 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008124 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8125 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008126 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008127 }
8128
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008129 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008130 D.getSourceRange().getBegin(),
8131 D.getIdentifierLoc(),
8132 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008133 if (Invalid)
8134 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00008135
Sebastian Redl54c04d42008-12-22 19:15:10 +00008136 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008137 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008138 PushOnScopeChains(ExDecl, S);
8139 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008140 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008141
Douglas Gregor758a8692009-06-17 21:51:59 +00008142 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00008143 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008144}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008145
Abramo Bagnaraea947882011-03-08 16:41:52 +00008146Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00008147 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00008148 Expr *AssertMessageExpr_,
8149 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00008150 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008151
Anders Carlsson54b26982009-03-14 00:33:21 +00008152 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8153 llvm::APSInt Value(32);
8154 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008155 Diag(StaticAssertLoc,
8156 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00008157 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008158 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00008159 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008160
Anders Carlsson54b26982009-03-14 00:33:21 +00008161 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008162 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00008163 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00008164 }
8165 }
Mike Stump11289f42009-09-09 15:08:12 +00008166
Douglas Gregoref68fee2010-12-15 23:55:21 +00008167 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8168 return 0;
8169
Abramo Bagnaraea947882011-03-08 16:41:52 +00008170 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8171 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00008172
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008173 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00008174 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008175}
Sebastian Redlf769df52009-03-24 22:27:57 +00008176
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008177/// \brief Perform semantic analysis of the given friend type declaration.
8178///
8179/// \returns A friend declaration that.
8180FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8181 TypeSourceInfo *TSInfo) {
8182 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8183
8184 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008185 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008186
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008187 if (!getLangOptions().CPlusPlus0x) {
8188 // C++03 [class.friend]p2:
8189 // An elaborated-type-specifier shall be used in a friend declaration
8190 // for a class.*
8191 //
8192 // * The class-key of the elaborated-type-specifier is required.
8193 if (!ActiveTemplateInstantiations.empty()) {
8194 // Do not complain about the form of friend template types during
8195 // template instantiation; we will already have complained when the
8196 // template was declared.
8197 } else if (!T->isElaboratedTypeSpecifier()) {
8198 // If we evaluated the type to a record type, suggest putting
8199 // a tag in front.
8200 if (const RecordType *RT = T->getAs<RecordType>()) {
8201 RecordDecl *RD = RT->getDecl();
8202
8203 std::string InsertionText = std::string(" ") + RD->getKindName();
8204
8205 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8206 << (unsigned) RD->getTagKind()
8207 << T
8208 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8209 InsertionText);
8210 } else {
8211 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8212 << T
8213 << SourceRange(FriendLoc, TypeRange.getEnd());
8214 }
8215 } else if (T->getAs<EnumType>()) {
8216 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008217 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008218 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008219 }
8220 }
8221
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008222 // C++0x [class.friend]p3:
8223 // If the type specifier in a friend declaration designates a (possibly
8224 // cv-qualified) class type, that class is declared as a friend; otherwise,
8225 // the friend declaration is ignored.
8226
8227 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8228 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008229
8230 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8231}
8232
John McCallace48cd2010-10-19 01:40:49 +00008233/// Handle a friend tag declaration where the scope specifier was
8234/// templated.
8235Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8236 unsigned TagSpec, SourceLocation TagLoc,
8237 CXXScopeSpec &SS,
8238 IdentifierInfo *Name, SourceLocation NameLoc,
8239 AttributeList *Attr,
8240 MultiTemplateParamsArg TempParamLists) {
8241 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8242
8243 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00008244 bool Invalid = false;
8245
8246 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008247 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00008248 TempParamLists.get(),
8249 TempParamLists.size(),
8250 /*friend*/ true,
8251 isExplicitSpecialization,
8252 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00008253 if (TemplateParams->size() > 0) {
8254 // This is a declaration of a class template.
8255 if (Invalid)
8256 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008257
John McCallace48cd2010-10-19 01:40:49 +00008258 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8259 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008260 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008261 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008262 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00008263 } else {
8264 // The "template<>" header is extraneous.
8265 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8266 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8267 isExplicitSpecialization = true;
8268 }
8269 }
8270
8271 if (Invalid) return 0;
8272
8273 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8274
8275 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00008276 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00008277 if (TempParamLists.get()[I]->size()) {
8278 isAllExplicitSpecializations = false;
8279 break;
8280 }
8281 }
8282
8283 // FIXME: don't ignore attributes.
8284
8285 // If it's explicit specializations all the way down, just forget
8286 // about the template header and build an appropriate non-templated
8287 // friend. TODO: for source fidelity, remember the headers.
8288 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008289 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00008290 ElaboratedTypeKeyword Keyword
8291 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008292 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008293 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00008294 if (T.isNull())
8295 return 0;
8296
8297 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8298 if (isa<DependentNameType>(T)) {
8299 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8300 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008301 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008302 TL.setNameLoc(NameLoc);
8303 } else {
8304 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8305 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008306 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008307 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8308 }
8309
8310 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8311 TSI, FriendLoc);
8312 Friend->setAccess(AS_public);
8313 CurContext->addDecl(Friend);
8314 return Friend;
8315 }
8316
8317 // Handle the case of a templated-scope friend class. e.g.
8318 // template <class T> class A<T>::B;
8319 // FIXME: we don't support these right now.
8320 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8321 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8322 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8323 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8324 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008325 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00008326 TL.setNameLoc(NameLoc);
8327
8328 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8329 TSI, FriendLoc);
8330 Friend->setAccess(AS_public);
8331 Friend->setUnsupportedFriend(true);
8332 CurContext->addDecl(Friend);
8333 return Friend;
8334}
8335
8336
John McCall11083da2009-09-16 22:47:08 +00008337/// Handle a friend type declaration. This works in tandem with
8338/// ActOnTag.
8339///
8340/// Notes on friend class templates:
8341///
8342/// We generally treat friend class declarations as if they were
8343/// declaring a class. So, for example, the elaborated type specifier
8344/// in a friend declaration is required to obey the restrictions of a
8345/// class-head (i.e. no typedefs in the scope chain), template
8346/// parameters are required to match up with simple template-ids, &c.
8347/// However, unlike when declaring a template specialization, it's
8348/// okay to refer to a template specialization without an empty
8349/// template parameter declaration, e.g.
8350/// friend class A<T>::B<unsigned>;
8351/// We permit this as a special case; if there are any template
8352/// parameters present at all, require proper matching, i.e.
8353/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00008354Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00008355 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008356 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00008357
8358 assert(DS.isFriendSpecified());
8359 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8360
John McCall11083da2009-09-16 22:47:08 +00008361 // Try to convert the decl specifier to a type. This works for
8362 // friend templates because ActOnTag never produces a ClassTemplateDecl
8363 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00008364 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00008365 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8366 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00008367 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00008368 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008369
Douglas Gregor6c110f32010-12-16 01:14:37 +00008370 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8371 return 0;
8372
John McCall11083da2009-09-16 22:47:08 +00008373 // This is definitely an error in C++98. It's probably meant to
8374 // be forbidden in C++0x, too, but the specification is just
8375 // poorly written.
8376 //
8377 // The problem is with declarations like the following:
8378 // template <T> friend A<T>::foo;
8379 // where deciding whether a class C is a friend or not now hinges
8380 // on whether there exists an instantiation of A that causes
8381 // 'foo' to equal C. There are restrictions on class-heads
8382 // (which we declare (by fiat) elaborated friend declarations to
8383 // be) that makes this tractable.
8384 //
8385 // FIXME: handle "template <> friend class A<T>;", which
8386 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00008387 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00008388 Diag(Loc, diag::err_tagless_friend_type_template)
8389 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008390 return 0;
John McCall11083da2009-09-16 22:47:08 +00008391 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008392
John McCallaa74a0c2009-08-28 07:59:38 +00008393 // C++98 [class.friend]p1: A friend of a class is a function
8394 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00008395 // This is fixed in DR77, which just barely didn't make the C++03
8396 // deadline. It's also a very silly restriction that seriously
8397 // affects inner classes and which nobody else seems to implement;
8398 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00008399 //
8400 // But note that we could warn about it: it's always useless to
8401 // friend one of your own members (it's not, however, worthless to
8402 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00008403
John McCall11083da2009-09-16 22:47:08 +00008404 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008405 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00008406 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008407 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00008408 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00008409 TSI,
John McCall11083da2009-09-16 22:47:08 +00008410 DS.getFriendSpecLoc());
8411 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008412 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8413
8414 if (!D)
John McCall48871652010-08-21 09:40:31 +00008415 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008416
John McCall11083da2009-09-16 22:47:08 +00008417 D->setAccess(AS_public);
8418 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00008419
John McCall48871652010-08-21 09:40:31 +00008420 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00008421}
8422
John McCallde3fd222010-10-12 23:13:28 +00008423Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8424 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008425 const DeclSpec &DS = D.getDeclSpec();
8426
8427 assert(DS.isFriendSpecified());
8428 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8429
8430 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00008431 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8432 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00008433
8434 // C++ [class.friend]p1
8435 // A friend of a class is a function or class....
8436 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00008437 // It *doesn't* see through dependent types, which is correct
8438 // according to [temp.arg.type]p3:
8439 // If a declaration acquires a function type through a
8440 // type dependent on a template-parameter and this causes
8441 // a declaration that does not use the syntactic form of a
8442 // function declarator to have a function type, the program
8443 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00008444 if (!T->isFunctionType()) {
8445 Diag(Loc, diag::err_unexpected_friend);
8446
8447 // It might be worthwhile to try to recover by creating an
8448 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00008449 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008450 }
8451
8452 // C++ [namespace.memdef]p3
8453 // - If a friend declaration in a non-local class first declares a
8454 // class or function, the friend class or function is a member
8455 // of the innermost enclosing namespace.
8456 // - The name of the friend is not found by simple name lookup
8457 // until a matching declaration is provided in that namespace
8458 // scope (either before or after the class declaration granting
8459 // friendship).
8460 // - If a friend function is called, its name may be found by the
8461 // name lookup that considers functions from namespaces and
8462 // classes associated with the types of the function arguments.
8463 // - When looking for a prior declaration of a class or a function
8464 // declared as a friend, scopes outside the innermost enclosing
8465 // namespace scope are not considered.
8466
John McCallde3fd222010-10-12 23:13:28 +00008467 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008468 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8469 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00008470 assert(Name);
8471
Douglas Gregor6c110f32010-12-16 01:14:37 +00008472 // Check for unexpanded parameter packs.
8473 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8474 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8475 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8476 return 0;
8477
John McCall07e91c02009-08-06 02:15:43 +00008478 // The context we found the declaration in, or in which we should
8479 // create the declaration.
8480 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00008481 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008482 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00008483 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00008484
John McCallde3fd222010-10-12 23:13:28 +00008485 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00008486
John McCallde3fd222010-10-12 23:13:28 +00008487 // There are four cases here.
8488 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00008489 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00008490 // there as appropriate.
8491 // Recover from invalid scope qualifiers as if they just weren't there.
8492 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00008493 // C++0x [namespace.memdef]p3:
8494 // If the name in a friend declaration is neither qualified nor
8495 // a template-id and the declaration is a function or an
8496 // elaborated-type-specifier, the lookup to determine whether
8497 // the entity has been previously declared shall not consider
8498 // any scopes outside the innermost enclosing namespace.
8499 // C++0x [class.friend]p11:
8500 // If a friend declaration appears in a local class and the name
8501 // specified is an unqualified name, a prior declaration is
8502 // looked up without considering scopes that are outside the
8503 // innermost enclosing non-class scope. For a friend function
8504 // declaration, if there is no prior declaration, the program is
8505 // ill-formed.
8506 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00008507 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00008508
John McCallf7cfb222010-10-13 05:45:15 +00008509 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00008510 DC = CurContext;
8511 while (true) {
8512 // Skip class contexts. If someone can cite chapter and verse
8513 // for this behavior, that would be nice --- it's what GCC and
8514 // EDG do, and it seems like a reasonable intent, but the spec
8515 // really only says that checks for unqualified existing
8516 // declarations should stop at the nearest enclosing namespace,
8517 // not that they should only consider the nearest enclosing
8518 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008519 while (DC->isRecord())
8520 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00008521
John McCall1f82f242009-11-18 22:49:29 +00008522 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00008523
8524 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00008525 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00008526 break;
John McCallf7cfb222010-10-13 05:45:15 +00008527
John McCallf4776592010-10-14 22:22:28 +00008528 if (isTemplateId) {
8529 if (isa<TranslationUnitDecl>(DC)) break;
8530 } else {
8531 if (DC->isFileContext()) break;
8532 }
John McCall07e91c02009-08-06 02:15:43 +00008533 DC = DC->getParent();
8534 }
8535
8536 // C++ [class.friend]p1: A friend of a class is a function or
8537 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00008538 // C++0x changes this for both friend types and functions.
8539 // Most C++ 98 compilers do seem to give an error here, so
8540 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00008541 if (!Previous.empty() && DC->Equals(CurContext)
8542 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00008543 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00008544
John McCallccbc0322010-10-13 06:22:15 +00008545 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00008546
John McCallde3fd222010-10-12 23:13:28 +00008547 // - There's a non-dependent scope specifier, in which case we
8548 // compute it and do a previous lookup there for a function
8549 // or function template.
8550 } else if (!SS.getScopeRep()->isDependent()) {
8551 DC = computeDeclContext(SS);
8552 if (!DC) return 0;
8553
8554 if (RequireCompleteDeclContext(SS, DC)) return 0;
8555
8556 LookupQualifiedName(Previous, DC);
8557
8558 // Ignore things found implicitly in the wrong scope.
8559 // TODO: better diagnostics for this case. Suggesting the right
8560 // qualified scope would be nice...
8561 LookupResult::Filter F = Previous.makeFilter();
8562 while (F.hasNext()) {
8563 NamedDecl *D = F.next();
8564 if (!DC->InEnclosingNamespaceSetOf(
8565 D->getDeclContext()->getRedeclContext()))
8566 F.erase();
8567 }
8568 F.done();
8569
8570 if (Previous.empty()) {
8571 D.setInvalidType();
8572 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8573 return 0;
8574 }
8575
8576 // C++ [class.friend]p1: A friend of a class is a function or
8577 // class that is not a member of the class . . .
8578 if (DC->Equals(CurContext))
8579 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8580
8581 // - There's a scope specifier that does not match any template
8582 // parameter lists, in which case we use some arbitrary context,
8583 // create a method or method template, and wait for instantiation.
8584 // - There's a scope specifier that does match some template
8585 // parameter lists, which we don't handle right now.
8586 } else {
8587 DC = CurContext;
8588 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00008589 }
8590
John McCallf7cfb222010-10-13 05:45:15 +00008591 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00008592 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00008593 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8594 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8595 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00008596 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00008597 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8598 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00008599 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008600 }
John McCall07e91c02009-08-06 02:15:43 +00008601 }
8602
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008603 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00008604 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00008605 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00008606 IsDefinition,
8607 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00008608 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00008609
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008610 assert(ND->getDeclContext() == DC);
8611 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00008612
John McCall759e32b2009-08-31 22:39:49 +00008613 // Add the function declaration to the appropriate lookup tables,
8614 // adjusting the redeclarations list as necessary. We don't
8615 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00008616 //
John McCall759e32b2009-08-31 22:39:49 +00008617 // Also update the scope-based lookup if the target context's
8618 // lookup context is in lexical scope.
8619 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008620 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008621 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008622 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008623 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008624 }
John McCallaa74a0c2009-08-28 07:59:38 +00008625
8626 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008627 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00008628 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00008629 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00008630 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00008631
John McCallde3fd222010-10-12 23:13:28 +00008632 if (ND->isInvalidDecl())
8633 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00008634 else {
8635 FunctionDecl *FD;
8636 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8637 FD = FTD->getTemplatedDecl();
8638 else
8639 FD = cast<FunctionDecl>(ND);
8640
8641 // Mark templated-scope function declarations as unsupported.
8642 if (FD->getNumTemplateParameterLists())
8643 FrD->setUnsupportedFriend(true);
8644 }
John McCallde3fd222010-10-12 23:13:28 +00008645
John McCall48871652010-08-21 09:40:31 +00008646 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00008647}
8648
John McCall48871652010-08-21 09:40:31 +00008649void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8650 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00008651
Sebastian Redlf769df52009-03-24 22:27:57 +00008652 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8653 if (!Fn) {
8654 Diag(DelLoc, diag::err_deleted_non_function);
8655 return;
8656 }
8657 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8658 Diag(DelLoc, diag::err_deleted_decl_not_first);
8659 Diag(Prev->getLocation(), diag::note_previous_declaration);
8660 // If the declaration wasn't the first, we delete the function anyway for
8661 // recovery.
8662 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008663 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00008664}
Sebastian Redl4c018662009-04-27 21:33:24 +00008665
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008666void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8667 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8668
8669 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +00008670 if (MD->getParent()->isDependentType()) {
8671 MD->setDefaulted();
8672 MD->setExplicitlyDefaulted();
8673 return;
8674 }
8675
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008676 CXXSpecialMember Member = getSpecialMember(MD);
8677 if (Member == CXXInvalid) {
8678 Diag(DefaultLoc, diag::err_default_special_members);
8679 return;
8680 }
8681
8682 MD->setDefaulted();
8683 MD->setExplicitlyDefaulted();
8684
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008685 // If this definition appears within the record, do the checking when
8686 // the record is complete.
8687 const FunctionDecl *Primary = MD;
8688 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8689 // Find the uninstantiated declaration that actually had the '= default'
8690 // on it.
8691 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8692
8693 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008694 return;
8695
8696 switch (Member) {
8697 case CXXDefaultConstructor: {
8698 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8699 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008700 if (!CD->isInvalidDecl())
8701 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8702 break;
8703 }
8704
8705 case CXXCopyConstructor: {
8706 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8707 CheckExplicitlyDefaultedCopyConstructor(CD);
8708 if (!CD->isInvalidDecl())
8709 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008710 break;
8711 }
Alexis Huntf91729462011-05-12 22:46:25 +00008712
Alexis Huntc9a55732011-05-14 05:23:28 +00008713 case CXXCopyAssignment: {
8714 CheckExplicitlyDefaultedCopyAssignment(MD);
8715 if (!MD->isInvalidDecl())
8716 DefineImplicitCopyAssignment(DefaultLoc, MD);
8717 break;
8718 }
8719
Alexis Huntf91729462011-05-12 22:46:25 +00008720 case CXXDestructor: {
8721 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8722 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008723 if (!DD->isInvalidDecl())
8724 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00008725 break;
8726 }
8727
Alexis Hunt119c10e2011-05-25 23:16:36 +00008728 case CXXMoveConstructor:
8729 case CXXMoveAssignment:
8730 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8731 break;
8732
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008733 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00008734 // FIXME: Do the rest once we have move functions
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008735 break;
8736 }
8737 } else {
8738 Diag(DefaultLoc, diag::err_default_special_members);
8739 }
8740}
8741
Sebastian Redl4c018662009-04-27 21:33:24 +00008742static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00008743 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00008744 Stmt *SubStmt = *CI;
8745 if (!SubStmt)
8746 continue;
8747 if (isa<ReturnStmt>(SubStmt))
8748 Self.Diag(SubStmt->getSourceRange().getBegin(),
8749 diag::err_return_in_constructor_handler);
8750 if (!isa<Expr>(SubStmt))
8751 SearchForReturnInStmt(Self, SubStmt);
8752 }
8753}
8754
8755void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8756 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8757 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8758 SearchForReturnInStmt(*this, Handler);
8759 }
8760}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008761
Mike Stump11289f42009-09-09 15:08:12 +00008762bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008763 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00008764 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8765 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008766
Chandler Carruth284bb2e2010-02-15 11:53:20 +00008767 if (Context.hasSameType(NewTy, OldTy) ||
8768 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008769 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008770
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008771 // Check if the return types are covariant
8772 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00008773
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008774 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008775 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8776 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008777 NewClassTy = NewPT->getPointeeType();
8778 OldClassTy = OldPT->getPointeeType();
8779 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008780 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8781 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8782 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8783 NewClassTy = NewRT->getPointeeType();
8784 OldClassTy = OldRT->getPointeeType();
8785 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008786 }
8787 }
Mike Stump11289f42009-09-09 15:08:12 +00008788
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008789 // The return types aren't either both pointers or references to a class type.
8790 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00008791 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008792 diag::err_different_return_type_for_overriding_virtual_function)
8793 << New->getDeclName() << NewTy << OldTy;
8794 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00008795
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008796 return true;
8797 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008798
Anders Carlssone60365b2009-12-31 18:34:24 +00008799 // C++ [class.virtual]p6:
8800 // If the return type of D::f differs from the return type of B::f, the
8801 // class type in the return type of D::f shall be complete at the point of
8802 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008803 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8804 if (!RT->isBeingDefined() &&
8805 RequireCompleteType(New->getLocation(), NewClassTy,
8806 PDiag(diag::err_covariant_return_incomplete)
8807 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00008808 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008809 }
Anders Carlssone60365b2009-12-31 18:34:24 +00008810
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008811 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008812 // Check if the new class derives from the old class.
8813 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8814 Diag(New->getLocation(),
8815 diag::err_covariant_return_not_derived)
8816 << New->getDeclName() << NewTy << OldTy;
8817 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8818 return true;
8819 }
Mike Stump11289f42009-09-09 15:08:12 +00008820
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008821 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00008822 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00008823 diag::err_covariant_return_inaccessible_base,
8824 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8825 // FIXME: Should this point to the return type?
8826 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00008827 // FIXME: this note won't trigger for delayed access control
8828 // diagnostics, and it's impossible to get an undelayed error
8829 // here from access control during the original parse because
8830 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008831 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8832 return true;
8833 }
8834 }
Mike Stump11289f42009-09-09 15:08:12 +00008835
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008836 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008837 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008838 Diag(New->getLocation(),
8839 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008840 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008841 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8842 return true;
8843 };
Mike Stump11289f42009-09-09 15:08:12 +00008844
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008845
8846 // The new class type must have the same or less qualifiers as the old type.
8847 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8848 Diag(New->getLocation(),
8849 diag::err_covariant_return_type_class_type_more_qualified)
8850 << New->getDeclName() << NewTy << OldTy;
8851 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8852 return true;
8853 };
Mike Stump11289f42009-09-09 15:08:12 +00008854
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008855 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008856}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008857
Douglas Gregor21920e372009-12-01 17:24:26 +00008858/// \brief Mark the given method pure.
8859///
8860/// \param Method the method to be marked pure.
8861///
8862/// \param InitRange the source range that covers the "0" initializer.
8863bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008864 SourceLocation EndLoc = InitRange.getEnd();
8865 if (EndLoc.isValid())
8866 Method->setRangeEnd(EndLoc);
8867
Douglas Gregor21920e372009-12-01 17:24:26 +00008868 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8869 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00008870 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008871 }
Douglas Gregor21920e372009-12-01 17:24:26 +00008872
8873 if (!Method->isInvalidDecl())
8874 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8875 << Method->getDeclName() << InitRange;
8876 return true;
8877}
8878
John McCall1f4ee7b2009-12-19 09:28:58 +00008879/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8880/// an initializer for the out-of-line declaration 'Dcl'. The scope
8881/// is a fresh scope pushed for just this purpose.
8882///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008883/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8884/// static data member of class X, names should be looked up in the scope of
8885/// class X.
John McCall48871652010-08-21 09:40:31 +00008886void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008887 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008888 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008889
John McCall1f4ee7b2009-12-19 09:28:58 +00008890 // We should only get called for declarations with scope specifiers, like:
8891 // int foo::bar;
8892 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008893 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008894}
8895
8896/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00008897/// initializer for the out-of-line declaration 'D'.
8898void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008899 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008900 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008901
John McCall1f4ee7b2009-12-19 09:28:58 +00008902 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008903 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008904}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008905
8906/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8907/// C++ if/switch/while/for statement.
8908/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00008909DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008910 // C++ 6.4p2:
8911 // The declarator shall not specify a function or an array.
8912 // The type-specifier-seq shall not contain typedef and shall not declare a
8913 // new class or enumeration.
8914 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8915 "Parser allowed 'typedef' as storage class of condition decl.");
8916
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008917 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00008918 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
8919 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008920
8921 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
8922 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
8923 // would be created and CXXConditionDeclExpr wants a VarDecl.
8924 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
8925 << D.getSourceRange();
8926 return DeclResult();
8927 } else if (OwnedTag && OwnedTag->isDefinition()) {
8928 // The type-specifier-seq shall not declare a new class or enumeration.
8929 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
8930 }
8931
John McCall48871652010-08-21 09:40:31 +00008932 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008933 if (!Dcl)
8934 return DeclResult();
8935
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008936 return Dcl;
8937}
Anders Carlssonf98849e2009-12-02 17:15:43 +00008938
Douglas Gregor88d292c2010-05-13 16:44:06 +00008939void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8940 bool DefinitionRequired) {
8941 // Ignore any vtable uses in unevaluated operands or for classes that do
8942 // not have a vtable.
8943 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8944 CurContext->isDependentContext() ||
8945 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00008946 return;
8947
Douglas Gregor88d292c2010-05-13 16:44:06 +00008948 // Try to insert this class into the map.
8949 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8950 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8951 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8952 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00008953 // If we already had an entry, check to see if we are promoting this vtable
8954 // to required a definition. If so, we need to reappend to the VTableUses
8955 // list, since we may have already processed the first entry.
8956 if (DefinitionRequired && !Pos.first->second) {
8957 Pos.first->second = true;
8958 } else {
8959 // Otherwise, we can early exit.
8960 return;
8961 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008962 }
8963
8964 // Local classes need to have their virtual members marked
8965 // immediately. For all other classes, we mark their virtual members
8966 // at the end of the translation unit.
8967 if (Class->isLocalClass())
8968 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00008969 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00008970 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00008971}
8972
Douglas Gregor88d292c2010-05-13 16:44:06 +00008973bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008974 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00008975 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00008976
Douglas Gregor88d292c2010-05-13 16:44:06 +00008977 // Note: The VTableUses vector could grow as a result of marking
8978 // the members of a class as "used", so we check the size each
8979 // time through the loop and prefer indices (with are stable) to
8980 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00008981 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00008982 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00008983 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00008984 if (!Class)
8985 continue;
8986
8987 SourceLocation Loc = VTableUses[I].second;
8988
8989 // If this class has a key function, but that key function is
8990 // defined in another translation unit, we don't need to emit the
8991 // vtable even though we're using it.
8992 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00008993 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008994 switch (KeyFunction->getTemplateSpecializationKind()) {
8995 case TSK_Undeclared:
8996 case TSK_ExplicitSpecialization:
8997 case TSK_ExplicitInstantiationDeclaration:
8998 // The key function is in another translation unit.
8999 continue;
9000
9001 case TSK_ExplicitInstantiationDefinition:
9002 case TSK_ImplicitInstantiation:
9003 // We will be instantiating the key function.
9004 break;
9005 }
9006 } else if (!KeyFunction) {
9007 // If we have a class with no key function that is the subject
9008 // of an explicit instantiation declaration, suppress the
9009 // vtable; it will live with the explicit instantiation
9010 // definition.
9011 bool IsExplicitInstantiationDeclaration
9012 = Class->getTemplateSpecializationKind()
9013 == TSK_ExplicitInstantiationDeclaration;
9014 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9015 REnd = Class->redecls_end();
9016 R != REnd; ++R) {
9017 TemplateSpecializationKind TSK
9018 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9019 if (TSK == TSK_ExplicitInstantiationDeclaration)
9020 IsExplicitInstantiationDeclaration = true;
9021 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9022 IsExplicitInstantiationDeclaration = false;
9023 break;
9024 }
9025 }
9026
9027 if (IsExplicitInstantiationDeclaration)
9028 continue;
9029 }
9030
9031 // Mark all of the virtual members of this class as referenced, so
9032 // that we can build a vtable. Then, tell the AST consumer that a
9033 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00009034 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009035 MarkVirtualMembersReferenced(Loc, Class);
9036 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9037 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9038
9039 // Optionally warn if we're emitting a weak vtable.
9040 if (Class->getLinkage() == ExternalLinkage &&
9041 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009042 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00009043 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9044 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00009045 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009046 VTableUses.clear();
9047
Douglas Gregor97509692011-04-22 22:25:37 +00009048 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00009049}
Anders Carlsson82fccd02009-12-07 08:24:59 +00009050
Rafael Espindola5b334082010-03-26 00:36:59 +00009051void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9052 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00009053 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9054 e = RD->method_end(); i != e; ++i) {
9055 CXXMethodDecl *MD = *i;
9056
9057 // C++ [basic.def.odr]p2:
9058 // [...] A virtual member function is used if it is not pure. [...]
9059 if (MD->isVirtual() && !MD->isPure())
9060 MarkDeclarationReferenced(Loc, MD);
9061 }
Rafael Espindola5b334082010-03-26 00:36:59 +00009062
9063 // Only classes that have virtual bases need a VTT.
9064 if (RD->getNumVBases() == 0)
9065 return;
9066
9067 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9068 e = RD->bases_end(); i != e; ++i) {
9069 const CXXRecordDecl *Base =
9070 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00009071 if (Base->getNumVBases() == 0)
9072 continue;
9073 MarkVirtualMembersReferenced(Loc, Base);
9074 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00009075}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009076
9077/// SetIvarInitializers - This routine builds initialization ASTs for the
9078/// Objective-C implementation whose ivars need be initialized.
9079void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9080 if (!getLangOptions().CPlusPlus)
9081 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00009082 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009083 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9084 CollectIvarsToConstructOrDestruct(OID, ivars);
9085 if (ivars.empty())
9086 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00009087 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009088 for (unsigned i = 0; i < ivars.size(); i++) {
9089 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00009090 if (Field->isInvalidDecl())
9091 continue;
9092
Alexis Hunt1d792652011-01-08 20:30:50 +00009093 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009094 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9095 InitializationKind InitKind =
9096 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9097
9098 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00009099 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00009100 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00009101 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009102 // Note, MemberInit could actually come back empty if no initialization
9103 // is required (e.g., because it would call a trivial default constructor)
9104 if (!MemberInit.get() || MemberInit.isInvalid())
9105 continue;
John McCallacf0ee52010-10-08 02:01:28 +00009106
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009107 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00009108 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9109 SourceLocation(),
9110 MemberInit.takeAs<Expr>(),
9111 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009112 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00009113
9114 // Be sure that the destructor is accessible and is marked as referenced.
9115 if (const RecordType *RecordTy
9116 = Context.getBaseElementType(Field->getType())
9117 ->getAs<RecordType>()) {
9118 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00009119 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00009120 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9121 CheckDestructorAccess(Field->getLocation(), Destructor,
9122 PDiag(diag::err_access_dtor_ivar)
9123 << Context.getBaseElementType(Field->getType()));
9124 }
9125 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009126 }
9127 ObjCImplementation->setIvarInitializers(Context,
9128 AllToInit.data(), AllToInit.size());
9129 }
9130}
Alexis Hunt6118d662011-05-04 05:57:24 +00009131
Alexis Hunt27a761d2011-05-04 23:29:54 +00009132static
9133void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9134 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9135 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9136 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9137 Sema &S) {
9138 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9139 CE = Current.end();
9140 if (Ctor->isInvalidDecl())
9141 return;
9142
9143 const FunctionDecl *FNTarget = 0;
9144 CXXConstructorDecl *Target;
9145
9146 // We ignore the result here since if we don't have a body, Target will be
9147 // null below.
9148 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9149 Target
9150= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9151
9152 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9153 // Avoid dereferencing a null pointer here.
9154 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9155
9156 if (!Current.insert(Canonical))
9157 return;
9158
9159 // We know that beyond here, we aren't chaining into a cycle.
9160 if (!Target || !Target->isDelegatingConstructor() ||
9161 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9162 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9163 Valid.insert(*CI);
9164 Current.clear();
9165 // We've hit a cycle.
9166 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9167 Current.count(TCanonical)) {
9168 // If we haven't diagnosed this cycle yet, do so now.
9169 if (!Invalid.count(TCanonical)) {
9170 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00009171 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00009172 << Ctor;
9173
9174 // Don't add a note for a function delegating directo to itself.
9175 if (TCanonical != Canonical)
9176 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9177
9178 CXXConstructorDecl *C = Target;
9179 while (C->getCanonicalDecl() != Canonical) {
9180 (void)C->getTargetConstructor()->hasBody(FNTarget);
9181 assert(FNTarget && "Ctor cycle through bodiless function");
9182
9183 C
9184 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9185 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9186 }
9187 }
9188
9189 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9190 Invalid.insert(*CI);
9191 Current.clear();
9192 } else {
9193 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9194 }
9195}
9196
9197
Alexis Hunt6118d662011-05-04 05:57:24 +00009198void Sema::CheckDelegatingCtorCycles() {
9199 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9200
Alexis Hunt27a761d2011-05-04 23:29:54 +00009201 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9202 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00009203
9204 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00009205 I = DelegatingCtorDecls.begin(),
9206 E = DelegatingCtorDecls.end();
9207 I != E; ++I) {
9208 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00009209 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00009210
9211 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9212 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00009213}