blob: de52b0aa5ea22533d3e4b2fbf23d3e5534cefbf1 [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
John McCallb1cd7da2010-06-04 08:34:12 +00001082 bool isFunc = false;
1083 if (D.isFunctionDeclarator())
1084 isFunc = true;
1085 else if (D.getNumTypeObjects() == 0 &&
1086 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +00001087 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +00001088 isFunc = TDType->isFunctionType();
1089 }
1090
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001091 // C++ 9.2p6: A member shall not be declared to have automatic storage
1092 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001093 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1094 // data members and cannot be applied to names declared const or static,
1095 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001096 switch (DS.getStorageClassSpec()) {
1097 case DeclSpec::SCS_unspecified:
1098 case DeclSpec::SCS_typedef:
1099 case DeclSpec::SCS_static:
1100 // FALL THROUGH.
1101 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001102 case DeclSpec::SCS_mutable:
1103 if (isFunc) {
1104 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001105 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001106 else
Chris Lattner3b054132008-11-19 05:08:23 +00001107 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001108
Sebastian Redl8071edb2008-11-17 23:24:37 +00001109 // FIXME: It would be nicer if the keyword was ignored only for this
1110 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001111 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001112 }
1113 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001114 default:
1115 if (DS.getStorageClassSpecLoc().isValid())
1116 Diag(DS.getStorageClassSpecLoc(),
1117 diag::err_storageclass_invalid_for_member);
1118 else
1119 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1120 D.getMutableDeclSpec().ClearStorageClassSpecs();
1121 }
1122
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001123 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1124 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001125 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001126
1127 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001128 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001129 CXXScopeSpec &SS = D.getCXXScopeSpec();
1130
Douglas Gregora007d362010-10-13 22:19:53 +00001131 if (SS.isSet() && !SS.isInvalid()) {
1132 // The user provided a superfluous scope specifier inside a class
1133 // definition:
1134 //
1135 // class X {
1136 // int X::member;
1137 // };
1138 DeclContext *DC = 0;
1139 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1140 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1141 << Name << FixItHint::CreateRemoval(SS.getRange());
1142 else
1143 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1144 << Name << SS.getRange();
1145
1146 SS.clear();
1147 }
1148
Douglas Gregor3447e762009-08-20 22:52:58 +00001149 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001150 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001151 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001152 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001153 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001154 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001155 assert(!HasDeferredInit);
1156
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001157 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001158 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001159 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001160 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001161
1162 // Non-instance-fields can't have a bitfield.
1163 if (BitWidth) {
1164 if (Member->isInvalidDecl()) {
1165 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001166 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001167 // C++ 9.6p3: A bit-field shall not be a static member.
1168 // "static member 'A' cannot be a bit-field"
1169 Diag(Loc, diag::err_static_not_bitfield)
1170 << Name << BitWidth->getSourceRange();
1171 } else if (isa<TypedefDecl>(Member)) {
1172 // "typedef member 'x' cannot be a bit-field"
1173 Diag(Loc, diag::err_typedef_not_bitfield)
1174 << Name << BitWidth->getSourceRange();
1175 } else {
1176 // A function typedef ("typedef int f(); f a;").
1177 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1178 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001179 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001180 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001181 }
Mike Stump11289f42009-09-09 15:08:12 +00001182
Chris Lattnerd26760a2009-03-05 23:01:03 +00001183 BitWidth = 0;
1184 Member->setInvalidDecl();
1185 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001186
1187 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Douglas Gregor3447e762009-08-20 22:52:58 +00001189 // If we have declared a member function template, set the access of the
1190 // templated declaration as well.
1191 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1192 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001193 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001194
Anders Carlsson13a69102011-01-20 04:34:22 +00001195 if (VS.isOverrideSpecified()) {
1196 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1197 if (!MD || !MD->isVirtual()) {
1198 Diag(Member->getLocStart(),
1199 diag::override_keyword_only_allowed_on_virtual_member_functions)
1200 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001201 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001202 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001203 }
1204 if (VS.isFinalSpecified()) {
1205 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1206 if (!MD || !MD->isVirtual()) {
1207 Diag(Member->getLocStart(),
1208 diag::override_keyword_only_allowed_on_virtual_member_functions)
1209 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001210 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001211 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001212 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001213
Douglas Gregorf2f08062011-03-08 17:10:18 +00001214 if (VS.getLastLocation().isValid()) {
1215 // Update the end location of a method that has a virt-specifiers.
1216 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1217 MD->setRangeEnd(VS.getLastLocation());
1218 }
1219
Anders Carlssonc87f8612011-01-20 06:29:02 +00001220 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001221
Douglas Gregor92751d42008-11-17 22:58:34 +00001222 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001223
Douglas Gregor0c880302009-03-11 23:00:04 +00001224 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001225 AddInitializerToDecl(Member, Init, false,
1226 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith938f40b2011-06-11 17:19:42 +00001227 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1228 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1229 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1230 // data member if a brace-or-equal-initializer is provided.
1231 Diag(Loc, diag::err_auto_var_requires_init)
1232 << Name << cast<ValueDecl>(Member)->getType();
1233 Member->setInvalidDecl();
1234 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001235
Richard Smithb2bc2e62011-02-21 20:05:19 +00001236 FinalizeDeclaration(Member);
1237
John McCall25849ca2011-02-15 07:12:36 +00001238 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001239 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001240 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001241}
1242
Richard Smith938f40b2011-06-11 17:19:42 +00001243/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1244/// in-class initializer for a non-static C++ class member. Such parsing
1245/// is deferred until the class is complete.
1246void
1247Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1248 Expr *InitExpr) {
1249 FieldDecl *FD = cast<FieldDecl>(D);
1250
1251 if (!InitExpr) {
1252 FD->setInvalidDecl();
1253 FD->removeInClassInitializer();
1254 return;
1255 }
1256
1257 ExprResult Init = InitExpr;
1258 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1259 // FIXME: if there is no EqualLoc, this is list-initialization.
1260 Init = PerformCopyInitialization(
1261 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1262 if (Init.isInvalid()) {
1263 FD->setInvalidDecl();
1264 return;
1265 }
1266
1267 CheckImplicitConversions(Init.get(), EqualLoc);
1268 }
1269
1270 // C++0x [class.base.init]p7:
1271 // The initialization of each base and member constitutes a
1272 // full-expression.
1273 Init = MaybeCreateExprWithCleanups(Init);
1274 if (Init.isInvalid()) {
1275 FD->setInvalidDecl();
1276 return;
1277 }
1278
1279 InitExpr = Init.release();
1280
1281 FD->setInClassInitializer(InitExpr);
1282}
1283
Douglas Gregor15e77a22009-12-31 09:10:24 +00001284/// \brief Find the direct and/or virtual base specifiers that
1285/// correspond to the given base type, for use in base initialization
1286/// within a constructor.
1287static bool FindBaseInitializer(Sema &SemaRef,
1288 CXXRecordDecl *ClassDecl,
1289 QualType BaseType,
1290 const CXXBaseSpecifier *&DirectBaseSpec,
1291 const CXXBaseSpecifier *&VirtualBaseSpec) {
1292 // First, check for a direct base class.
1293 DirectBaseSpec = 0;
1294 for (CXXRecordDecl::base_class_const_iterator Base
1295 = ClassDecl->bases_begin();
1296 Base != ClassDecl->bases_end(); ++Base) {
1297 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1298 // We found a direct base of this type. That's what we're
1299 // initializing.
1300 DirectBaseSpec = &*Base;
1301 break;
1302 }
1303 }
1304
1305 // Check for a virtual base class.
1306 // FIXME: We might be able to short-circuit this if we know in advance that
1307 // there are no virtual bases.
1308 VirtualBaseSpec = 0;
1309 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1310 // We haven't found a base yet; search the class hierarchy for a
1311 // virtual base class.
1312 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1313 /*DetectVirtual=*/false);
1314 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1315 BaseType, Paths)) {
1316 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1317 Path != Paths.end(); ++Path) {
1318 if (Path->back().Base->isVirtual()) {
1319 VirtualBaseSpec = Path->back().Base;
1320 break;
1321 }
1322 }
1323 }
1324 }
1325
1326 return DirectBaseSpec || VirtualBaseSpec;
1327}
1328
Douglas Gregore8381c02008-11-05 04:29:56 +00001329/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001330MemInitResult
John McCall48871652010-08-21 09:40:31 +00001331Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001332 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001333 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001334 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001335 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001336 SourceLocation IdLoc,
1337 SourceLocation LParenLoc,
1338 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001339 SourceLocation RParenLoc,
1340 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001341 if (!ConstructorD)
1342 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001343
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001344 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001345
1346 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001347 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001348 if (!Constructor) {
1349 // The user wrote a constructor initializer on a function that is
1350 // not a C++ constructor. Ignore the error for now, because we may
1351 // have more member initializers coming; we'll diagnose it just
1352 // once in ActOnMemInitializers.
1353 return true;
1354 }
1355
1356 CXXRecordDecl *ClassDecl = Constructor->getParent();
1357
1358 // C++ [class.base.init]p2:
1359 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001360 // constructor's class and, if not found in that scope, are looked
1361 // up in the scope containing the constructor's definition.
1362 // [Note: if the constructor's class contains a member with the
1363 // same name as a direct or virtual base class of the class, a
1364 // mem-initializer-id naming the member or base class and composed
1365 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001366 // mem-initializer-id for the hidden base class may be specified
1367 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001368 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001369 // Look for a member, first.
1370 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001371 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001372 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001373 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001374 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001375
Douglas Gregor44e7df62011-01-04 00:32:56 +00001376 if (Member) {
1377 if (EllipsisLoc.isValid())
1378 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1379 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1380
Francois Pichetd583da02010-12-04 09:14:42 +00001381 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001382 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001383 }
1384
Francois Pichetd583da02010-12-04 09:14:42 +00001385 // Handle anonymous union case.
1386 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001387 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1388 if (EllipsisLoc.isValid())
1389 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1390 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1391
Francois Pichetd583da02010-12-04 09:14:42 +00001392 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1393 NumArgs, IdLoc,
1394 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001395 }
Francois Pichetd583da02010-12-04 09:14:42 +00001396 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001397 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001398 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001399 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001400 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001401
1402 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001403 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001404 } else {
1405 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1406 LookupParsedName(R, S, &SS);
1407
1408 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1409 if (!TyD) {
1410 if (R.isAmbiguous()) return true;
1411
John McCallda6841b2010-04-09 19:01:14 +00001412 // We don't want access-control diagnostics here.
1413 R.suppressDiagnostics();
1414
Douglas Gregora3b624a2010-01-19 06:46:48 +00001415 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1416 bool NotUnknownSpecialization = false;
1417 DeclContext *DC = computeDeclContext(SS, false);
1418 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1419 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1420
1421 if (!NotUnknownSpecialization) {
1422 // When the scope specifier can refer to a member of an unknown
1423 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001424 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1425 SS.getWithLocInContext(Context),
1426 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001427 if (BaseType.isNull())
1428 return true;
1429
Douglas Gregora3b624a2010-01-19 06:46:48 +00001430 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001431 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001432 }
1433 }
1434
Douglas Gregor15e77a22009-12-31 09:10:24 +00001435 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001436 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001437 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1438 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001439 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001440 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001441 // We have found a non-static data member with a similar
1442 // name to what was typed; complain and initialize that
1443 // member.
1444 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1445 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001446 << FixItHint::CreateReplacement(R.getNameLoc(),
1447 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001448 Diag(Member->getLocation(), diag::note_previous_decl)
1449 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001450
1451 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1452 LParenLoc, RParenLoc);
1453 }
1454 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1455 const CXXBaseSpecifier *DirectBaseSpec;
1456 const CXXBaseSpecifier *VirtualBaseSpec;
1457 if (FindBaseInitializer(*this, ClassDecl,
1458 Context.getTypeDeclType(Type),
1459 DirectBaseSpec, VirtualBaseSpec)) {
1460 // We have found a direct or virtual base class with a
1461 // similar name to what was typed; complain and initialize
1462 // that base class.
1463 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1464 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001465 << FixItHint::CreateReplacement(R.getNameLoc(),
1466 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001467
1468 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1469 : VirtualBaseSpec;
1470 Diag(BaseSpec->getSourceRange().getBegin(),
1471 diag::note_base_class_specified_here)
1472 << BaseSpec->getType()
1473 << BaseSpec->getSourceRange();
1474
Douglas Gregor15e77a22009-12-31 09:10:24 +00001475 TyD = Type;
1476 }
1477 }
1478 }
1479
Douglas Gregora3b624a2010-01-19 06:46:48 +00001480 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001481 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1482 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1483 return true;
1484 }
John McCallb5a0d312009-12-21 10:41:20 +00001485 }
1486
Douglas Gregora3b624a2010-01-19 06:46:48 +00001487 if (BaseType.isNull()) {
1488 BaseType = Context.getTypeDeclType(TyD);
1489 if (SS.isSet()) {
1490 NestedNameSpecifier *Qualifier =
1491 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001492
Douglas Gregora3b624a2010-01-19 06:46:48 +00001493 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001494 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001495 }
John McCallb5a0d312009-12-21 10:41:20 +00001496 }
1497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498
John McCallbcd03502009-12-07 02:54:59 +00001499 if (!TInfo)
1500 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001501
John McCallbcd03502009-12-07 02:54:59 +00001502 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001503 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001504}
1505
John McCalle22a04a2009-11-04 23:02:40 +00001506/// Checks an initializer expression for use of uninitialized fields, such as
1507/// containing the field that is being initialized. Returns true if there is an
1508/// uninitialized field was used an updates the SourceLocation parameter; false
1509/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001510static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001511 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001512 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001513 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1514
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001515 if (isa<CallExpr>(S)) {
1516 // Do not descend into function calls or constructors, as the use
1517 // of an uninitialized field may be valid. One would have to inspect
1518 // the contents of the function/ctor to determine if it is safe or not.
1519 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1520 // may be safe, depending on what the function/ctor does.
1521 return false;
1522 }
1523 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1524 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001525
1526 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1527 // The member expression points to a static data member.
1528 assert(VD->isStaticDataMember() &&
1529 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001530 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001531 return false;
1532 }
1533
1534 if (isa<EnumConstantDecl>(RhsField)) {
1535 // The member expression points to an enum.
1536 return false;
1537 }
1538
John McCalle22a04a2009-11-04 23:02:40 +00001539 if (RhsField == LhsField) {
1540 // Initializing a field with itself. Throw a warning.
1541 // But wait; there are exceptions!
1542 // Exception #1: The field may not belong to this record.
1543 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001544 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001545 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1546 // Even though the field matches, it does not belong to this record.
1547 return false;
1548 }
1549 // None of the exceptions triggered; return true to indicate an
1550 // uninitialized field was used.
1551 *L = ME->getMemberLoc();
1552 return true;
1553 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001554 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001555 // sizeof/alignof doesn't reference contents, do not warn.
1556 return false;
1557 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1558 // address-of doesn't reference contents (the pointer may be dereferenced
1559 // in the same expression but it would be rare; and weird).
1560 if (UOE->getOpcode() == UO_AddrOf)
1561 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001562 }
John McCall8322c3a2011-02-13 04:07:26 +00001563 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001564 if (!*it) {
1565 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001566 continue;
1567 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001568 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1569 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001570 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001571 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001572}
1573
John McCallfaf5fb42010-08-26 23:41:50 +00001574MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001575Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001576 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001577 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001578 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001579 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1580 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1581 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001582 "Member must be a FieldDecl or IndirectFieldDecl");
1583
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001584 if (Member->isInvalidDecl())
1585 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001586
John McCalle22a04a2009-11-04 23:02:40 +00001587 // Diagnose value-uses of fields to initialize themselves, e.g.
1588 // foo(foo)
1589 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001590 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001591 for (unsigned i = 0; i < NumArgs; ++i) {
1592 SourceLocation L;
1593 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1594 // FIXME: Return true in the case when other fields are used before being
1595 // uninitialized. For example, let this field be the i'th field. When
1596 // initializing the i'th field, throw a warning if any of the >= i'th
1597 // fields are used, as they are not yet initialized.
1598 // Right now we are only handling the case where the i'th field uses
1599 // itself in its initializer.
1600 Diag(L, diag::warn_field_is_uninit);
1601 }
1602 }
1603
Eli Friedman8e1433b2009-07-29 19:44:27 +00001604 bool HasDependentArg = false;
1605 for (unsigned i = 0; i < NumArgs; i++)
1606 HasDependentArg |= Args[i]->isTypeDependent();
1607
Chandler Carruthd44c3102010-12-06 09:23:57 +00001608 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001609 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001610 // Can't check initialization for a member of dependent type or when
1611 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001612 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1613 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001614
John McCall31168b02011-06-15 23:02:42 +00001615 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00001616 } else {
1617 // Initialize the member.
1618 InitializedEntity MemberEntity =
1619 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1620 : InitializedEntity::InitializeMember(IndirectMember, 0);
1621 InitializationKind Kind =
1622 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001623
Chandler Carruthd44c3102010-12-06 09:23:57 +00001624 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1625
1626 ExprResult MemberInit =
1627 InitSeq.Perform(*this, MemberEntity, Kind,
1628 MultiExprArg(*this, Args, NumArgs), 0);
1629 if (MemberInit.isInvalid())
1630 return true;
1631
1632 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1633
1634 // C++0x [class.base.init]p7:
1635 // The initialization of each base and member constitutes a
1636 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001637 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001638 if (MemberInit.isInvalid())
1639 return true;
1640
1641 // If we are in a dependent context, template instantiation will
1642 // perform this type-checking again. Just save the arguments that we
1643 // received in a ParenListExpr.
1644 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1645 // of the information that we have about the member
1646 // initializer. However, deconstructing the ASTs is a dicey process,
1647 // and this approach is far more likely to get the corner cases right.
1648 if (CurContext->isDependentContext())
1649 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1650 RParenLoc);
1651 else
1652 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001653 }
1654
Chandler Carruthd44c3102010-12-06 09:23:57 +00001655 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001656 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001657 IdLoc, LParenLoc, Init,
1658 RParenLoc);
1659 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001660 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001661 IdLoc, LParenLoc, Init,
1662 RParenLoc);
1663 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001664}
1665
John McCallfaf5fb42010-08-26 23:41:50 +00001666MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001667Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1668 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001669 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001670 SourceLocation LParenLoc,
1671 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001672 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001673 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1674 if (!LangOpts.CPlusPlus0x)
1675 return Diag(Loc, diag::err_delegation_0x_only)
1676 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001677
Alexis Huntc5575cc2011-02-26 19:13:13 +00001678 // Initialize the object.
1679 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1680 QualType(ClassDecl->getTypeForDecl(), 0));
1681 InitializationKind Kind =
1682 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1683
1684 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1685
1686 ExprResult DelegationInit =
1687 InitSeq.Perform(*this, DelegationEntity, Kind,
1688 MultiExprArg(*this, Args, NumArgs), 0);
1689 if (DelegationInit.isInvalid())
1690 return true;
1691
1692 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001693 CXXConstructorDecl *Constructor
1694 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001695 assert(Constructor && "Delegating constructor with no target?");
1696
1697 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1698
1699 // C++0x [class.base.init]p7:
1700 // The initialization of each base and member constitutes a
1701 // full-expression.
1702 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1703 if (DelegationInit.isInvalid())
1704 return true;
1705
1706 // If we are in a dependent context, template instantiation will
1707 // perform this type-checking again. Just save the arguments that we
1708 // received in a ParenListExpr.
1709 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1710 // of the information that we have about the base
1711 // initializer. However, deconstructing the ASTs is a dicey process,
1712 // and this approach is far more likely to get the corner cases right.
1713 if (CurContext->isDependentContext()) {
1714 ExprResult Init
1715 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1716 NumArgs, RParenLoc));
1717 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1718 Constructor, Init.takeAs<Expr>(),
1719 RParenLoc);
1720 }
1721
1722 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1723 DelegationInit.takeAs<Expr>(),
1724 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001725}
1726
1727MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001728Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001729 Expr **Args, unsigned NumArgs,
1730 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001731 CXXRecordDecl *ClassDecl,
1732 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001733 bool HasDependentArg = false;
1734 for (unsigned i = 0; i < NumArgs; i++)
1735 HasDependentArg |= Args[i]->isTypeDependent();
1736
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001737 SourceLocation BaseLoc
1738 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1739
1740 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1741 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1742 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1743
1744 // C++ [class.base.init]p2:
1745 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001746 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001747 // of that class, the mem-initializer is ill-formed. A
1748 // mem-initializer-list can initialize a base class using any
1749 // name that denotes that base class type.
1750 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1751
Douglas Gregor44e7df62011-01-04 00:32:56 +00001752 if (EllipsisLoc.isValid()) {
1753 // This is a pack expansion.
1754 if (!BaseType->containsUnexpandedParameterPack()) {
1755 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1756 << SourceRange(BaseLoc, RParenLoc);
1757
1758 EllipsisLoc = SourceLocation();
1759 }
1760 } else {
1761 // Check for any unexpanded parameter packs.
1762 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1763 return true;
1764
1765 for (unsigned I = 0; I != NumArgs; ++I)
1766 if (DiagnoseUnexpandedParameterPack(Args[I]))
1767 return true;
1768 }
1769
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001770 // Check for direct and virtual base classes.
1771 const CXXBaseSpecifier *DirectBaseSpec = 0;
1772 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1773 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001774 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1775 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001776 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1777 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001778
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001779 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1780 VirtualBaseSpec);
1781
1782 // C++ [base.class.init]p2:
1783 // Unless the mem-initializer-id names a nonstatic data member of the
1784 // constructor's class or a direct or virtual base of that class, the
1785 // mem-initializer is ill-formed.
1786 if (!DirectBaseSpec && !VirtualBaseSpec) {
1787 // If the class has any dependent bases, then it's possible that
1788 // one of those types will resolve to the same type as
1789 // BaseType. Therefore, just treat this as a dependent base
1790 // class initialization. FIXME: Should we try to check the
1791 // initialization anyway? It seems odd.
1792 if (ClassDecl->hasAnyDependentBases())
1793 Dependent = true;
1794 else
1795 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1796 << BaseType << Context.getTypeDeclType(ClassDecl)
1797 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1798 }
1799 }
1800
1801 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001802 // Can't check initialization for a base of dependent type or when
1803 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001804 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001805 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1806 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001807
John McCall31168b02011-06-15 23:02:42 +00001808 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001809
Alexis Hunt1d792652011-01-08 20:30:50 +00001810 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001811 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001812 LParenLoc,
1813 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001814 RParenLoc,
1815 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001816 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001817
1818 // C++ [base.class.init]p2:
1819 // If a mem-initializer-id is ambiguous because it designates both
1820 // a direct non-virtual base class and an inherited virtual base
1821 // class, the mem-initializer is ill-formed.
1822 if (DirectBaseSpec && VirtualBaseSpec)
1823 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001824 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001825
1826 CXXBaseSpecifier *BaseSpec
1827 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1828 if (!BaseSpec)
1829 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1830
1831 // Initialize the base.
1832 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001833 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001834 InitializationKind Kind =
1835 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1836
1837 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1838
John McCalldadc5752010-08-24 06:29:42 +00001839 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001840 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001841 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001842 if (BaseInit.isInvalid())
1843 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001844
1845 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001846
1847 // C++0x [class.base.init]p7:
1848 // The initialization of each base and member constitutes a
1849 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001850 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001851 if (BaseInit.isInvalid())
1852 return true;
1853
1854 // If we are in a dependent context, template instantiation will
1855 // perform this type-checking again. Just save the arguments that we
1856 // received in a ParenListExpr.
1857 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1858 // of the information that we have about the base
1859 // initializer. However, deconstructing the ASTs is a dicey process,
1860 // and this approach is far more likely to get the corner cases right.
1861 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001862 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001863 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1864 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001865 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001866 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001867 LParenLoc,
1868 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001869 RParenLoc,
1870 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001871 }
1872
Alexis Hunt1d792652011-01-08 20:30:50 +00001873 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001874 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001875 LParenLoc,
1876 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001877 RParenLoc,
1878 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001879}
1880
Anders Carlsson1b00e242010-04-23 03:10:23 +00001881/// ImplicitInitializerKind - How an implicit base or member initializer should
1882/// initialize its base or member.
1883enum ImplicitInitializerKind {
1884 IIK_Default,
1885 IIK_Copy,
1886 IIK_Move
1887};
1888
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001889static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001890BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001891 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001892 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001893 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001894 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001895 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001896 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1897 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001898
John McCalldadc5752010-08-24 06:29:42 +00001899 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001900
1901 switch (ImplicitInitKind) {
1902 case IIK_Default: {
1903 InitializationKind InitKind
1904 = InitializationKind::CreateDefault(Constructor->getLocation());
1905 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1906 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001907 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001908 break;
1909 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001910
Anders Carlsson1b00e242010-04-23 03:10:23 +00001911 case IIK_Copy: {
1912 ParmVarDecl *Param = Constructor->getParamDecl(0);
1913 QualType ParamType = Param->getType().getNonReferenceType();
1914
1915 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001916 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001917 Constructor->getLocation(), ParamType,
1918 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001919
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001920 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001921 QualType ArgTy =
1922 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1923 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001924
1925 CXXCastPath BasePath;
1926 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001927 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1928 CK_UncheckedDerivedToBase,
1929 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001930
Anders Carlsson1b00e242010-04-23 03:10:23 +00001931 InitializationKind InitKind
1932 = InitializationKind::CreateDirect(Constructor->getLocation(),
1933 SourceLocation(), SourceLocation());
1934 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1935 &CopyCtorArg, 1);
1936 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001937 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001938 break;
1939 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001940
Anders Carlsson1b00e242010-04-23 03:10:23 +00001941 case IIK_Move:
1942 assert(false && "Unhandled initializer kind!");
1943 }
John McCallb268a282010-08-23 23:25:46 +00001944
Douglas Gregora40433a2010-12-07 00:41:46 +00001945 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001946 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001947 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001948
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001949 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001950 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001951 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1952 SourceLocation()),
1953 BaseSpec->isVirtual(),
1954 SourceLocation(),
1955 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001956 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001957 SourceLocation());
1958
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001959 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001960}
1961
Anders Carlsson3c1db572010-04-23 02:15:47 +00001962static bool
1963BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001964 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001965 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001966 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001967 if (Field->isInvalidDecl())
1968 return true;
1969
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001970 SourceLocation Loc = Constructor->getLocation();
1971
Anders Carlsson423f5d82010-04-23 16:04:08 +00001972 if (ImplicitInitKind == IIK_Copy) {
1973 ParmVarDecl *Param = Constructor->getParamDecl(0);
1974 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00001975
1976 // Suppress copying zero-width bitfields.
1977 if (const Expr *Width = Field->getBitWidth())
1978 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1979 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00001980
1981 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001982 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001983 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001984
1985 // Build a reference to this field within the parameter.
1986 CXXScopeSpec SS;
1987 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1988 Sema::LookupMemberName);
1989 MemberLookup.addDecl(Field, AS_public);
1990 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001991 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001992 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001993 ParamType, Loc,
1994 /*IsArrow=*/false,
1995 SS,
1996 /*FirstQualifierInScope=*/0,
1997 MemberLookup,
1998 /*TemplateArgs=*/0);
1999 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002000 return true;
2001
Douglas Gregor94f9a482010-05-05 05:51:00 +00002002 // When the field we are copying is an array, create index variables for
2003 // each dimension of the array. We use these index variables to subscript
2004 // the source array, and other clients (e.g., CodeGen) will perform the
2005 // necessary iteration with these index variables.
2006 llvm::SmallVector<VarDecl *, 4> IndexVariables;
2007 QualType BaseType = Field->getType();
2008 QualType SizeType = SemaRef.Context.getSizeType();
2009 while (const ConstantArrayType *Array
2010 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2011 // Create the iteration variable for this array index.
2012 IdentifierInfo *IterationVarName = 0;
2013 {
2014 llvm::SmallString<8> Str;
2015 llvm::raw_svector_ostream OS(Str);
2016 OS << "__i" << IndexVariables.size();
2017 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2018 }
2019 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002020 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002021 IterationVarName, SizeType,
2022 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002023 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002024 IndexVariables.push_back(IterationVar);
2025
2026 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002027 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002028 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002029 assert(!IterationVarRef.isInvalid() &&
2030 "Reference to invented variable cannot fail!");
2031
2032 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00002033 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002034 Loc,
John McCallb268a282010-08-23 23:25:46 +00002035 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002036 Loc);
2037 if (CopyCtorArg.isInvalid())
2038 return true;
2039
2040 BaseType = Array->getElementType();
2041 }
2042
2043 // Construct the entity that we will be initializing. For an array, this
2044 // will be first element in the array, which may require several levels
2045 // of array-subscript entities.
2046 llvm::SmallVector<InitializedEntity, 4> Entities;
2047 Entities.reserve(1 + IndexVariables.size());
2048 Entities.push_back(InitializedEntity::InitializeMember(Field));
2049 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2050 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2051 0,
2052 Entities.back()));
2053
2054 // Direct-initialize to use the copy constructor.
2055 InitializationKind InitKind =
2056 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2057
2058 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2059 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2060 &CopyCtorArgE, 1);
2061
John McCalldadc5752010-08-24 06:29:42 +00002062 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002063 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002064 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002065 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002066 if (MemberInit.isInvalid())
2067 return true;
2068
2069 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00002070 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002071 MemberInit.takeAs<Expr>(), Loc,
2072 IndexVariables.data(),
2073 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002074 return false;
2075 }
2076
Anders Carlsson423f5d82010-04-23 16:04:08 +00002077 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2078
Anders Carlsson3c1db572010-04-23 02:15:47 +00002079 QualType FieldBaseElementType =
2080 SemaRef.Context.getBaseElementType(Field->getType());
2081
Anders Carlsson3c1db572010-04-23 02:15:47 +00002082 if (FieldBaseElementType->isRecordType()) {
2083 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002084 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002085 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002086
2087 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002088 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002089 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002090
Douglas Gregora40433a2010-12-07 00:41:46 +00002091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002092 if (MemberInit.isInvalid())
2093 return true;
2094
2095 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002096 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002097 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002098 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002099 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002100 return false;
2101 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002102
Alexis Hunt8b455182011-05-17 00:19:05 +00002103 if (!Field->getParent()->isUnion()) {
2104 if (FieldBaseElementType->isReferenceType()) {
2105 SemaRef.Diag(Constructor->getLocation(),
2106 diag::err_uninitialized_member_in_ctor)
2107 << (int)Constructor->isImplicit()
2108 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2109 << 0 << Field->getDeclName();
2110 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2111 return true;
2112 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002113
Alexis Hunt8b455182011-05-17 00:19:05 +00002114 if (FieldBaseElementType.isConstQualified()) {
2115 SemaRef.Diag(Constructor->getLocation(),
2116 diag::err_uninitialized_member_in_ctor)
2117 << (int)Constructor->isImplicit()
2118 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2119 << 1 << Field->getDeclName();
2120 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2121 return true;
2122 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002123 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002124
John McCall31168b02011-06-15 23:02:42 +00002125 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2126 FieldBaseElementType->isObjCRetainableType() &&
2127 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2128 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2129 // Instant objects:
2130 // Default-initialize Objective-C pointers to NULL.
2131 CXXMemberInit
2132 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2133 Loc, Loc,
2134 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2135 Loc);
2136 return false;
2137 }
2138
Anders Carlsson3c1db572010-04-23 02:15:47 +00002139 // Nothing to initialize.
2140 CXXMemberInit = 0;
2141 return false;
2142}
John McCallbc83b3f2010-05-20 23:23:51 +00002143
2144namespace {
2145struct BaseAndFieldInfo {
2146 Sema &S;
2147 CXXConstructorDecl *Ctor;
2148 bool AnyErrorsInInits;
2149 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002150 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2151 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002152
2153 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2154 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2155 // FIXME: Handle implicit move constructors.
2156 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2157 IIK = IIK_Copy;
2158 else
2159 IIK = IIK_Default;
2160 }
2161};
2162}
2163
Richard Smith938f40b2011-06-11 17:19:42 +00002164static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
John McCallbc83b3f2010-05-20 23:23:51 +00002165 FieldDecl *Top, FieldDecl *Field) {
2166
Chandler Carruth139e9622010-06-30 02:59:29 +00002167 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002168 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002169 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002170 return false;
2171 }
2172
Richard Smith938f40b2011-06-11 17:19:42 +00002173 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2174 // has a brace-or-equal-initializer, the entity is initialized as specified
2175 // in [dcl.init].
2176 if (Field->hasInClassInitializer()) {
2177 Info.AllToInit.push_back(
2178 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2179 SourceLocation(),
2180 SourceLocation(), 0,
2181 SourceLocation()));
2182 return false;
2183 }
2184
John McCallbc83b3f2010-05-20 23:23:51 +00002185 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2186 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2187 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002188 CXXRecordDecl *FieldClassDecl
2189 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002190
2191 // Even though union members never have non-trivial default
2192 // constructions in C++03, we still build member initializers for aggregate
2193 // record types which can be union members, and C++0x allows non-trivial
2194 // default constructors for union members, so we ensure that only one
2195 // member is initialized for these.
2196 if (FieldClassDecl->isUnion()) {
2197 // First check for an explicit initializer for one field.
2198 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2199 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002200 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002201 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002202
2203 // Once we've initialized a field of an anonymous union, the union
2204 // field in the class is also initialized, so exit immediately.
2205 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002206 } else if ((*FA)->isAnonymousStructOrUnion()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002207 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002208 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002209 }
2210 }
2211
2212 // Fallthrough and construct a default initializer for the union as
2213 // a whole, which can call its default constructor if such a thing exists
2214 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2215 // behavior going forward with C++0x, when anonymous unions there are
2216 // finalized, we should revisit this.
2217 } else {
2218 // For structs, we simply descend through to initialize all members where
2219 // necessary.
2220 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2221 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Richard Smith938f40b2011-06-11 17:19:42 +00002222 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Chandler Carruth139e9622010-06-30 02:59:29 +00002223 return true;
2224 }
2225 }
John McCallbc83b3f2010-05-20 23:23:51 +00002226 }
2227
2228 // Don't try to build an implicit initializer if there were semantic
2229 // errors in any of the initializers (and therefore we might be
2230 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002231 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002232 return false;
2233
Alexis Hunt1d792652011-01-08 20:30:50 +00002234 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002235 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2236 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002237
Francois Pichetd583da02010-12-04 09:14:42 +00002238 if (Init)
2239 Info.AllToInit.push_back(Init);
2240
John McCallbc83b3f2010-05-20 23:23:51 +00002241 return false;
2242}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002243
2244bool
2245Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2246 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002247 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002248 Constructor->setNumCtorInitializers(1);
2249 CXXCtorInitializer **initializer =
2250 new (Context) CXXCtorInitializer*[1];
2251 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2252 Constructor->setCtorInitializers(initializer);
2253
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002254 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2255 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2256 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2257 }
2258
Alexis Hunte2622992011-05-05 00:05:47 +00002259 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002260
Alexis Hunt61bc1732011-05-01 07:04:31 +00002261 return false;
2262}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002263
John McCall1b1a1db2011-06-17 00:18:42 +00002264bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2265 CXXCtorInitializer **Initializers,
2266 unsigned NumInitializers,
2267 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002268 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002269 // Just store the initializers as written, they will be checked during
2270 // instantiation.
2271 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002272 Constructor->setNumCtorInitializers(NumInitializers);
2273 CXXCtorInitializer **baseOrMemberInitializers =
2274 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002275 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002276 NumInitializers * sizeof(CXXCtorInitializer*));
2277 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002278 }
2279
2280 return false;
2281 }
2282
John McCallbc83b3f2010-05-20 23:23:51 +00002283 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002284
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002285 // We need to build the initializer AST according to order of construction
2286 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002287 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002288 if (!ClassDecl)
2289 return true;
2290
Eli Friedman9cf6b592009-11-09 19:20:36 +00002291 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002292
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002293 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002294 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002295
2296 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002297 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002298 else
Francois Pichetd583da02010-12-04 09:14:42 +00002299 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002300 }
2301
Anders Carlsson43c64af2010-04-21 19:52:01 +00002302 // Keep track of the direct virtual bases.
2303 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2304 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2305 E = ClassDecl->bases_end(); I != E; ++I) {
2306 if (I->isVirtual())
2307 DirectVBases.insert(I);
2308 }
2309
Anders Carlssondb0a9652010-04-02 06:26:44 +00002310 // Push virtual bases before others.
2311 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2312 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2313
Alexis Hunt1d792652011-01-08 20:30:50 +00002314 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002315 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2316 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002317 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002318 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002319 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002320 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002321 VBase, IsInheritedVirtualBase,
2322 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002323 HadError = true;
2324 continue;
2325 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002326
John McCallbc83b3f2010-05-20 23:23:51 +00002327 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002328 }
2329 }
Mike Stump11289f42009-09-09 15:08:12 +00002330
John McCallbc83b3f2010-05-20 23:23:51 +00002331 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002332 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2333 E = ClassDecl->bases_end(); Base != E; ++Base) {
2334 // Virtuals are in the virtual base list and already constructed.
2335 if (Base->isVirtual())
2336 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002337
Alexis Hunt1d792652011-01-08 20:30:50 +00002338 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002339 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2340 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002341 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002342 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002343 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002344 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002345 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002346 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002347 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002348 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002349
John McCallbc83b3f2010-05-20 23:23:51 +00002350 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002351 }
2352 }
Mike Stump11289f42009-09-09 15:08:12 +00002353
John McCallbc83b3f2010-05-20 23:23:51 +00002354 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002355 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002356 E = ClassDecl->field_end(); Field != E; ++Field) {
2357 if ((*Field)->getType()->isIncompleteArrayType()) {
2358 assert(ClassDecl->hasFlexibleArrayMember() &&
2359 "Incomplete array type is not valid");
2360 continue;
2361 }
Richard Smith938f40b2011-06-11 17:19:42 +00002362 if (CollectFieldInitializer(*this, Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002363 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002364 }
Mike Stump11289f42009-09-09 15:08:12 +00002365
John McCallbc83b3f2010-05-20 23:23:51 +00002366 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002367 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002368 Constructor->setNumCtorInitializers(NumInitializers);
2369 CXXCtorInitializer **baseOrMemberInitializers =
2370 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002371 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002372 NumInitializers * sizeof(CXXCtorInitializer*));
2373 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002374
John McCalla6309952010-03-16 21:39:52 +00002375 // Constructors implicitly reference the base and member
2376 // destructors.
2377 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2378 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002379 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002380
2381 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002382}
2383
Eli Friedman952c15d2009-07-21 19:28:10 +00002384static void *GetKeyForTopLevelField(FieldDecl *Field) {
2385 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002386 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002387 if (RT->getDecl()->isAnonymousStructOrUnion())
2388 return static_cast<void *>(RT->getDecl());
2389 }
2390 return static_cast<void *>(Field);
2391}
2392
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002393static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002394 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002395}
2396
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002397static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002398 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002399 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002400 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002401
Eli Friedman952c15d2009-07-21 19:28:10 +00002402 // For fields injected into the class via declaration of an anonymous union,
2403 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002404 FieldDecl *Field = Member->getAnyMember();
2405
John McCall23eebd92010-04-10 09:28:51 +00002406 // If the field is a member of an anonymous struct or union, our key
2407 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002408 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002409 if (RD->isAnonymousStructOrUnion()) {
2410 while (true) {
2411 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2412 if (Parent->isAnonymousStructOrUnion())
2413 RD = Parent;
2414 else
2415 break;
2416 }
2417
Anders Carlsson83ac3122010-03-30 16:19:37 +00002418 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002419 }
Mike Stump11289f42009-09-09 15:08:12 +00002420
Anders Carlssona942dcd2010-03-30 15:39:27 +00002421 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002422}
2423
Anders Carlssone857b292010-04-02 03:37:03 +00002424static void
2425DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002426 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002427 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002428 unsigned NumInits) {
2429 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002430 return;
Mike Stump11289f42009-09-09 15:08:12 +00002431
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002432 // Don't check initializers order unless the warning is enabled at the
2433 // location of at least one initializer.
2434 bool ShouldCheckOrder = false;
2435 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002436 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002437 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2438 Init->getSourceLocation())
2439 != Diagnostic::Ignored) {
2440 ShouldCheckOrder = true;
2441 break;
2442 }
2443 }
2444 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002445 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002446
John McCallbb7b6582010-04-10 07:37:23 +00002447 // Build the list of bases and members in the order that they'll
2448 // actually be initialized. The explicit initializers should be in
2449 // this same order but may be missing things.
2450 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002451
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002452 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2453
John McCallbb7b6582010-04-10 07:37:23 +00002454 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002455 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002456 ClassDecl->vbases_begin(),
2457 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002458 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002459
John McCallbb7b6582010-04-10 07:37:23 +00002460 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002461 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002462 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002463 if (Base->isVirtual())
2464 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002465 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
John McCallbb7b6582010-04-10 07:37:23 +00002468 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002469 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2470 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002471 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002472
John McCallbb7b6582010-04-10 07:37:23 +00002473 unsigned NumIdealInits = IdealInitKeys.size();
2474 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002475
Alexis Hunt1d792652011-01-08 20:30:50 +00002476 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002477 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002478 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002479 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002480
2481 // Scan forward to try to find this initializer in the idealized
2482 // initializers list.
2483 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2484 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002485 break;
John McCallbb7b6582010-04-10 07:37:23 +00002486
2487 // If we didn't find this initializer, it must be because we
2488 // scanned past it on a previous iteration. That can only
2489 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002490 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002491 Sema::SemaDiagnosticBuilder D =
2492 SemaRef.Diag(PrevInit->getSourceLocation(),
2493 diag::warn_initializer_out_of_order);
2494
Francois Pichetd583da02010-12-04 09:14:42 +00002495 if (PrevInit->isAnyMemberInitializer())
2496 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002497 else
2498 D << 1 << PrevInit->getBaseClassInfo()->getType();
2499
Francois Pichetd583da02010-12-04 09:14:42 +00002500 if (Init->isAnyMemberInitializer())
2501 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002502 else
2503 D << 1 << Init->getBaseClassInfo()->getType();
2504
2505 // Move back to the initializer's location in the ideal list.
2506 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2507 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002508 break;
John McCallbb7b6582010-04-10 07:37:23 +00002509
2510 assert(IdealIndex != NumIdealInits &&
2511 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002512 }
John McCallbb7b6582010-04-10 07:37:23 +00002513
2514 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002515 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002516}
2517
John McCall23eebd92010-04-10 09:28:51 +00002518namespace {
2519bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002520 CXXCtorInitializer *Init,
2521 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002522 if (!PrevInit) {
2523 PrevInit = Init;
2524 return false;
2525 }
2526
2527 if (FieldDecl *Field = Init->getMember())
2528 S.Diag(Init->getSourceLocation(),
2529 diag::err_multiple_mem_initialization)
2530 << Field->getDeclName()
2531 << Init->getSourceRange();
2532 else {
John McCall424cec92011-01-19 06:33:43 +00002533 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002534 assert(BaseClass && "neither field nor base");
2535 S.Diag(Init->getSourceLocation(),
2536 diag::err_multiple_base_initialization)
2537 << QualType(BaseClass, 0)
2538 << Init->getSourceRange();
2539 }
2540 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2541 << 0 << PrevInit->getSourceRange();
2542
2543 return true;
2544}
2545
Alexis Hunt1d792652011-01-08 20:30:50 +00002546typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002547typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2548
2549bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002550 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002551 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002552 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002553 RecordDecl *Parent = Field->getParent();
2554 if (!Parent->isAnonymousStructOrUnion())
2555 return false;
2556
2557 NamedDecl *Child = Field;
2558 do {
2559 if (Parent->isUnion()) {
2560 UnionEntry &En = Unions[Parent];
2561 if (En.first && En.first != Child) {
2562 S.Diag(Init->getSourceLocation(),
2563 diag::err_multiple_mem_union_initialization)
2564 << Field->getDeclName()
2565 << Init->getSourceRange();
2566 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2567 << 0 << En.second->getSourceRange();
2568 return true;
2569 } else if (!En.first) {
2570 En.first = Child;
2571 En.second = Init;
2572 }
2573 }
2574
2575 Child = Parent;
2576 Parent = cast<RecordDecl>(Parent->getDeclContext());
2577 } while (Parent->isAnonymousStructOrUnion());
2578
2579 return false;
2580}
2581}
2582
Anders Carlssone857b292010-04-02 03:37:03 +00002583/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002584void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002585 SourceLocation ColonLoc,
2586 MemInitTy **meminits, unsigned NumMemInits,
2587 bool AnyErrors) {
2588 if (!ConstructorDecl)
2589 return;
2590
2591 AdjustDeclIfTemplate(ConstructorDecl);
2592
2593 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002594 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002595
2596 if (!Constructor) {
2597 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2598 return;
2599 }
2600
Alexis Hunt1d792652011-01-08 20:30:50 +00002601 CXXCtorInitializer **MemInits =
2602 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002603
2604 // Mapping for the duplicate initializers check.
2605 // For member initializers, this is keyed with a FieldDecl*.
2606 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002607 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002608
2609 // Mapping for the inconsistent anonymous-union initializers check.
2610 RedundantUnionMap MemberUnions;
2611
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002612 bool HadError = false;
2613 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002614 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002615
Abramo Bagnara341d7832010-05-26 18:09:23 +00002616 // Set the source order index.
2617 Init->setSourceOrder(i);
2618
Francois Pichetd583da02010-12-04 09:14:42 +00002619 if (Init->isAnyMemberInitializer()) {
2620 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002621 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2622 CheckRedundantUnionInit(*this, Init, MemberUnions))
2623 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002624 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002625 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2626 if (CheckRedundantInit(*this, Init, Members[Key]))
2627 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002628 } else {
2629 assert(Init->isDelegatingInitializer());
2630 // This must be the only initializer
2631 if (i != 0 || NumMemInits > 1) {
2632 Diag(MemInits[0]->getSourceLocation(),
2633 diag::err_delegating_initializer_alone)
2634 << MemInits[0]->getSourceRange();
2635 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002636 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002637 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002638 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002639 // Return immediately as the initializer is set.
2640 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002641 }
Anders Carlssone857b292010-04-02 03:37:03 +00002642 }
2643
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002644 if (HadError)
2645 return;
2646
Anders Carlssone857b292010-04-02 03:37:03 +00002647 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002648
Alexis Hunt1d792652011-01-08 20:30:50 +00002649 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002650}
2651
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002652void
John McCalla6309952010-03-16 21:39:52 +00002653Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2654 CXXRecordDecl *ClassDecl) {
2655 // Ignore dependent contexts.
2656 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002657 return;
John McCall1064d7e2010-03-16 05:22:47 +00002658
2659 // FIXME: all the access-control diagnostics are positioned on the
2660 // field/base declaration. That's probably good; that said, the
2661 // user might reasonably want to know why the destructor is being
2662 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002663
Anders Carlssondee9a302009-11-17 04:44:12 +00002664 // Non-static data members.
2665 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2666 E = ClassDecl->field_end(); I != E; ++I) {
2667 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002668 if (Field->isInvalidDecl())
2669 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002670 QualType FieldType = Context.getBaseElementType(Field->getType());
2671
2672 const RecordType* RT = FieldType->getAs<RecordType>();
2673 if (!RT)
2674 continue;
2675
2676 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002677 if (FieldClassDecl->isInvalidDecl())
2678 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002679 if (FieldClassDecl->hasTrivialDestructor())
2680 continue;
2681
Douglas Gregore71edda2010-07-01 22:47:18 +00002682 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002683 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002684 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002685 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002686 << Field->getDeclName()
2687 << FieldType);
2688
John McCalla6309952010-03-16 21:39:52 +00002689 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002690 }
2691
John McCall1064d7e2010-03-16 05:22:47 +00002692 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2693
Anders Carlssondee9a302009-11-17 04:44:12 +00002694 // Bases.
2695 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2696 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002697 // Bases are always records in a well-formed non-dependent class.
2698 const RecordType *RT = Base->getType()->getAs<RecordType>();
2699
2700 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002701 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002702 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002703
John McCall1064d7e2010-03-16 05:22:47 +00002704 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002705 // If our base class is invalid, we probably can't get its dtor anyway.
2706 if (BaseClassDecl->isInvalidDecl())
2707 continue;
2708 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002709 if (BaseClassDecl->hasTrivialDestructor())
2710 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002711
Douglas Gregore71edda2010-07-01 22:47:18 +00002712 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002713 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002714
2715 // FIXME: caret should be on the start of the class name
2716 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002717 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002718 << Base->getType()
2719 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002720
John McCalla6309952010-03-16 21:39:52 +00002721 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002722 }
2723
2724 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002725 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2726 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002727
2728 // Bases are always records in a well-formed non-dependent class.
2729 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2730
2731 // Ignore direct virtual bases.
2732 if (DirectVirtualBases.count(RT))
2733 continue;
2734
John McCall1064d7e2010-03-16 05:22:47 +00002735 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002736 // If our base class is invalid, we probably can't get its dtor anyway.
2737 if (BaseClassDecl->isInvalidDecl())
2738 continue;
2739 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002740 if (BaseClassDecl->hasTrivialDestructor())
2741 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002742
Douglas Gregore71edda2010-07-01 22:47:18 +00002743 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002744 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002745 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002746 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002747 << VBase->getType());
2748
John McCalla6309952010-03-16 21:39:52 +00002749 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002750 }
2751}
2752
John McCall48871652010-08-21 09:40:31 +00002753void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002754 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002755 return;
Mike Stump11289f42009-09-09 15:08:12 +00002756
Mike Stump11289f42009-09-09 15:08:12 +00002757 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002758 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002759 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002760}
2761
Mike Stump11289f42009-09-09 15:08:12 +00002762bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002763 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002764 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002765 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002766 else
John McCall02db245d2010-08-18 09:41:07 +00002767 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002768}
2769
Anders Carlssoneabf7702009-08-27 00:13:57 +00002770bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002771 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002772 if (!getLangOptions().CPlusPlus)
2773 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002774
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002775 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002776 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002777
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002778 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002779 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002780 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002781 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002782
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002783 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002784 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002785 }
Mike Stump11289f42009-09-09 15:08:12 +00002786
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002787 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002788 if (!RT)
2789 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002790
John McCall67da35c2010-02-04 22:26:26 +00002791 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002792
John McCall02db245d2010-08-18 09:41:07 +00002793 // We can't answer whether something is abstract until it has a
2794 // definition. If it's currently being defined, we'll walk back
2795 // over all the declarations when we have a full definition.
2796 const CXXRecordDecl *Def = RD->getDefinition();
2797 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002798 return false;
2799
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002800 if (!RD->isAbstract())
2801 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002802
Anders Carlssoneabf7702009-08-27 00:13:57 +00002803 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002804 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002805
John McCall02db245d2010-08-18 09:41:07 +00002806 return true;
2807}
2808
2809void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2810 // Check if we've already emitted the list of pure virtual functions
2811 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002812 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002813 return;
Mike Stump11289f42009-09-09 15:08:12 +00002814
Douglas Gregor4165bd62010-03-23 23:47:56 +00002815 CXXFinalOverriderMap FinalOverriders;
2816 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002817
Anders Carlssona2f74f32010-06-03 01:00:02 +00002818 // Keep a set of seen pure methods so we won't diagnose the same method
2819 // more than once.
2820 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2821
Douglas Gregor4165bd62010-03-23 23:47:56 +00002822 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2823 MEnd = FinalOverriders.end();
2824 M != MEnd;
2825 ++M) {
2826 for (OverridingMethods::iterator SO = M->second.begin(),
2827 SOEnd = M->second.end();
2828 SO != SOEnd; ++SO) {
2829 // C++ [class.abstract]p4:
2830 // A class is abstract if it contains or inherits at least one
2831 // pure virtual function for which the final overrider is pure
2832 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002833
Douglas Gregor4165bd62010-03-23 23:47:56 +00002834 //
2835 if (SO->second.size() != 1)
2836 continue;
2837
2838 if (!SO->second.front().Method->isPure())
2839 continue;
2840
Anders Carlssona2f74f32010-06-03 01:00:02 +00002841 if (!SeenPureMethods.insert(SO->second.front().Method))
2842 continue;
2843
Douglas Gregor4165bd62010-03-23 23:47:56 +00002844 Diag(SO->second.front().Method->getLocation(),
2845 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002846 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002847 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002848 }
2849
2850 if (!PureVirtualClassDiagSet)
2851 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2852 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002853}
2854
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002855namespace {
John McCall02db245d2010-08-18 09:41:07 +00002856struct AbstractUsageInfo {
2857 Sema &S;
2858 CXXRecordDecl *Record;
2859 CanQualType AbstractType;
2860 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002861
John McCall02db245d2010-08-18 09:41:07 +00002862 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2863 : S(S), Record(Record),
2864 AbstractType(S.Context.getCanonicalType(
2865 S.Context.getTypeDeclType(Record))),
2866 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002867
John McCall02db245d2010-08-18 09:41:07 +00002868 void DiagnoseAbstractType() {
2869 if (Invalid) return;
2870 S.DiagnoseAbstractType(Record);
2871 Invalid = true;
2872 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002873
John McCall02db245d2010-08-18 09:41:07 +00002874 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2875};
2876
2877struct CheckAbstractUsage {
2878 AbstractUsageInfo &Info;
2879 const NamedDecl *Ctx;
2880
2881 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2882 : Info(Info), Ctx(Ctx) {}
2883
2884 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2885 switch (TL.getTypeLocClass()) {
2886#define ABSTRACT_TYPELOC(CLASS, PARENT)
2887#define TYPELOC(CLASS, PARENT) \
2888 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2889#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002890 }
John McCall02db245d2010-08-18 09:41:07 +00002891 }
Mike Stump11289f42009-09-09 15:08:12 +00002892
John McCall02db245d2010-08-18 09:41:07 +00002893 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2894 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2895 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002896 if (!TL.getArg(I))
2897 continue;
2898
John McCall02db245d2010-08-18 09:41:07 +00002899 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2900 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002901 }
John McCall02db245d2010-08-18 09:41:07 +00002902 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002903
John McCall02db245d2010-08-18 09:41:07 +00002904 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2905 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2906 }
Mike Stump11289f42009-09-09 15:08:12 +00002907
John McCall02db245d2010-08-18 09:41:07 +00002908 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2909 // Visit the type parameters from a permissive context.
2910 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2911 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2912 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2913 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2914 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2915 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002916 }
John McCall02db245d2010-08-18 09:41:07 +00002917 }
Mike Stump11289f42009-09-09 15:08:12 +00002918
John McCall02db245d2010-08-18 09:41:07 +00002919 // Visit pointee types from a permissive context.
2920#define CheckPolymorphic(Type) \
2921 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2922 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2923 }
2924 CheckPolymorphic(PointerTypeLoc)
2925 CheckPolymorphic(ReferenceTypeLoc)
2926 CheckPolymorphic(MemberPointerTypeLoc)
2927 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002928
John McCall02db245d2010-08-18 09:41:07 +00002929 /// Handle all the types we haven't given a more specific
2930 /// implementation for above.
2931 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2932 // Every other kind of type that we haven't called out already
2933 // that has an inner type is either (1) sugar or (2) contains that
2934 // inner type in some way as a subobject.
2935 if (TypeLoc Next = TL.getNextTypeLoc())
2936 return Visit(Next, Sel);
2937
2938 // If there's no inner type and we're in a permissive context,
2939 // don't diagnose.
2940 if (Sel == Sema::AbstractNone) return;
2941
2942 // Check whether the type matches the abstract type.
2943 QualType T = TL.getType();
2944 if (T->isArrayType()) {
2945 Sel = Sema::AbstractArrayType;
2946 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002947 }
John McCall02db245d2010-08-18 09:41:07 +00002948 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2949 if (CT != Info.AbstractType) return;
2950
2951 // It matched; do some magic.
2952 if (Sel == Sema::AbstractArrayType) {
2953 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2954 << T << TL.getSourceRange();
2955 } else {
2956 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2957 << Sel << T << TL.getSourceRange();
2958 }
2959 Info.DiagnoseAbstractType();
2960 }
2961};
2962
2963void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2964 Sema::AbstractDiagSelID Sel) {
2965 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2966}
2967
2968}
2969
2970/// Check for invalid uses of an abstract type in a method declaration.
2971static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2972 CXXMethodDecl *MD) {
2973 // No need to do the check on definitions, which require that
2974 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002975 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00002976 return;
2977
2978 // For safety's sake, just ignore it if we don't have type source
2979 // information. This should never happen for non-implicit methods,
2980 // but...
2981 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2982 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2983}
2984
2985/// Check for invalid uses of an abstract type within a class definition.
2986static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2987 CXXRecordDecl *RD) {
2988 for (CXXRecordDecl::decl_iterator
2989 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2990 Decl *D = *I;
2991 if (D->isImplicit()) continue;
2992
2993 // Methods and method templates.
2994 if (isa<CXXMethodDecl>(D)) {
2995 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2996 } else if (isa<FunctionTemplateDecl>(D)) {
2997 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2998 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2999
3000 // Fields and static variables.
3001 } else if (isa<FieldDecl>(D)) {
3002 FieldDecl *FD = cast<FieldDecl>(D);
3003 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3004 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3005 } else if (isa<VarDecl>(D)) {
3006 VarDecl *VD = cast<VarDecl>(D);
3007 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3008 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3009
3010 // Nested classes and class templates.
3011 } else if (isa<CXXRecordDecl>(D)) {
3012 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3013 } else if (isa<ClassTemplateDecl>(D)) {
3014 CheckAbstractClassUsage(Info,
3015 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3016 }
3017 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003018}
3019
Douglas Gregorc99f1552009-12-03 18:33:45 +00003020/// \brief Perform semantic checks on a class definition that has been
3021/// completing, introducing implicitly-declared members, checking for
3022/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003023void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003024 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003025 return;
3026
John McCall02db245d2010-08-18 09:41:07 +00003027 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3028 AbstractUsageInfo Info(*this, Record);
3029 CheckAbstractClassUsage(Info, Record);
3030 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003031
3032 // If this is not an aggregate type and has no user-declared constructor,
3033 // complain about any non-static data members of reference or const scalar
3034 // type, since they will never get initializers.
3035 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3036 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3037 bool Complained = false;
3038 for (RecordDecl::field_iterator F = Record->field_begin(),
3039 FEnd = Record->field_end();
3040 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003041 if (F->hasInClassInitializer())
3042 continue;
3043
Douglas Gregor454a5b62010-04-15 00:00:53 +00003044 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003045 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003046 if (!Complained) {
3047 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3048 << Record->getTagKind() << Record;
3049 Complained = true;
3050 }
3051
3052 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3053 << F->getType()->isReferenceType()
3054 << F->getDeclName();
3055 }
3056 }
3057 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003058
Anders Carlssone771e762011-01-25 18:08:22 +00003059 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003060 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003061
3062 if (Record->getIdentifier()) {
3063 // C++ [class.mem]p13:
3064 // If T is the name of a class, then each of the following shall have a
3065 // name different from T:
3066 // - every member of every anonymous union that is a member of class T.
3067 //
3068 // C++ [class.mem]p14:
3069 // In addition, if class T has a user-declared constructor (12.1), every
3070 // non-static data member of class T shall have a name different from T.
3071 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003072 R.first != R.second; ++R.first) {
3073 NamedDecl *D = *R.first;
3074 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3075 isa<IndirectFieldDecl>(D)) {
3076 Diag(D->getLocation(), diag::err_member_name_of_class)
3077 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003078 break;
3079 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003080 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003081 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003082
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003083 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003084 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003085 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003086 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003087 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3088 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3089 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003090
3091 // See if a method overloads virtual methods in a base
3092 /// class without overriding any.
3093 if (!Record->isDependentType()) {
3094 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3095 MEnd = Record->method_end();
3096 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003097 if (!(*M)->isStatic())
3098 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003099 }
3100 }
Sebastian Redl08905022011-02-05 19:23:19 +00003101
3102 // Declare inherited constructors. We do this eagerly here because:
3103 // - The standard requires an eager diagnostic for conflicting inherited
3104 // constructors from different classes.
3105 // - The lazy declaration of the other implicit constructors is so as to not
3106 // waste space and performance on classes that are not meant to be
3107 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3108 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003109 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003110
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003111 if (!Record->isDependentType())
3112 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003113}
3114
3115void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003116 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3117 ME = Record->method_end();
3118 MI != ME; ++MI) {
3119 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3120 switch (getSpecialMember(*MI)) {
3121 case CXXDefaultConstructor:
3122 CheckExplicitlyDefaultedDefaultConstructor(
3123 cast<CXXConstructorDecl>(*MI));
3124 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003125
Alexis Huntf91729462011-05-12 22:46:25 +00003126 case CXXDestructor:
3127 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3128 break;
3129
3130 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003131 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3132 break;
3133
Alexis Huntf91729462011-05-12 22:46:25 +00003134 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003135 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003136 break;
3137
Alexis Hunt119c10e2011-05-25 23:16:36 +00003138 case CXXMoveConstructor:
3139 case CXXMoveAssignment:
3140 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3141 break;
3142
Alexis Huntf91729462011-05-12 22:46:25 +00003143 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00003144 // FIXME: Do moves once they exist
Alexis Huntf91729462011-05-12 22:46:25 +00003145 llvm_unreachable("non-special member explicitly defaulted!");
3146 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003147 }
3148 }
3149
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003150}
3151
3152void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3153 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3154
3155 // Whether this was the first-declared instance of the constructor.
3156 // This affects whether we implicitly add an exception spec (and, eventually,
3157 // constexpr). It is also ill-formed to explicitly default a constructor such
3158 // that it would be deleted. (C++0x [decl.fct.def.default])
3159 bool First = CD == CD->getCanonicalDecl();
3160
Alexis Hunt913820d2011-05-13 06:10:58 +00003161 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003162 if (CD->getNumParams() != 0) {
3163 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3164 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003165 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003166 }
3167
3168 ImplicitExceptionSpecification Spec
3169 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3170 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003171 if (EPI.ExceptionSpecType == EST_Delayed) {
3172 // Exception specification depends on some deferred part of the class. We'll
3173 // try again when the class's definition has been fully processed.
3174 return;
3175 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003176 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3177 *ExceptionType = Context.getFunctionType(
3178 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3179
3180 if (CtorType->hasExceptionSpec()) {
3181 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003182 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003183 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003184 PDiag(),
3185 ExceptionType, SourceLocation(),
3186 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003187 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003188 }
3189 } else if (First) {
3190 // We set the declaration to have the computed exception spec here.
3191 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003192 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003193 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3194 }
Alexis Huntb3153022011-05-12 03:51:48 +00003195
Alexis Hunt913820d2011-05-13 06:10:58 +00003196 if (HadError) {
3197 CD->setInvalidDecl();
3198 return;
3199 }
3200
Alexis Huntb3153022011-05-12 03:51:48 +00003201 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003202 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003203 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003204 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003205 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003206 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003207 CD->setInvalidDecl();
3208 }
3209 }
3210}
3211
3212void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3213 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3214
3215 // Whether this was the first-declared instance of the constructor.
3216 bool First = CD == CD->getCanonicalDecl();
3217
3218 bool HadError = false;
3219 if (CD->getNumParams() != 1) {
3220 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3221 << CD->getSourceRange();
3222 HadError = true;
3223 }
3224
3225 ImplicitExceptionSpecification Spec(Context);
3226 bool Const;
3227 llvm::tie(Spec, Const) =
3228 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3229
3230 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3231 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3232 *ExceptionType = Context.getFunctionType(
3233 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3234
3235 // Check for parameter type matching.
3236 // This is a copy ctor so we know it's a cv-qualified reference to T.
3237 QualType ArgType = CtorType->getArgType(0);
3238 if (ArgType->getPointeeType().isVolatileQualified()) {
3239 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3240 HadError = true;
3241 }
3242 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3243 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3244 HadError = true;
3245 }
3246
3247 if (CtorType->hasExceptionSpec()) {
3248 if (CheckEquivalentExceptionSpec(
3249 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003250 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003251 PDiag(),
3252 ExceptionType, SourceLocation(),
3253 CtorType, CD->getLocation())) {
3254 HadError = true;
3255 }
3256 } else if (First) {
3257 // We set the declaration to have the computed exception spec here.
3258 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003259 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003260 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3261 }
3262
3263 if (HadError) {
3264 CD->setInvalidDecl();
3265 return;
3266 }
3267
3268 if (ShouldDeleteCopyConstructor(CD)) {
3269 if (First) {
3270 CD->setDeletedAsWritten();
3271 } else {
3272 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003273 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003274 CD->setInvalidDecl();
3275 }
Alexis Huntb3153022011-05-12 03:51:48 +00003276 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003277}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003278
Alexis Huntc9a55732011-05-14 05:23:28 +00003279void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3280 assert(MD->isExplicitlyDefaulted());
3281
3282 // Whether this was the first-declared instance of the operator
3283 bool First = MD == MD->getCanonicalDecl();
3284
3285 bool HadError = false;
3286 if (MD->getNumParams() != 1) {
3287 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3288 << MD->getSourceRange();
3289 HadError = true;
3290 }
3291
3292 QualType ReturnType =
3293 MD->getType()->getAs<FunctionType>()->getResultType();
3294 if (!ReturnType->isLValueReferenceType() ||
3295 !Context.hasSameType(
3296 Context.getCanonicalType(ReturnType->getPointeeType()),
3297 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3298 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3299 HadError = true;
3300 }
3301
3302 ImplicitExceptionSpecification Spec(Context);
3303 bool Const;
3304 llvm::tie(Spec, Const) =
3305 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3306
3307 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3308 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3309 *ExceptionType = Context.getFunctionType(
3310 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3311
Alexis Huntc9a55732011-05-14 05:23:28 +00003312 QualType ArgType = OperType->getArgType(0);
Alexis Hunt604aeb32011-05-17 20:44:43 +00003313 if (!ArgType->isReferenceType()) {
3314 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003315 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003316 } else {
3317 if (ArgType->getPointeeType().isVolatileQualified()) {
3318 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3319 HadError = true;
3320 }
3321 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3322 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3323 HadError = true;
3324 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003325 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003326
Alexis Huntc9a55732011-05-14 05:23:28 +00003327 if (OperType->getTypeQuals()) {
3328 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3329 HadError = true;
3330 }
3331
3332 if (OperType->hasExceptionSpec()) {
3333 if (CheckEquivalentExceptionSpec(
3334 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003335 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003336 PDiag(),
3337 ExceptionType, SourceLocation(),
3338 OperType, MD->getLocation())) {
3339 HadError = true;
3340 }
3341 } else if (First) {
3342 // We set the declaration to have the computed exception spec here.
3343 // We duplicate the one parameter type.
3344 EPI.RefQualifier = OperType->getRefQualifier();
3345 EPI.ExtInfo = OperType->getExtInfo();
3346 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3347 }
3348
3349 if (HadError) {
3350 MD->setInvalidDecl();
3351 return;
3352 }
3353
3354 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3355 if (First) {
3356 MD->setDeletedAsWritten();
3357 } else {
3358 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003359 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003360 MD->setInvalidDecl();
3361 }
3362 }
3363}
3364
Alexis Huntf91729462011-05-12 22:46:25 +00003365void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3366 assert(DD->isExplicitlyDefaulted());
3367
3368 // Whether this was the first-declared instance of the destructor.
3369 bool First = DD == DD->getCanonicalDecl();
3370
3371 ImplicitExceptionSpecification Spec
3372 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3373 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3374 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3375 *ExceptionType = Context.getFunctionType(
3376 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3377
3378 if (DtorType->hasExceptionSpec()) {
3379 if (CheckEquivalentExceptionSpec(
3380 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003381 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00003382 PDiag(),
3383 ExceptionType, SourceLocation(),
3384 DtorType, DD->getLocation())) {
3385 DD->setInvalidDecl();
3386 return;
3387 }
3388 } else if (First) {
3389 // We set the declaration to have the computed exception spec here.
3390 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003391 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003392 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3393 }
3394
3395 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003396 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003397 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003398 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003399 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003400 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003401 DD->setInvalidDecl();
3402 }
Alexis Huntf91729462011-05-12 22:46:25 +00003403 }
Alexis Huntf91729462011-05-12 22:46:25 +00003404}
3405
Alexis Huntea6f0322011-05-11 22:34:38 +00003406bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3407 CXXRecordDecl *RD = CD->getParent();
3408 assert(!RD->isDependentType() && "do deletion after instantiation");
3409 if (!LangOpts.CPlusPlus0x)
3410 return false;
3411
Alexis Hunte77a28f2011-05-18 03:41:58 +00003412 SourceLocation Loc = CD->getLocation();
3413
Alexis Huntea6f0322011-05-11 22:34:38 +00003414 // Do access control from the constructor
3415 ContextRAII CtorContext(*this, CD);
3416
3417 bool Union = RD->isUnion();
3418 bool AllConst = true;
3419
Alexis Huntea6f0322011-05-11 22:34:38 +00003420 // We do this because we should never actually use an anonymous
3421 // union's constructor.
3422 if (Union && RD->isAnonymousStructOrUnion())
3423 return false;
3424
3425 // FIXME: We should put some diagnostic logic right into this function.
3426
3427 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00003428 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00003429
3430 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3431 BE = RD->bases_end();
3432 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003433 // We'll handle this one later
3434 if (BI->isVirtual())
3435 continue;
3436
Alexis Huntea6f0322011-05-11 22:34:38 +00003437 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3438 assert(BaseDecl && "base isn't a CXXRecordDecl");
3439
3440 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00003441 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00003442 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3443 if (BaseDtor->isDeleted())
3444 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003445 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003446 AR_accessible)
3447 return true;
3448
Alexis Huntea6f0322011-05-11 22:34:38 +00003449 // -- any [direct base class either] has no default constructor or
3450 // overload resolution as applied to [its] default constructor
3451 // results in an ambiguity or in a function that is deleted or
3452 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003453 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3454 if (!BaseDefault || BaseDefault->isDeleted())
3455 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003456
Alexis Hunteef8ee02011-06-10 03:50:41 +00003457 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3458 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003459 return true;
3460 }
3461
3462 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3463 BE = RD->vbases_end();
3464 BI != BE; ++BI) {
3465 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3466 assert(BaseDecl && "base isn't a CXXRecordDecl");
3467
3468 // -- any [virtual base class] has a type with a destructor that is
3469 // delete or inaccessible from the defaulted default constructor
3470 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3471 if (BaseDtor->isDeleted())
3472 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003473 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003474 AR_accessible)
3475 return true;
3476
3477 // -- any [virtual base class either] has no default constructor or
3478 // overload resolution as applied to [its] default constructor
3479 // results in an ambiguity or in a function that is deleted or
3480 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003481 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3482 if (!BaseDefault || BaseDefault->isDeleted())
3483 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003484
Alexis Hunteef8ee02011-06-10 03:50:41 +00003485 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3486 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003487 return true;
3488 }
3489
3490 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3491 FE = RD->field_end();
3492 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00003493 if (FI->isInvalidDecl())
3494 continue;
3495
Alexis Huntea6f0322011-05-11 22:34:38 +00003496 QualType FieldType = Context.getBaseElementType(FI->getType());
3497 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00003498
Alexis Huntea6f0322011-05-11 22:34:38 +00003499 // -- any non-static data member with no brace-or-equal-initializer is of
3500 // reference type
Richard Smith938f40b2011-06-11 17:19:42 +00003501 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Alexis Huntea6f0322011-05-11 22:34:38 +00003502 return true;
3503
3504 // -- X is a union and all its variant members are of const-qualified type
3505 // (or array thereof)
3506 if (Union && !FieldType.isConstQualified())
3507 AllConst = false;
3508
3509 if (FieldRecord) {
3510 // -- X is a union-like class that has a variant member with a non-trivial
3511 // default constructor
3512 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3513 return true;
3514
3515 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3516 if (FieldDtor->isDeleted())
3517 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003518 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003519 AR_accessible)
3520 return true;
3521
3522 // -- any non-variant non-static data member of const-qualified type (or
3523 // array thereof) with no brace-or-equal-initializer does not have a
3524 // user-provided default constructor
3525 if (FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003526 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00003527 !FieldRecord->hasUserProvidedDefaultConstructor())
3528 return true;
3529
3530 if (!Union && FieldRecord->isUnion() &&
3531 FieldRecord->isAnonymousStructOrUnion()) {
3532 // We're okay to reuse AllConst here since we only care about the
3533 // value otherwise if we're in a union.
3534 AllConst = true;
3535
3536 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3537 UE = FieldRecord->field_end();
3538 UI != UE; ++UI) {
3539 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3540 CXXRecordDecl *UnionFieldRecord =
3541 UnionFieldType->getAsCXXRecordDecl();
3542
3543 if (!UnionFieldType.isConstQualified())
3544 AllConst = false;
3545
3546 if (UnionFieldRecord &&
3547 !UnionFieldRecord->hasTrivialDefaultConstructor())
3548 return true;
3549 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003550
Alexis Huntea6f0322011-05-11 22:34:38 +00003551 if (AllConst)
3552 return true;
3553
3554 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003555 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003556 continue;
3557 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003558
Richard Smith938f40b2011-06-11 17:19:42 +00003559 // -- any non-static data member with no brace-or-equal-initializer has
3560 // class type M (or array thereof) and either M has no default
3561 // constructor or overload resolution as applied to M's default
3562 // constructor results in an ambiguity or in a function that is deleted
3563 // or inaccessible from the defaulted default constructor.
3564 if (!FI->hasInClassInitializer()) {
3565 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3566 if (!FieldDefault || FieldDefault->isDeleted())
3567 return true;
3568 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3569 PDiag()) != AR_accessible)
3570 return true;
3571 }
3572 } else if (!Union && FieldType.isConstQualified() &&
3573 !FI->hasInClassInitializer()) {
Alexis Hunta671bca2011-05-20 21:43:47 +00003574 // -- any non-variant non-static data member of const-qualified type (or
3575 // array thereof) with no brace-or-equal-initializer does not have a
3576 // user-provided default constructor
3577 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003578 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003579 }
3580
3581 if (Union && AllConst)
3582 return true;
3583
3584 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003585}
3586
Alexis Hunt913820d2011-05-13 06:10:58 +00003587bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003588 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003589 assert(!RD->isDependentType() && "do deletion after instantiation");
3590 if (!LangOpts.CPlusPlus0x)
3591 return false;
3592
Alexis Hunte77a28f2011-05-18 03:41:58 +00003593 SourceLocation Loc = CD->getLocation();
3594
Alexis Hunt913820d2011-05-13 06:10:58 +00003595 // Do access control from the constructor
3596 ContextRAII CtorContext(*this, CD);
3597
Alexis Hunt899bd442011-06-10 04:44:37 +00003598 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003599
Alexis Huntc9a55732011-05-14 05:23:28 +00003600 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3601 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00003602 unsigned ArgQuals =
3603 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3604 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00003605
3606 // We do this because we should never actually use an anonymous
3607 // union's constructor.
3608 if (Union && RD->isAnonymousStructOrUnion())
3609 return false;
3610
3611 // FIXME: We should put some diagnostic logic right into this function.
3612
3613 // C++0x [class.copy]/11
3614 // A defaulted [copy] constructor for class X is defined as delete if X has:
3615
3616 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3617 BE = RD->bases_end();
3618 BI != BE; ++BI) {
3619 // We'll handle this one later
3620 if (BI->isVirtual())
3621 continue;
3622
3623 QualType BaseType = BI->getType();
3624 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3625 assert(BaseDecl && "base isn't a CXXRecordDecl");
3626
3627 // -- any [direct base class] of a type with a destructor that is deleted or
3628 // inaccessible from the defaulted constructor
3629 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3630 if (BaseDtor->isDeleted())
3631 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003632 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003633 AR_accessible)
3634 return true;
3635
3636 // -- a [direct base class] B that cannot be [copied] because overload
3637 // resolution, as applied to B's [copy] constructor, results in an
3638 // ambiguity or a function that is deleted or inaccessible from the
3639 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003640 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003641 if (!BaseCtor || BaseCtor->isDeleted())
3642 return true;
3643 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3644 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003645 return true;
3646 }
3647
3648 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3649 BE = RD->vbases_end();
3650 BI != BE; ++BI) {
3651 QualType BaseType = BI->getType();
3652 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3653 assert(BaseDecl && "base isn't a CXXRecordDecl");
3654
Alexis Hunteef8ee02011-06-10 03:50:41 +00003655 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00003656 // inaccessible from the defaulted constructor
3657 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3658 if (BaseDtor->isDeleted())
3659 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003660 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003661 AR_accessible)
3662 return true;
3663
3664 // -- a [virtual base class] B that cannot be [copied] because overload
3665 // resolution, as applied to B's [copy] constructor, results in an
3666 // ambiguity or a function that is deleted or inaccessible from the
3667 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003668 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003669 if (!BaseCtor || BaseCtor->isDeleted())
3670 return true;
3671 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3672 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003673 return true;
3674 }
3675
3676 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3677 FE = RD->field_end();
3678 FI != FE; ++FI) {
3679 QualType FieldType = Context.getBaseElementType(FI->getType());
3680
3681 // -- for a copy constructor, a non-static data member of rvalue reference
3682 // type
3683 if (FieldType->isRValueReferenceType())
3684 return true;
3685
3686 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3687
3688 if (FieldRecord) {
3689 // This is an anonymous union
3690 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3691 // Anonymous unions inside unions do not variant members create
3692 if (!Union) {
3693 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3694 UE = FieldRecord->field_end();
3695 UI != UE; ++UI) {
3696 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3697 CXXRecordDecl *UnionFieldRecord =
3698 UnionFieldType->getAsCXXRecordDecl();
3699
3700 // -- a variant member with a non-trivial [copy] constructor and X
3701 // is a union-like class
3702 if (UnionFieldRecord &&
3703 !UnionFieldRecord->hasTrivialCopyConstructor())
3704 return true;
3705 }
3706 }
3707
3708 // Don't try to initalize an anonymous union
3709 continue;
3710 } else {
3711 // -- a variant member with a non-trivial [copy] constructor and X is a
3712 // union-like class
3713 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3714 return true;
3715
3716 // -- any [non-static data member] of a type with a destructor that is
3717 // deleted or inaccessible from the defaulted constructor
3718 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3719 if (FieldDtor->isDeleted())
3720 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003721 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003722 AR_accessible)
3723 return true;
3724 }
Alexis Hunt899bd442011-06-10 04:44:37 +00003725
3726 // -- a [non-static data member of class type (or array thereof)] B that
3727 // cannot be [copied] because overload resolution, as applied to B's
3728 // [copy] constructor, results in an ambiguity or a function that is
3729 // deleted or inaccessible from the defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003730 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3731 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003732 if (!FieldCtor || FieldCtor->isDeleted())
3733 return true;
3734 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3735 PDiag()) != AR_accessible)
3736 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00003737 }
Alexis Hunt913820d2011-05-13 06:10:58 +00003738 }
3739
3740 return false;
3741}
3742
Alexis Huntb2f27802011-05-14 05:23:24 +00003743bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3744 CXXRecordDecl *RD = MD->getParent();
3745 assert(!RD->isDependentType() && "do deletion after instantiation");
3746 if (!LangOpts.CPlusPlus0x)
3747 return false;
3748
Alexis Hunte77a28f2011-05-18 03:41:58 +00003749 SourceLocation Loc = MD->getLocation();
3750
Alexis Huntb2f27802011-05-14 05:23:24 +00003751 // Do access control from the constructor
3752 ContextRAII MethodContext(*this, MD);
3753
3754 bool Union = RD->isUnion();
3755
Alexis Hunt491ec602011-06-21 23:42:56 +00003756 unsigned ArgQuals =
3757 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3758 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00003759
3760 // We do this because we should never actually use an anonymous
3761 // union's constructor.
3762 if (Union && RD->isAnonymousStructOrUnion())
3763 return false;
3764
Alexis Huntb2f27802011-05-14 05:23:24 +00003765 // FIXME: We should put some diagnostic logic right into this function.
3766
3767 // C++0x [class.copy]/11
3768 // A defaulted [copy] assignment operator for class X is defined as deleted
3769 // if X has:
3770
3771 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3772 BE = RD->bases_end();
3773 BI != BE; ++BI) {
3774 // We'll handle this one later
3775 if (BI->isVirtual())
3776 continue;
3777
3778 QualType BaseType = BI->getType();
3779 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3780 assert(BaseDecl && "base isn't a CXXRecordDecl");
3781
3782 // -- a [direct base class] B that cannot be [copied] because overload
3783 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00003784 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00003785 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00003786 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3787 0);
3788 if (!CopyOper || CopyOper->isDeleted())
3789 return true;
3790 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00003791 return true;
3792 }
3793
3794 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3795 BE = RD->vbases_end();
3796 BI != BE; ++BI) {
3797 QualType BaseType = BI->getType();
3798 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3799 assert(BaseDecl && "base isn't a CXXRecordDecl");
3800
Alexis Huntb2f27802011-05-14 05:23:24 +00003801 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00003802 // resolution, as applied to B's [copy] assignment operator, results in
3803 // an ambiguity or a function that is deleted or inaccessible from the
3804 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00003805 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3806 0);
3807 if (!CopyOper || CopyOper->isDeleted())
3808 return true;
3809 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00003810 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00003811 }
3812
3813 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3814 FE = RD->field_end();
3815 FI != FE; ++FI) {
3816 QualType FieldType = Context.getBaseElementType(FI->getType());
3817
3818 // -- a non-static data member of reference type
3819 if (FieldType->isReferenceType())
3820 return true;
3821
3822 // -- a non-static data member of const non-class type (or array thereof)
3823 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3824 return true;
3825
3826 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3827
3828 if (FieldRecord) {
3829 // This is an anonymous union
3830 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3831 // Anonymous unions inside unions do not variant members create
3832 if (!Union) {
3833 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3834 UE = FieldRecord->field_end();
3835 UI != UE; ++UI) {
3836 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3837 CXXRecordDecl *UnionFieldRecord =
3838 UnionFieldType->getAsCXXRecordDecl();
3839
3840 // -- a variant member with a non-trivial [copy] assignment operator
3841 // and X is a union-like class
3842 if (UnionFieldRecord &&
3843 !UnionFieldRecord->hasTrivialCopyAssignment())
3844 return true;
3845 }
3846 }
3847
3848 // Don't try to initalize an anonymous union
3849 continue;
3850 // -- a variant member with a non-trivial [copy] assignment operator
3851 // and X is a union-like class
3852 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3853 return true;
3854 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003855
Alexis Hunt491ec602011-06-21 23:42:56 +00003856 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
3857 false, 0);
3858 if (!CopyOper || CopyOper->isDeleted())
3859 return false;
3860 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3861 return false;
Alexis Huntc9a55732011-05-14 05:23:28 +00003862 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003863 }
3864
3865 return false;
3866}
3867
Alexis Huntf91729462011-05-12 22:46:25 +00003868bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3869 CXXRecordDecl *RD = DD->getParent();
3870 assert(!RD->isDependentType() && "do deletion after instantiation");
3871 if (!LangOpts.CPlusPlus0x)
3872 return false;
3873
Alexis Hunte77a28f2011-05-18 03:41:58 +00003874 SourceLocation Loc = DD->getLocation();
3875
Alexis Huntf91729462011-05-12 22:46:25 +00003876 // Do access control from the destructor
3877 ContextRAII CtorContext(*this, DD);
3878
3879 bool Union = RD->isUnion();
3880
Alexis Hunt913820d2011-05-13 06:10:58 +00003881 // We do this because we should never actually use an anonymous
3882 // union's destructor.
3883 if (Union && RD->isAnonymousStructOrUnion())
3884 return false;
3885
Alexis Huntf91729462011-05-12 22:46:25 +00003886 // C++0x [class.dtor]p5
3887 // A defaulted destructor for a class X is defined as deleted if:
3888 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3889 BE = RD->bases_end();
3890 BI != BE; ++BI) {
3891 // We'll handle this one later
3892 if (BI->isVirtual())
3893 continue;
3894
3895 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3896 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3897 assert(BaseDtor && "base has no destructor");
3898
3899 // -- any direct or virtual base class has a deleted destructor or
3900 // a destructor that is inaccessible from the defaulted destructor
3901 if (BaseDtor->isDeleted())
3902 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003903 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003904 AR_accessible)
3905 return true;
3906 }
3907
3908 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3909 BE = RD->vbases_end();
3910 BI != BE; ++BI) {
3911 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3912 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3913 assert(BaseDtor && "base has no destructor");
3914
3915 // -- any direct or virtual base class has a deleted destructor or
3916 // a destructor that is inaccessible from the defaulted destructor
3917 if (BaseDtor->isDeleted())
3918 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003919 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003920 AR_accessible)
3921 return true;
3922 }
3923
3924 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3925 FE = RD->field_end();
3926 FI != FE; ++FI) {
3927 QualType FieldType = Context.getBaseElementType(FI->getType());
3928 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3929 if (FieldRecord) {
3930 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3931 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3932 UE = FieldRecord->field_end();
3933 UI != UE; ++UI) {
3934 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3935 CXXRecordDecl *UnionFieldRecord =
3936 UnionFieldType->getAsCXXRecordDecl();
3937
3938 // -- X is a union-like class that has a variant member with a non-
3939 // trivial destructor.
3940 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3941 return true;
3942 }
3943 // Technically we are supposed to do this next check unconditionally.
3944 // But that makes absolutely no sense.
3945 } else {
3946 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3947
3948 // -- any of the non-static data members has class type M (or array
3949 // thereof) and M has a deleted destructor or a destructor that is
3950 // inaccessible from the defaulted destructor
3951 if (FieldDtor->isDeleted())
3952 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003953 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003954 AR_accessible)
3955 return true;
3956
3957 // -- X is a union-like class that has a variant member with a non-
3958 // trivial destructor.
3959 if (Union && !FieldDtor->isTrivial())
3960 return true;
3961 }
3962 }
3963 }
3964
3965 if (DD->isVirtual()) {
3966 FunctionDecl *OperatorDelete = 0;
3967 DeclarationName Name =
3968 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00003969 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00003970 false))
3971 return true;
3972 }
3973
3974
3975 return false;
3976}
3977
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003978/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00003979namespace {
3980 struct FindHiddenVirtualMethodData {
3981 Sema *S;
3982 CXXMethodDecl *Method;
3983 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3984 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3985 };
3986}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003987
3988/// \brief Member lookup function that determines whether a given C++
3989/// method overloads virtual methods in a base class without overriding any,
3990/// to be used with CXXRecordDecl::lookupInBases().
3991static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3992 CXXBasePath &Path,
3993 void *UserData) {
3994 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3995
3996 FindHiddenVirtualMethodData &Data
3997 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3998
3999 DeclarationName Name = Data.Method->getDeclName();
4000 assert(Name.getNameKind() == DeclarationName::Identifier);
4001
4002 bool foundSameNameMethod = false;
4003 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4004 for (Path.Decls = BaseRecord->lookup(Name);
4005 Path.Decls.first != Path.Decls.second;
4006 ++Path.Decls.first) {
4007 NamedDecl *D = *Path.Decls.first;
4008 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004009 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004010 foundSameNameMethod = true;
4011 // Interested only in hidden virtual methods.
4012 if (!MD->isVirtual())
4013 continue;
4014 // If the method we are checking overrides a method from its base
4015 // don't warn about the other overloaded methods.
4016 if (!Data.S->IsOverload(Data.Method, MD, false))
4017 return true;
4018 // Collect the overload only if its hidden.
4019 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4020 overloadedMethods.push_back(MD);
4021 }
4022 }
4023
4024 if (foundSameNameMethod)
4025 Data.OverloadedMethods.append(overloadedMethods.begin(),
4026 overloadedMethods.end());
4027 return foundSameNameMethod;
4028}
4029
4030/// \brief See if a method overloads virtual methods in a base class without
4031/// overriding any.
4032void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4033 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4034 MD->getLocation()) == Diagnostic::Ignored)
4035 return;
4036 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4037 return;
4038
4039 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4040 /*bool RecordPaths=*/false,
4041 /*bool DetectVirtual=*/false);
4042 FindHiddenVirtualMethodData Data;
4043 Data.Method = MD;
4044 Data.S = this;
4045
4046 // Keep the base methods that were overriden or introduced in the subclass
4047 // by 'using' in a set. A base method not in this set is hidden.
4048 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4049 res.first != res.second; ++res.first) {
4050 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4051 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4052 E = MD->end_overridden_methods();
4053 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004054 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004055 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4056 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004057 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004058 }
4059
4060 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4061 !Data.OverloadedMethods.empty()) {
4062 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4063 << MD << (Data.OverloadedMethods.size() > 1);
4064
4065 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4066 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4067 Diag(overloadedMD->getLocation(),
4068 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4069 }
4070 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004071}
4072
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004073void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004074 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004075 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004076 SourceLocation RBrac,
4077 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004078 if (!TagDecl)
4079 return;
Mike Stump11289f42009-09-09 15:08:12 +00004080
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004081 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004082
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004083 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00004084 // strict aliasing violation!
4085 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004086 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004087
Douglas Gregor0be31a22010-07-02 17:43:08 +00004088 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004089 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004090}
4091
Douglas Gregor05379422008-11-03 17:51:48 +00004092/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4093/// special functions, such as the default constructor, copy
4094/// constructor, or destructor, to the given C++ class (C++
4095/// [special]p1). This routine can only be executed just before the
4096/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004097void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004098 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004099 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004100
Douglas Gregor54be3392010-07-01 17:57:27 +00004101 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004102 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004103
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004104 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4105 ++ASTContext::NumImplicitCopyAssignmentOperators;
4106
4107 // If we have a dynamic class, then the copy assignment operator may be
4108 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4109 // it shows up in the right place in the vtable and that we diagnose
4110 // problems with the implicit exception specification.
4111 if (ClassDecl->isDynamicClass())
4112 DeclareImplicitCopyAssignment(ClassDecl);
4113 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004114
Douglas Gregor7454c562010-07-02 20:37:36 +00004115 if (!ClassDecl->hasUserDeclaredDestructor()) {
4116 ++ASTContext::NumImplicitDestructors;
4117
4118 // If we have a dynamic class, then the destructor may be virtual, so we
4119 // have to declare the destructor immediately. This ensures that, e.g., it
4120 // shows up in the right place in the vtable and that we diagnose problems
4121 // with the implicit exception specification.
4122 if (ClassDecl->isDynamicClass())
4123 DeclareImplicitDestructor(ClassDecl);
4124 }
Douglas Gregor05379422008-11-03 17:51:48 +00004125}
4126
Francois Pichet1c229c02011-04-22 22:18:13 +00004127void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4128 if (!D)
4129 return;
4130
4131 int NumParamList = D->getNumTemplateParameterLists();
4132 for (int i = 0; i < NumParamList; i++) {
4133 TemplateParameterList* Params = D->getTemplateParameterList(i);
4134 for (TemplateParameterList::iterator Param = Params->begin(),
4135 ParamEnd = Params->end();
4136 Param != ParamEnd; ++Param) {
4137 NamedDecl *Named = cast<NamedDecl>(*Param);
4138 if (Named->getDeclName()) {
4139 S->AddDecl(Named);
4140 IdResolver.AddDecl(Named);
4141 }
4142 }
4143 }
4144}
4145
John McCall48871652010-08-21 09:40:31 +00004146void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004147 if (!D)
4148 return;
4149
4150 TemplateParameterList *Params = 0;
4151 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4152 Params = Template->getTemplateParameters();
4153 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4154 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4155 Params = PartialSpec->getTemplateParameters();
4156 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004157 return;
4158
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004159 for (TemplateParameterList::iterator Param = Params->begin(),
4160 ParamEnd = Params->end();
4161 Param != ParamEnd; ++Param) {
4162 NamedDecl *Named = cast<NamedDecl>(*Param);
4163 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004164 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004165 IdResolver.AddDecl(Named);
4166 }
4167 }
4168}
4169
John McCall48871652010-08-21 09:40:31 +00004170void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004171 if (!RecordD) return;
4172 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004173 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004174 PushDeclContext(S, Record);
4175}
4176
John McCall48871652010-08-21 09:40:31 +00004177void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004178 if (!RecordD) return;
4179 PopDeclContext();
4180}
4181
Douglas Gregor4d87df52008-12-16 21:30:33 +00004182/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4183/// parsing a top-level (non-nested) C++ class, and we are now
4184/// parsing those parts of the given Method declaration that could
4185/// not be parsed earlier (C++ [class.mem]p2), such as default
4186/// arguments. This action should enter the scope of the given
4187/// Method declaration as if we had just parsed the qualified method
4188/// name. However, it should not bring the parameters into scope;
4189/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004190void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004191}
4192
4193/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4194/// C++ method declaration. We're (re-)introducing the given
4195/// function parameter into scope for use in parsing later parts of
4196/// the method declaration. For example, we could see an
4197/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004198void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004199 if (!ParamD)
4200 return;
Mike Stump11289f42009-09-09 15:08:12 +00004201
John McCall48871652010-08-21 09:40:31 +00004202 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004203
4204 // If this parameter has an unparsed default argument, clear it out
4205 // to make way for the parsed default argument.
4206 if (Param->hasUnparsedDefaultArg())
4207 Param->setDefaultArg(0);
4208
John McCall48871652010-08-21 09:40:31 +00004209 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004210 if (Param->getDeclName())
4211 IdResolver.AddDecl(Param);
4212}
4213
4214/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4215/// processing the delayed method declaration for Method. The method
4216/// declaration is now considered finished. There may be a separate
4217/// ActOnStartOfFunctionDef action later (not necessarily
4218/// immediately!) for this method, if it was also defined inside the
4219/// class body.
John McCall48871652010-08-21 09:40:31 +00004220void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004221 if (!MethodD)
4222 return;
Mike Stump11289f42009-09-09 15:08:12 +00004223
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004224 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004225
John McCall48871652010-08-21 09:40:31 +00004226 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004227
4228 // Now that we have our default arguments, check the constructor
4229 // again. It could produce additional diagnostics or affect whether
4230 // the class has implicitly-declared destructors, among other
4231 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004232 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4233 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004234
4235 // Check the default arguments, which we may have added.
4236 if (!Method->isInvalidDecl())
4237 CheckCXXDefaultArguments(Method);
4238}
4239
Douglas Gregor831c93f2008-11-05 20:51:48 +00004240/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004241/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004242/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004243/// emit diagnostics and set the invalid bit to true. In any case, the type
4244/// will be updated to reflect a well-formed type for the constructor and
4245/// returned.
4246QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004247 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004248 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004249
4250 // C++ [class.ctor]p3:
4251 // A constructor shall not be virtual (10.3) or static (9.4). A
4252 // constructor can be invoked for a const, volatile or const
4253 // volatile object. A constructor shall not be declared const,
4254 // volatile, or const volatile (9.3.2).
4255 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004256 if (!D.isInvalidType())
4257 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4258 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4259 << SourceRange(D.getIdentifierLoc());
4260 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004261 }
John McCall8e7d6562010-08-26 03:08:43 +00004262 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004263 if (!D.isInvalidType())
4264 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4265 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4266 << SourceRange(D.getIdentifierLoc());
4267 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004268 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004269 }
Mike Stump11289f42009-09-09 15:08:12 +00004270
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004271 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004272 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004273 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004274 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4275 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004276 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004277 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4278 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004279 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004280 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4281 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004282 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004283 }
Mike Stump11289f42009-09-09 15:08:12 +00004284
Douglas Gregordb9d6642011-01-26 05:01:58 +00004285 // C++0x [class.ctor]p4:
4286 // A constructor shall not be declared with a ref-qualifier.
4287 if (FTI.hasRefQualifier()) {
4288 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4289 << FTI.RefQualifierIsLValueRef
4290 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4291 D.setInvalidType();
4292 }
4293
Douglas Gregor831c93f2008-11-05 20:51:48 +00004294 // Rebuild the function type "R" without any type qualifiers (in
4295 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004296 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004297 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004298 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4299 return R;
4300
4301 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4302 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004303 EPI.RefQualifier = RQ_None;
4304
Chris Lattner38378bf2009-04-25 08:28:21 +00004305 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004306 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004307}
4308
Douglas Gregor4d87df52008-12-16 21:30:33 +00004309/// CheckConstructor - Checks a fully-formed constructor for
4310/// well-formedness, issuing any diagnostics required. Returns true if
4311/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004312void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004313 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004314 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4315 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004316 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004317
4318 // C++ [class.copy]p3:
4319 // A declaration of a constructor for a class X is ill-formed if
4320 // its first parameter is of type (optionally cv-qualified) X and
4321 // either there are no other parameters or else all other
4322 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004323 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004324 ((Constructor->getNumParams() == 1) ||
4325 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004326 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4327 Constructor->getTemplateSpecializationKind()
4328 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004329 QualType ParamType = Constructor->getParamDecl(0)->getType();
4330 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4331 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004332 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004333 const char *ConstRef
4334 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4335 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004336 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004337 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004338
4339 // FIXME: Rather that making the constructor invalid, we should endeavor
4340 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004341 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004342 }
4343 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004344}
4345
John McCalldeb646e2010-08-04 01:04:25 +00004346/// CheckDestructor - Checks a fully-formed destructor definition for
4347/// well-formedness, issuing any diagnostics required. Returns true
4348/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004349bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004350 CXXRecordDecl *RD = Destructor->getParent();
4351
4352 if (Destructor->isVirtual()) {
4353 SourceLocation Loc;
4354
4355 if (!Destructor->isImplicit())
4356 Loc = Destructor->getLocation();
4357 else
4358 Loc = RD->getLocation();
4359
4360 // If we have a virtual destructor, look up the deallocation function
4361 FunctionDecl *OperatorDelete = 0;
4362 DeclarationName Name =
4363 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004364 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004365 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004366
4367 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004368
4369 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004370 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004371
4372 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004373}
4374
Mike Stump11289f42009-09-09 15:08:12 +00004375static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004376FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4377 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4378 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004379 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004380}
4381
Douglas Gregor831c93f2008-11-05 20:51:48 +00004382/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4383/// the well-formednes of the destructor declarator @p D with type @p
4384/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004385/// emit diagnostics and set the declarator to invalid. Even if this happens,
4386/// will be updated to reflect a well-formed type for the destructor and
4387/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004388QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004389 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004390 // C++ [class.dtor]p1:
4391 // [...] A typedef-name that names a class is a class-name
4392 // (7.1.3); however, a typedef-name that names a class shall not
4393 // be used as the identifier in the declarator for a destructor
4394 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004395 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004396 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004397 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004398 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004399 else if (const TemplateSpecializationType *TST =
4400 DeclaratorType->getAs<TemplateSpecializationType>())
4401 if (TST->isTypeAlias())
4402 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4403 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004404
4405 // C++ [class.dtor]p2:
4406 // A destructor is used to destroy objects of its class type. A
4407 // destructor takes no parameters, and no return type can be
4408 // specified for it (not even void). The address of a destructor
4409 // shall not be taken. A destructor shall not be static. A
4410 // destructor can be invoked for a const, volatile or const
4411 // volatile object. A destructor shall not be declared const,
4412 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004413 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004414 if (!D.isInvalidType())
4415 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4416 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004417 << SourceRange(D.getIdentifierLoc())
4418 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4419
John McCall8e7d6562010-08-26 03:08:43 +00004420 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004421 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004422 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004423 // Destructors don't have return types, but the parser will
4424 // happily parse something like:
4425 //
4426 // class X {
4427 // float ~X();
4428 // };
4429 //
4430 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004431 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4432 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4433 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004434 }
Mike Stump11289f42009-09-09 15:08:12 +00004435
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004436 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004437 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004438 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004439 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4440 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004441 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004442 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4443 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004444 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4446 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00004447 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004448 }
4449
Douglas Gregordb9d6642011-01-26 05:01:58 +00004450 // C++0x [class.dtor]p2:
4451 // A destructor shall not be declared with a ref-qualifier.
4452 if (FTI.hasRefQualifier()) {
4453 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4454 << FTI.RefQualifierIsLValueRef
4455 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4456 D.setInvalidType();
4457 }
4458
Douglas Gregor831c93f2008-11-05 20:51:48 +00004459 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00004460 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004461 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4462
4463 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00004464 FTI.freeArgs();
4465 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004466 }
4467
Mike Stump11289f42009-09-09 15:08:12 +00004468 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00004469 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004470 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00004471 D.setInvalidType();
4472 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00004473
4474 // Rebuild the function type "R" without any type qualifiers or
4475 // parameters (in case any of the errors above fired) and with
4476 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00004477 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00004478 if (!D.isInvalidType())
4479 return R;
4480
Douglas Gregor95755162010-07-01 05:10:53 +00004481 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004482 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4483 EPI.Variadic = false;
4484 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004485 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004486 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004487}
4488
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004489/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4490/// well-formednes of the conversion function declarator @p D with
4491/// type @p R. If there are any errors in the declarator, this routine
4492/// will emit diagnostics and return true. Otherwise, it will return
4493/// false. Either way, the type @p R will be updated to reflect a
4494/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004495void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00004496 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004497 // C++ [class.conv.fct]p1:
4498 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00004499 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00004500 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00004501 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004502 if (!D.isInvalidType())
4503 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4504 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4505 << SourceRange(D.getIdentifierLoc());
4506 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004507 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004508 }
John McCall212fa2e2010-04-13 00:04:31 +00004509
4510 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4511
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004512 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004513 // Conversion functions don't have return types, but the parser will
4514 // happily parse something like:
4515 //
4516 // class X {
4517 // float operator bool();
4518 // };
4519 //
4520 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00004521 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4522 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4523 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00004524 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004525 }
4526
John McCall212fa2e2010-04-13 00:04:31 +00004527 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4528
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004529 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00004530 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004531 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4532
4533 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004534 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004535 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00004536 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004537 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004538 D.setInvalidType();
4539 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004540
John McCall212fa2e2010-04-13 00:04:31 +00004541 // Diagnose "&operator bool()" and other such nonsense. This
4542 // is actually a gcc extension which we don't support.
4543 if (Proto->getResultType() != ConvType) {
4544 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4545 << Proto->getResultType();
4546 D.setInvalidType();
4547 ConvType = Proto->getResultType();
4548 }
4549
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004550 // C++ [class.conv.fct]p4:
4551 // The conversion-type-id shall not represent a function type nor
4552 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004553 if (ConvType->isArrayType()) {
4554 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4555 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004556 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004557 } else if (ConvType->isFunctionType()) {
4558 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4559 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004560 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004561 }
4562
4563 // Rebuild the function type "R" without any parameters (in case any
4564 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00004565 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00004566 if (D.isInvalidType())
4567 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004568
Douglas Gregor5fb53972009-01-14 15:45:31 +00004569 // C++0x explicit conversion operators.
4570 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00004571 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00004572 diag::warn_explicit_conversion_functions)
4573 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004574}
4575
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004576/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4577/// the declaration of the given C++ conversion function. This routine
4578/// is responsible for recording the conversion function in the C++
4579/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00004580Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004581 assert(Conversion && "Expected to receive a conversion function declaration");
4582
Douglas Gregor4287b372008-12-12 08:25:50 +00004583 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004584
4585 // Make sure we aren't redeclaring the conversion function.
4586 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004587
4588 // C++ [class.conv.fct]p1:
4589 // [...] A conversion function is never used to convert a
4590 // (possibly cv-qualified) object to the (possibly cv-qualified)
4591 // same object type (or a reference to it), to a (possibly
4592 // cv-qualified) base class of that type (or a reference to it),
4593 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00004594 // FIXME: Suppress this warning if the conversion function ends up being a
4595 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00004596 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004597 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004598 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004599 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004600 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4601 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00004602 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004603 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004604 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4605 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004606 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004607 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004608 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004609 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004610 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004611 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004612 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004613 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004614 }
4615
Douglas Gregor457104e2010-09-29 04:25:11 +00004616 if (FunctionTemplateDecl *ConversionTemplate
4617 = Conversion->getDescribedFunctionTemplate())
4618 return ConversionTemplate;
4619
John McCall48871652010-08-21 09:40:31 +00004620 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004621}
4622
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004623//===----------------------------------------------------------------------===//
4624// Namespace Handling
4625//===----------------------------------------------------------------------===//
4626
John McCallb1be5232010-08-26 09:15:37 +00004627
4628
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004629/// ActOnStartNamespaceDef - This is called at the start of a namespace
4630/// definition.
John McCall48871652010-08-21 09:40:31 +00004631Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00004632 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004633 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00004634 SourceLocation IdentLoc,
4635 IdentifierInfo *II,
4636 SourceLocation LBrace,
4637 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004638 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4639 // For anonymous namespace, take the location of the left brace.
4640 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00004641 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004642 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004643 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004644
4645 Scope *DeclRegionScope = NamespcScope->getParent();
4646
Anders Carlssona7bcade2010-02-07 01:09:23 +00004647 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4648
John McCall2faf32c2010-12-10 02:59:44 +00004649 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4650 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00004651
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004652 if (II) {
4653 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00004654 // The identifier in an original-namespace-definition shall not
4655 // have been previously defined in the declarative region in
4656 // which the original-namespace-definition appears. The
4657 // identifier in an original-namespace-definition is the name of
4658 // the namespace. Subsequently in that declarative region, it is
4659 // treated as an original-namespace-name.
4660 //
4661 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00004662 // look through using directives, just look for any ordinary names.
4663
4664 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4665 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4666 Decl::IDNS_Namespace;
4667 NamedDecl *PrevDecl = 0;
4668 for (DeclContext::lookup_result R
4669 = CurContext->getRedeclContext()->lookup(II);
4670 R.first != R.second; ++R.first) {
4671 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4672 PrevDecl = *R.first;
4673 break;
4674 }
4675 }
4676
Douglas Gregor91f84212008-12-11 16:49:14 +00004677 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4678 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004679 if (Namespc->isInline() != OrigNS->isInline()) {
4680 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00004681 if (OrigNS->isInline()) {
4682 // The user probably just forgot the 'inline', so suggest that it
4683 // be added back.
4684 Diag(Namespc->getLocation(),
4685 diag::warn_inline_namespace_reopened_noninline)
4686 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4687 } else {
4688 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4689 << Namespc->isInline();
4690 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004691 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00004692
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004693 // Recover by ignoring the new namespace's inline status.
4694 Namespc->setInline(OrigNS->isInline());
4695 }
4696
Douglas Gregor91f84212008-12-11 16:49:14 +00004697 // Attach this namespace decl to the chain of extended namespace
4698 // definitions.
4699 OrigNS->setNextNamespace(Namespc);
4700 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004701
Mike Stump11289f42009-09-09 15:08:12 +00004702 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00004703 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00004704 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00004705 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004706 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004707 } else if (PrevDecl) {
4708 // This is an invalid name redefinition.
4709 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4710 << Namespc->getDeclName();
4711 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4712 Namespc->setInvalidDecl();
4713 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00004714 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004715 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004716 // This is the first "real" definition of the namespace "std", so update
4717 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004718 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004719 // We had already defined a dummy namespace "std". Link this new
4720 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004721 StdNS->setNextNamespace(Namespc);
4722 StdNS->setLocation(IdentLoc);
4723 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00004724 }
4725
4726 // Make our StdNamespace cache point at the first real definition of the
4727 // "std" namespace.
4728 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00004729 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004730
4731 PushOnScopeChains(Namespc, DeclRegionScope);
4732 } else {
John McCall4fa53422009-10-01 00:25:31 +00004733 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00004734 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00004735
4736 // Link the anonymous namespace into its parent.
4737 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00004738 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00004739 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4740 PrevDecl = TU->getAnonymousNamespace();
4741 TU->setAnonymousNamespace(Namespc);
4742 } else {
4743 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4744 PrevDecl = ND->getAnonymousNamespace();
4745 ND->setAnonymousNamespace(Namespc);
4746 }
4747
4748 // Link the anonymous namespace with its previous declaration.
4749 if (PrevDecl) {
4750 assert(PrevDecl->isAnonymousNamespace());
4751 assert(!PrevDecl->getNextNamespace());
4752 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4753 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004754
4755 if (Namespc->isInline() != PrevDecl->isInline()) {
4756 // inline-ness must match
4757 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4758 << Namespc->isInline();
4759 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4760 Namespc->setInvalidDecl();
4761 // Recover by ignoring the new namespace's inline status.
4762 Namespc->setInline(PrevDecl->isInline());
4763 }
John McCall0db42252009-12-16 02:06:49 +00004764 }
John McCall4fa53422009-10-01 00:25:31 +00004765
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00004766 CurContext->addDecl(Namespc);
4767
John McCall4fa53422009-10-01 00:25:31 +00004768 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4769 // behaves as if it were replaced by
4770 // namespace unique { /* empty body */ }
4771 // using namespace unique;
4772 // namespace unique { namespace-body }
4773 // where all occurrences of 'unique' in a translation unit are
4774 // replaced by the same identifier and this identifier differs
4775 // from all other identifiers in the entire program.
4776
4777 // We just create the namespace with an empty name and then add an
4778 // implicit using declaration, just like the standard suggests.
4779 //
4780 // CodeGen enforces the "universally unique" aspect by giving all
4781 // declarations semantically contained within an anonymous
4782 // namespace internal linkage.
4783
John McCall0db42252009-12-16 02:06:49 +00004784 if (!PrevDecl) {
4785 UsingDirectiveDecl* UD
4786 = UsingDirectiveDecl::Create(Context, CurContext,
4787 /* 'using' */ LBrace,
4788 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00004789 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00004790 /* identifier */ SourceLocation(),
4791 Namespc,
4792 /* Ancestor */ CurContext);
4793 UD->setImplicit();
4794 CurContext->addDecl(UD);
4795 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004796 }
4797
4798 // Although we could have an invalid decl (i.e. the namespace name is a
4799 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00004800 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4801 // for the namespace has the declarations that showed up in that particular
4802 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00004803 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00004804 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004805}
4806
Sebastian Redla6602e92009-11-23 15:34:23 +00004807/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4808/// is a namespace alias, returns the namespace it points to.
4809static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4810 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4811 return AD->getNamespace();
4812 return dyn_cast_or_null<NamespaceDecl>(D);
4813}
4814
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004815/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4816/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00004817void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004818 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4819 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004820 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004821 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00004822 if (Namespc->hasAttr<VisibilityAttr>())
4823 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004824}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004825
John McCall28a0cf72010-08-25 07:42:41 +00004826CXXRecordDecl *Sema::getStdBadAlloc() const {
4827 return cast_or_null<CXXRecordDecl>(
4828 StdBadAlloc.get(Context.getExternalSource()));
4829}
4830
4831NamespaceDecl *Sema::getStdNamespace() const {
4832 return cast_or_null<NamespaceDecl>(
4833 StdNamespace.get(Context.getExternalSource()));
4834}
4835
Douglas Gregorcdf87022010-06-29 17:53:46 +00004836/// \brief Retrieve the special "std" namespace, which may require us to
4837/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004838NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00004839 if (!StdNamespace) {
4840 // The "std" namespace has not yet been defined, so build one implicitly.
4841 StdNamespace = NamespaceDecl::Create(Context,
4842 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004843 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00004844 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004845 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004846 }
4847
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004848 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004849}
4850
Douglas Gregora172e082011-03-26 22:25:30 +00004851/// \brief Determine whether a using statement is in a context where it will be
4852/// apply in all contexts.
4853static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4854 switch (CurContext->getDeclKind()) {
4855 case Decl::TranslationUnit:
4856 return true;
4857 case Decl::LinkageSpec:
4858 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4859 default:
4860 return false;
4861 }
4862}
4863
John McCall48871652010-08-21 09:40:31 +00004864Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00004865 SourceLocation UsingLoc,
4866 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004867 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004868 SourceLocation IdentLoc,
4869 IdentifierInfo *NamespcName,
4870 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00004871 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4872 assert(NamespcName && "Invalid NamespcName.");
4873 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00004874
4875 // This can only happen along a recovery path.
4876 while (S->getFlags() & Scope::TemplateParamScope)
4877 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00004878 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00004879
Douglas Gregor889ceb72009-02-03 19:21:40 +00004880 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00004881 NestedNameSpecifier *Qualifier = 0;
4882 if (SS.isSet())
4883 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4884
Douglas Gregor34074322009-01-14 22:20:51 +00004885 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004886 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4887 LookupParsedName(R, S, &SS);
4888 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004889 return 0;
John McCall27b18f82009-11-17 02:14:36 +00004890
Douglas Gregorcdf87022010-06-29 17:53:46 +00004891 if (R.empty()) {
4892 // Allow "using namespace std;" or "using namespace ::std;" even if
4893 // "std" hasn't been defined yet, for GCC compatibility.
4894 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4895 NamespcName->isStr("std")) {
4896 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004897 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00004898 R.resolveKind();
4899 }
4900 // Otherwise, attempt typo correction.
4901 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4902 CTC_NoKeywords, 0)) {
4903 if (R.getAsSingle<NamespaceDecl>() ||
4904 R.getAsSingle<NamespaceAliasDecl>()) {
4905 if (DeclContext *DC = computeDeclContext(SS, false))
4906 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4907 << NamespcName << DC << Corrected << SS.getRange()
4908 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4909 else
4910 Diag(IdentLoc, diag::err_using_directive_suggest)
4911 << NamespcName << Corrected
4912 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4913 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4914 << Corrected;
4915
4916 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004917 } else {
4918 R.clear();
4919 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004920 }
4921 }
4922 }
4923
John McCall9f3059a2009-10-09 21:13:30 +00004924 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00004925 NamedDecl *Named = R.getFoundDecl();
4926 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4927 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00004928 // C++ [namespace.udir]p1:
4929 // A using-directive specifies that the names in the nominated
4930 // namespace can be used in the scope in which the
4931 // using-directive appears after the using-directive. During
4932 // unqualified name lookup (3.4.1), the names appear as if they
4933 // were declared in the nearest enclosing namespace which
4934 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00004935 // namespace. [Note: in this context, "contains" means "contains
4936 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00004937
4938 // Find enclosing context containing both using-directive and
4939 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00004940 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004941 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4942 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4943 CommonAncestor = CommonAncestor->getParent();
4944
Sebastian Redla6602e92009-11-23 15:34:23 +00004945 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00004946 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00004947 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004948
Douglas Gregora172e082011-03-26 22:25:30 +00004949 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00004950 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004951 Diag(IdentLoc, diag::warn_using_directive_in_header);
4952 }
4953
Douglas Gregor889ceb72009-02-03 19:21:40 +00004954 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004955 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00004956 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00004957 }
4958
Douglas Gregor889ceb72009-02-03 19:21:40 +00004959 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00004960 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00004961}
4962
4963void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4964 // If scope has associated entity, then using directive is at namespace
4965 // or translation unit scope. We add UsingDirectiveDecls, into
4966 // it's lookup structure.
4967 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004968 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004969 else
4970 // Otherwise it is block-sope. using-directives will affect lookup
4971 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00004972 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004973}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004974
Douglas Gregorfec52632009-06-20 00:51:54 +00004975
John McCall48871652010-08-21 09:40:31 +00004976Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00004977 AccessSpecifier AS,
4978 bool HasUsingKeyword,
4979 SourceLocation UsingLoc,
4980 CXXScopeSpec &SS,
4981 UnqualifiedId &Name,
4982 AttributeList *AttrList,
4983 bool IsTypeName,
4984 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004985 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004986
Douglas Gregor220f4272009-11-04 16:30:06 +00004987 switch (Name.getKind()) {
4988 case UnqualifiedId::IK_Identifier:
4989 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004990 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004991 case UnqualifiedId::IK_ConversionFunctionId:
4992 break;
4993
4994 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004995 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004996 // C++0x inherited constructors.
4997 if (getLangOptions().CPlusPlus0x) break;
4998
Douglas Gregor220f4272009-11-04 16:30:06 +00004999 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5000 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005001 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005002
5003 case UnqualifiedId::IK_DestructorName:
5004 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5005 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005006 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005007
5008 case UnqualifiedId::IK_TemplateId:
5009 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5010 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00005011 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005012 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005013
5014 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5015 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005016 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005017 return 0;
John McCall3969e302009-12-08 07:46:18 +00005018
John McCalla0097262009-12-11 02:10:03 +00005019 // Warn about using declarations.
5020 // TODO: store that the declaration was written without 'using' and
5021 // talk about access decls instead of using decls in the
5022 // diagnostics.
5023 if (!HasUsingKeyword) {
5024 UsingLoc = Name.getSourceRange().getBegin();
5025
5026 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005027 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005028 }
5029
Douglas Gregorc4356532010-12-16 00:46:58 +00005030 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5031 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5032 return 0;
5033
John McCall3f746822009-11-17 05:59:44 +00005034 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005035 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005036 /* IsInstantiation */ false,
5037 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005038 if (UD)
5039 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005040
John McCall48871652010-08-21 09:40:31 +00005041 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005042}
5043
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005044/// \brief Determine whether a using declaration considers the given
5045/// declarations as "equivalent", e.g., if they are redeclarations of
5046/// the same entity or are both typedefs of the same type.
5047static bool
5048IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5049 bool &SuppressRedeclaration) {
5050 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5051 SuppressRedeclaration = false;
5052 return true;
5053 }
5054
Richard Smithdda56e42011-04-15 14:24:37 +00005055 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5056 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005057 SuppressRedeclaration = true;
5058 return Context.hasSameType(TD1->getUnderlyingType(),
5059 TD2->getUnderlyingType());
5060 }
5061
5062 return false;
5063}
5064
5065
John McCall84d87672009-12-10 09:41:52 +00005066/// Determines whether to create a using shadow decl for a particular
5067/// decl, given the set of decls existing prior to this using lookup.
5068bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5069 const LookupResult &Previous) {
5070 // Diagnose finding a decl which is not from a base class of the
5071 // current class. We do this now because there are cases where this
5072 // function will silently decide not to build a shadow decl, which
5073 // will pre-empt further diagnostics.
5074 //
5075 // We don't need to do this in C++0x because we do the check once on
5076 // the qualifier.
5077 //
5078 // FIXME: diagnose the following if we care enough:
5079 // struct A { int foo; };
5080 // struct B : A { using A::foo; };
5081 // template <class T> struct C : A {};
5082 // template <class T> struct D : C<T> { using B::foo; } // <---
5083 // This is invalid (during instantiation) in C++03 because B::foo
5084 // resolves to the using decl in B, which is not a base class of D<T>.
5085 // We can't diagnose it immediately because C<T> is an unknown
5086 // specialization. The UsingShadowDecl in D<T> then points directly
5087 // to A::foo, which will look well-formed when we instantiate.
5088 // The right solution is to not collapse the shadow-decl chain.
5089 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5090 DeclContext *OrigDC = Orig->getDeclContext();
5091
5092 // Handle enums and anonymous structs.
5093 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5094 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5095 while (OrigRec->isAnonymousStructOrUnion())
5096 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5097
5098 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5099 if (OrigDC == CurContext) {
5100 Diag(Using->getLocation(),
5101 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005102 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005103 Diag(Orig->getLocation(), diag::note_using_decl_target);
5104 return true;
5105 }
5106
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005107 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005108 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005109 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005110 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005111 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005112 Diag(Orig->getLocation(), diag::note_using_decl_target);
5113 return true;
5114 }
5115 }
5116
5117 if (Previous.empty()) return false;
5118
5119 NamedDecl *Target = Orig;
5120 if (isa<UsingShadowDecl>(Target))
5121 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5122
John McCalla17e83e2009-12-11 02:33:26 +00005123 // If the target happens to be one of the previous declarations, we
5124 // don't have a conflict.
5125 //
5126 // FIXME: but we might be increasing its access, in which case we
5127 // should redeclare it.
5128 NamedDecl *NonTag = 0, *Tag = 0;
5129 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5130 I != E; ++I) {
5131 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005132 bool Result;
5133 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5134 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005135
5136 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5137 }
5138
John McCall84d87672009-12-10 09:41:52 +00005139 if (Target->isFunctionOrFunctionTemplate()) {
5140 FunctionDecl *FD;
5141 if (isa<FunctionTemplateDecl>(Target))
5142 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5143 else
5144 FD = cast<FunctionDecl>(Target);
5145
5146 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005147 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005148 case Ovl_Overload:
5149 return false;
5150
5151 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005152 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005153 break;
5154
5155 // We found a decl with the exact signature.
5156 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005157 // If we're in a record, we want to hide the target, so we
5158 // return true (without a diagnostic) to tell the caller not to
5159 // build a shadow decl.
5160 if (CurContext->isRecord())
5161 return true;
5162
5163 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005164 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005165 break;
5166 }
5167
5168 Diag(Target->getLocation(), diag::note_using_decl_target);
5169 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5170 return true;
5171 }
5172
5173 // Target is not a function.
5174
John McCall84d87672009-12-10 09:41:52 +00005175 if (isa<TagDecl>(Target)) {
5176 // No conflict between a tag and a non-tag.
5177 if (!Tag) return false;
5178
John McCalle29c5cd2009-12-10 19:51:03 +00005179 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005180 Diag(Target->getLocation(), diag::note_using_decl_target);
5181 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5182 return true;
5183 }
5184
5185 // No conflict between a tag and a non-tag.
5186 if (!NonTag) return false;
5187
John McCalle29c5cd2009-12-10 19:51:03 +00005188 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005189 Diag(Target->getLocation(), diag::note_using_decl_target);
5190 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5191 return true;
5192}
5193
John McCall3f746822009-11-17 05:59:44 +00005194/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005195UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005196 UsingDecl *UD,
5197 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005198
5199 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005200 NamedDecl *Target = Orig;
5201 if (isa<UsingShadowDecl>(Target)) {
5202 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5203 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005204 }
5205
5206 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005207 = UsingShadowDecl::Create(Context, CurContext,
5208 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005209 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005210
5211 Shadow->setAccess(UD->getAccess());
5212 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5213 Shadow->setInvalidDecl();
5214
John McCall3f746822009-11-17 05:59:44 +00005215 if (S)
John McCall3969e302009-12-08 07:46:18 +00005216 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005217 else
John McCall3969e302009-12-08 07:46:18 +00005218 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005219
John McCall3969e302009-12-08 07:46:18 +00005220
John McCall84d87672009-12-10 09:41:52 +00005221 return Shadow;
5222}
John McCall3969e302009-12-08 07:46:18 +00005223
John McCall84d87672009-12-10 09:41:52 +00005224/// Hides a using shadow declaration. This is required by the current
5225/// using-decl implementation when a resolvable using declaration in a
5226/// class is followed by a declaration which would hide or override
5227/// one or more of the using decl's targets; for example:
5228///
5229/// struct Base { void foo(int); };
5230/// struct Derived : Base {
5231/// using Base::foo;
5232/// void foo(int);
5233/// };
5234///
5235/// The governing language is C++03 [namespace.udecl]p12:
5236///
5237/// When a using-declaration brings names from a base class into a
5238/// derived class scope, member functions in the derived class
5239/// override and/or hide member functions with the same name and
5240/// parameter types in a base class (rather than conflicting).
5241///
5242/// There are two ways to implement this:
5243/// (1) optimistically create shadow decls when they're not hidden
5244/// by existing declarations, or
5245/// (2) don't create any shadow decls (or at least don't make them
5246/// visible) until we've fully parsed/instantiated the class.
5247/// The problem with (1) is that we might have to retroactively remove
5248/// a shadow decl, which requires several O(n) operations because the
5249/// decl structures are (very reasonably) not designed for removal.
5250/// (2) avoids this but is very fiddly and phase-dependent.
5251void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005252 if (Shadow->getDeclName().getNameKind() ==
5253 DeclarationName::CXXConversionFunctionName)
5254 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5255
John McCall84d87672009-12-10 09:41:52 +00005256 // Remove it from the DeclContext...
5257 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005258
John McCall84d87672009-12-10 09:41:52 +00005259 // ...and the scope, if applicable...
5260 if (S) {
John McCall48871652010-08-21 09:40:31 +00005261 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005262 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005263 }
5264
John McCall84d87672009-12-10 09:41:52 +00005265 // ...and the using decl.
5266 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5267
5268 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005269 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005270}
5271
John McCalle61f2ba2009-11-18 02:36:19 +00005272/// Builds a using declaration.
5273///
5274/// \param IsInstantiation - Whether this call arises from an
5275/// instantiation of an unresolved using declaration. We treat
5276/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005277NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5278 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005279 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005280 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005281 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005282 bool IsInstantiation,
5283 bool IsTypeName,
5284 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005285 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005286 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005287 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005288
Anders Carlssonf038fc22009-08-28 05:49:21 +00005289 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005290
Anders Carlsson59140b32009-08-28 03:16:11 +00005291 if (SS.isEmpty()) {
5292 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005293 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005294 }
Mike Stump11289f42009-09-09 15:08:12 +00005295
John McCall84d87672009-12-10 09:41:52 +00005296 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005297 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005298 ForRedeclaration);
5299 Previous.setHideTags(false);
5300 if (S) {
5301 LookupName(Previous, S);
5302
5303 // It is really dumb that we have to do this.
5304 LookupResult::Filter F = Previous.makeFilter();
5305 while (F.hasNext()) {
5306 NamedDecl *D = F.next();
5307 if (!isDeclInScope(D, CurContext, S))
5308 F.erase();
5309 }
5310 F.done();
5311 } else {
5312 assert(IsInstantiation && "no scope in non-instantiation");
5313 assert(CurContext->isRecord() && "scope not record in instantiation");
5314 LookupQualifiedName(Previous, CurContext);
5315 }
5316
John McCall84d87672009-12-10 09:41:52 +00005317 // Check for invalid redeclarations.
5318 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5319 return 0;
5320
5321 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005322 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5323 return 0;
5324
John McCall84c16cf2009-11-12 03:15:40 +00005325 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005326 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005327 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005328 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005329 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005330 // FIXME: not all declaration name kinds are legal here
5331 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5332 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005333 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005334 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005335 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005336 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5337 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005338 }
John McCallb96ec562009-12-04 22:46:56 +00005339 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005340 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5341 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005342 }
John McCallb96ec562009-12-04 22:46:56 +00005343 D->setAccess(AS);
5344 CurContext->addDecl(D);
5345
5346 if (!LookupContext) return D;
5347 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005348
John McCall0b66eb32010-05-01 00:40:08 +00005349 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005350 UD->setInvalidDecl();
5351 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005352 }
5353
Sebastian Redl08905022011-02-05 19:23:19 +00005354 // Constructor inheriting using decls get special treatment.
5355 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005356 if (CheckInheritedConstructorUsingDecl(UD))
5357 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005358 return UD;
5359 }
5360
5361 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005362
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005363 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetefb1af92011-05-23 03:43:44 +00005364 R.setUsingDeclaration(true);
John McCalle61f2ba2009-11-18 02:36:19 +00005365
John McCall3969e302009-12-08 07:46:18 +00005366 // Unlike most lookups, we don't always want to hide tag
5367 // declarations: tag names are visible through the using declaration
5368 // even if hidden by ordinary names, *except* in a dependent context
5369 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005370 if (!IsInstantiation)
5371 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005372
John McCall27b18f82009-11-17 02:14:36 +00005373 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005374
John McCall9f3059a2009-10-09 21:13:30 +00005375 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005376 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005377 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005378 UD->setInvalidDecl();
5379 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005380 }
5381
John McCallb96ec562009-12-04 22:46:56 +00005382 if (R.isAmbiguous()) {
5383 UD->setInvalidDecl();
5384 return UD;
5385 }
Mike Stump11289f42009-09-09 15:08:12 +00005386
John McCalle61f2ba2009-11-18 02:36:19 +00005387 if (IsTypeName) {
5388 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005389 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005390 Diag(IdentLoc, diag::err_using_typename_non_type);
5391 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5392 Diag((*I)->getUnderlyingDecl()->getLocation(),
5393 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005394 UD->setInvalidDecl();
5395 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005396 }
5397 } else {
5398 // If we asked for a non-typename and we got a type, error out,
5399 // but only if this is an instantiation of an unresolved using
5400 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005401 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005402 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5403 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005404 UD->setInvalidDecl();
5405 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005406 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005407 }
5408
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005409 // C++0x N2914 [namespace.udecl]p6:
5410 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005411 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005412 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5413 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005414 UD->setInvalidDecl();
5415 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005416 }
Mike Stump11289f42009-09-09 15:08:12 +00005417
John McCall84d87672009-12-10 09:41:52 +00005418 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5419 if (!CheckUsingShadowDecl(UD, *I, Previous))
5420 BuildUsingShadowDecl(S, UD, *I);
5421 }
John McCall3f746822009-11-17 05:59:44 +00005422
5423 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005424}
5425
Sebastian Redl08905022011-02-05 19:23:19 +00005426/// Additional checks for a using declaration referring to a constructor name.
5427bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5428 if (UD->isTypeName()) {
5429 // FIXME: Cannot specify typename when specifying constructor
5430 return true;
5431 }
5432
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005433 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00005434 assert(SourceType &&
5435 "Using decl naming constructor doesn't have type in scope spec.");
5436 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5437
5438 // Check whether the named type is a direct base class.
5439 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5440 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5441 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5442 BaseIt != BaseE; ++BaseIt) {
5443 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5444 if (CanonicalSourceType == BaseType)
5445 break;
5446 }
5447
5448 if (BaseIt == BaseE) {
5449 // Did not find SourceType in the bases.
5450 Diag(UD->getUsingLocation(),
5451 diag::err_using_decl_constructor_not_in_direct_base)
5452 << UD->getNameInfo().getSourceRange()
5453 << QualType(SourceType, 0) << TargetClass;
5454 return true;
5455 }
5456
5457 BaseIt->setInheritConstructors();
5458
5459 return false;
5460}
5461
John McCall84d87672009-12-10 09:41:52 +00005462/// Checks that the given using declaration is not an invalid
5463/// redeclaration. Note that this is checking only for the using decl
5464/// itself, not for any ill-formedness among the UsingShadowDecls.
5465bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5466 bool isTypeName,
5467 const CXXScopeSpec &SS,
5468 SourceLocation NameLoc,
5469 const LookupResult &Prev) {
5470 // C++03 [namespace.udecl]p8:
5471 // C++0x [namespace.udecl]p10:
5472 // A using-declaration is a declaration and can therefore be used
5473 // repeatedly where (and only where) multiple declarations are
5474 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00005475 //
John McCall032092f2010-11-29 18:01:58 +00005476 // That's in non-member contexts.
5477 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00005478 return false;
5479
5480 NestedNameSpecifier *Qual
5481 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5482
5483 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5484 NamedDecl *D = *I;
5485
5486 bool DTypename;
5487 NestedNameSpecifier *DQual;
5488 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5489 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005490 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005491 } else if (UnresolvedUsingValueDecl *UD
5492 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5493 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005494 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005495 } else if (UnresolvedUsingTypenameDecl *UD
5496 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5497 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005498 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005499 } else continue;
5500
5501 // using decls differ if one says 'typename' and the other doesn't.
5502 // FIXME: non-dependent using decls?
5503 if (isTypeName != DTypename) continue;
5504
5505 // using decls differ if they name different scopes (but note that
5506 // template instantiation can cause this check to trigger when it
5507 // didn't before instantiation).
5508 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5509 Context.getCanonicalNestedNameSpecifier(DQual))
5510 continue;
5511
5512 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00005513 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00005514 return true;
5515 }
5516
5517 return false;
5518}
5519
John McCall3969e302009-12-08 07:46:18 +00005520
John McCallb96ec562009-12-04 22:46:56 +00005521/// Checks that the given nested-name qualifier used in a using decl
5522/// in the current context is appropriately related to the current
5523/// scope. If an error is found, diagnoses it and returns true.
5524bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5525 const CXXScopeSpec &SS,
5526 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00005527 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005528
John McCall3969e302009-12-08 07:46:18 +00005529 if (!CurContext->isRecord()) {
5530 // C++03 [namespace.udecl]p3:
5531 // C++0x [namespace.udecl]p8:
5532 // A using-declaration for a class member shall be a member-declaration.
5533
5534 // If we weren't able to compute a valid scope, it must be a
5535 // dependent class scope.
5536 if (!NamedContext || NamedContext->isRecord()) {
5537 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5538 << SS.getRange();
5539 return true;
5540 }
5541
5542 // Otherwise, everything is known to be fine.
5543 return false;
5544 }
5545
5546 // The current scope is a record.
5547
5548 // If the named context is dependent, we can't decide much.
5549 if (!NamedContext) {
5550 // FIXME: in C++0x, we can diagnose if we can prove that the
5551 // nested-name-specifier does not refer to a base class, which is
5552 // still possible in some cases.
5553
5554 // Otherwise we have to conservatively report that things might be
5555 // okay.
5556 return false;
5557 }
5558
5559 if (!NamedContext->isRecord()) {
5560 // Ideally this would point at the last name in the specifier,
5561 // but we don't have that level of source info.
5562 Diag(SS.getRange().getBegin(),
5563 diag::err_using_decl_nested_name_specifier_is_not_class)
5564 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5565 return true;
5566 }
5567
Douglas Gregor7c842292010-12-21 07:41:49 +00005568 if (!NamedContext->isDependentContext() &&
5569 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5570 return true;
5571
John McCall3969e302009-12-08 07:46:18 +00005572 if (getLangOptions().CPlusPlus0x) {
5573 // C++0x [namespace.udecl]p3:
5574 // In a using-declaration used as a member-declaration, the
5575 // nested-name-specifier shall name a base class of the class
5576 // being defined.
5577
5578 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5579 cast<CXXRecordDecl>(NamedContext))) {
5580 if (CurContext == NamedContext) {
5581 Diag(NameLoc,
5582 diag::err_using_decl_nested_name_specifier_is_current_class)
5583 << SS.getRange();
5584 return true;
5585 }
5586
5587 Diag(SS.getRange().getBegin(),
5588 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5589 << (NestedNameSpecifier*) SS.getScopeRep()
5590 << cast<CXXRecordDecl>(CurContext)
5591 << SS.getRange();
5592 return true;
5593 }
5594
5595 return false;
5596 }
5597
5598 // C++03 [namespace.udecl]p4:
5599 // A using-declaration used as a member-declaration shall refer
5600 // to a member of a base class of the class being defined [etc.].
5601
5602 // Salient point: SS doesn't have to name a base class as long as
5603 // lookup only finds members from base classes. Therefore we can
5604 // diagnose here only if we can prove that that can't happen,
5605 // i.e. if the class hierarchies provably don't intersect.
5606
5607 // TODO: it would be nice if "definitely valid" results were cached
5608 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5609 // need to be repeated.
5610
5611 struct UserData {
5612 llvm::DenseSet<const CXXRecordDecl*> Bases;
5613
5614 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5615 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5616 Data->Bases.insert(Base);
5617 return true;
5618 }
5619
5620 bool hasDependentBases(const CXXRecordDecl *Class) {
5621 return !Class->forallBases(collect, this);
5622 }
5623
5624 /// Returns true if the base is dependent or is one of the
5625 /// accumulated base classes.
5626 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5627 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5628 return !Data->Bases.count(Base);
5629 }
5630
5631 bool mightShareBases(const CXXRecordDecl *Class) {
5632 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5633 }
5634 };
5635
5636 UserData Data;
5637
5638 // Returns false if we find a dependent base.
5639 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5640 return false;
5641
5642 // Returns false if the class has a dependent base or if it or one
5643 // of its bases is present in the base set of the current context.
5644 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5645 return false;
5646
5647 Diag(SS.getRange().getBegin(),
5648 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5649 << (NestedNameSpecifier*) SS.getScopeRep()
5650 << cast<CXXRecordDecl>(CurContext)
5651 << SS.getRange();
5652
5653 return true;
John McCallb96ec562009-12-04 22:46:56 +00005654}
5655
Richard Smithdda56e42011-04-15 14:24:37 +00005656Decl *Sema::ActOnAliasDeclaration(Scope *S,
5657 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005658 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00005659 SourceLocation UsingLoc,
5660 UnqualifiedId &Name,
5661 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00005662 // Skip up to the relevant declaration scope.
5663 while (S->getFlags() & Scope::TemplateParamScope)
5664 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00005665 assert((S->getFlags() & Scope::DeclScope) &&
5666 "got alias-declaration outside of declaration scope");
5667
5668 if (Type.isInvalid())
5669 return 0;
5670
5671 bool Invalid = false;
5672 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5673 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00005674 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00005675
5676 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5677 return 0;
5678
5679 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005680 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00005681 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005682 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5683 TInfo->getTypeLoc().getBeginLoc());
5684 }
Richard Smithdda56e42011-04-15 14:24:37 +00005685
5686 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5687 LookupName(Previous, S);
5688
5689 // Warn about shadowing the name of a template parameter.
5690 if (Previous.isSingleResult() &&
5691 Previous.getFoundDecl()->isTemplateParameter()) {
5692 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5693 Previous.getFoundDecl()))
5694 Invalid = true;
5695 Previous.clear();
5696 }
5697
5698 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5699 "name in alias declaration must be an identifier");
5700 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5701 Name.StartLocation,
5702 Name.Identifier, TInfo);
5703
5704 NewTD->setAccess(AS);
5705
5706 if (Invalid)
5707 NewTD->setInvalidDecl();
5708
Richard Smith3f1b5d02011-05-05 21:57:07 +00005709 CheckTypedefForVariablyModifiedType(S, NewTD);
5710 Invalid |= NewTD->isInvalidDecl();
5711
Richard Smithdda56e42011-04-15 14:24:37 +00005712 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005713
5714 NamedDecl *NewND;
5715 if (TemplateParamLists.size()) {
5716 TypeAliasTemplateDecl *OldDecl = 0;
5717 TemplateParameterList *OldTemplateParams = 0;
5718
5719 if (TemplateParamLists.size() != 1) {
5720 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5721 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5722 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5723 }
5724 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5725
5726 // Only consider previous declarations in the same scope.
5727 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5728 /*ExplicitInstantiationOrSpecialization*/false);
5729 if (!Previous.empty()) {
5730 Redeclaration = true;
5731
5732 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5733 if (!OldDecl && !Invalid) {
5734 Diag(UsingLoc, diag::err_redefinition_different_kind)
5735 << Name.Identifier;
5736
5737 NamedDecl *OldD = Previous.getRepresentativeDecl();
5738 if (OldD->getLocation().isValid())
5739 Diag(OldD->getLocation(), diag::note_previous_definition);
5740
5741 Invalid = true;
5742 }
5743
5744 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5745 if (TemplateParameterListsAreEqual(TemplateParams,
5746 OldDecl->getTemplateParameters(),
5747 /*Complain=*/true,
5748 TPL_TemplateMatch))
5749 OldTemplateParams = OldDecl->getTemplateParameters();
5750 else
5751 Invalid = true;
5752
5753 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5754 if (!Invalid &&
5755 !Context.hasSameType(OldTD->getUnderlyingType(),
5756 NewTD->getUnderlyingType())) {
5757 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5758 // but we can't reasonably accept it.
5759 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5760 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5761 if (OldTD->getLocation().isValid())
5762 Diag(OldTD->getLocation(), diag::note_previous_definition);
5763 Invalid = true;
5764 }
5765 }
5766 }
5767
5768 // Merge any previous default template arguments into our parameters,
5769 // and check the parameter list.
5770 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5771 TPC_TypeAliasTemplate))
5772 return 0;
5773
5774 TypeAliasTemplateDecl *NewDecl =
5775 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5776 Name.Identifier, TemplateParams,
5777 NewTD);
5778
5779 NewDecl->setAccess(AS);
5780
5781 if (Invalid)
5782 NewDecl->setInvalidDecl();
5783 else if (OldDecl)
5784 NewDecl->setPreviousDeclaration(OldDecl);
5785
5786 NewND = NewDecl;
5787 } else {
5788 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5789 NewND = NewTD;
5790 }
Richard Smithdda56e42011-04-15 14:24:37 +00005791
5792 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00005793 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00005794
Richard Smith3f1b5d02011-05-05 21:57:07 +00005795 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00005796}
5797
John McCall48871652010-08-21 09:40:31 +00005798Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005799 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005800 SourceLocation AliasLoc,
5801 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005802 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005803 SourceLocation IdentLoc,
5804 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00005805
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005806 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005807 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5808 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005809
Anders Carlssondca83c42009-03-28 06:23:46 +00005810 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00005811 NamedDecl *PrevDecl
5812 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5813 ForRedeclaration);
5814 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5815 PrevDecl = 0;
5816
5817 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005818 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00005819 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005820 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00005821 // FIXME: At some point, we'll want to create the (redundant)
5822 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00005823 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00005824 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00005825 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005826 }
Mike Stump11289f42009-09-09 15:08:12 +00005827
Anders Carlssondca83c42009-03-28 06:23:46 +00005828 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5829 diag::err_redefinition_different_kind;
5830 Diag(AliasLoc, DiagID) << Alias;
5831 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00005832 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00005833 }
5834
John McCall27b18f82009-11-17 02:14:36 +00005835 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005836 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005837
John McCall9f3059a2009-10-09 21:13:30 +00005838 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005839 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5840 CTC_NoKeywords, 0)) {
5841 if (R.getAsSingle<NamespaceDecl>() ||
5842 R.getAsSingle<NamespaceAliasDecl>()) {
5843 if (DeclContext *DC = computeDeclContext(SS, false))
5844 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5845 << Ident << DC << Corrected << SS.getRange()
5846 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5847 else
5848 Diag(IdentLoc, diag::err_using_directive_suggest)
5849 << Ident << Corrected
5850 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5851
5852 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5853 << Corrected;
5854
5855 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00005856 } else {
5857 R.clear();
5858 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005859 }
5860 }
5861
5862 if (R.empty()) {
5863 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005864 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005865 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00005866 }
Mike Stump11289f42009-09-09 15:08:12 +00005867
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005868 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00005869 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00005870 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00005871 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00005872
John McCalld8d0d432010-02-16 06:53:13 +00005873 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00005874 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00005875}
5876
Douglas Gregora57478e2010-05-01 15:04:51 +00005877namespace {
5878 /// \brief Scoped object used to handle the state changes required in Sema
5879 /// to implicitly define the body of a C++ member function;
5880 class ImplicitlyDefinedFunctionScope {
5881 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00005882 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00005883
5884 public:
5885 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00005886 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00005887 {
Douglas Gregora57478e2010-05-01 15:04:51 +00005888 S.PushFunctionScope();
5889 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5890 }
5891
5892 ~ImplicitlyDefinedFunctionScope() {
5893 S.PopExpressionEvaluationContext();
5894 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00005895 }
5896 };
5897}
5898
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005899Sema::ImplicitExceptionSpecification
5900Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00005901 // C++ [except.spec]p14:
5902 // An implicitly declared special member function (Clause 12) shall have an
5903 // exception-specification. [...]
5904 ImplicitExceptionSpecification ExceptSpec(Context);
5905
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005906 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005907 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5908 BEnd = ClassDecl->bases_end();
5909 B != BEnd; ++B) {
5910 if (B->isVirtual()) // Handled below.
5911 continue;
5912
Douglas Gregor9672f922010-07-03 00:47:00 +00005913 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5914 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005915 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5916 // If this is a deleted function, add it anyway. This might be conformant
5917 // with the standard. This might not. I'm not sure. It might not matter.
5918 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005919 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005920 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005921 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005922
5923 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005924 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5925 BEnd = ClassDecl->vbases_end();
5926 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00005927 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5928 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005929 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
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 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005933 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005934 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005935 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005936
5937 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005938 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5939 FEnd = ClassDecl->field_end();
5940 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00005941 if (F->hasInClassInitializer()) {
5942 if (Expr *E = F->getInClassInitializer())
5943 ExceptSpec.CalledExpr(E);
5944 else if (!F->isInvalidDecl())
5945 ExceptSpec.SetDelayed();
5946 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00005947 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00005948 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5949 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5950 // If this is a deleted function, add it anyway. This might be conformant
5951 // with the standard. This might not. I'm not sure. It might not matter.
5952 // In particular, the problem is that this function never gets called. It
5953 // might just be ill-formed because this function attempts to refer to
5954 // a deleted function here.
5955 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005956 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005957 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005958 }
John McCalldb40c7f2010-12-14 08:05:40 +00005959
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005960 return ExceptSpec;
5961}
5962
5963CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5964 CXXRecordDecl *ClassDecl) {
5965 // C++ [class.ctor]p5:
5966 // A default constructor for a class X is a constructor of class X
5967 // that can be called without an argument. If there is no
5968 // user-declared constructor for class X, a default constructor is
5969 // implicitly declared. An implicitly-declared default constructor
5970 // is an inline public member of its class.
5971 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5972 "Should not build implicit default constructor!");
5973
5974 ImplicitExceptionSpecification Spec =
5975 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5976 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005977
Douglas Gregor6d880b12010-07-01 22:31:05 +00005978 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005979 CanQualType ClassType
5980 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005981 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005982 DeclarationName Name
5983 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005984 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005985 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00005986 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005987 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005988 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005989 /*TInfo=*/0,
5990 /*isExplicit=*/false,
5991 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005992 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005993 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00005994 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005995 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00005996 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00005997
5998 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00005999 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6000
Douglas Gregor0be31a22010-07-02 17:43:08 +00006001 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00006002 PushOnScopeChains(DefaultCon, S, false);
6003 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00006004
6005 if (ShouldDeleteDefaultConstructor(DefaultCon))
6006 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00006007
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006008 return DefaultCon;
6009}
6010
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006011void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6012 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006013 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006014 !Constructor->doesThisDeclarationHaveABody() &&
6015 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006016 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006017
Anders Carlsson423f5d82010-04-23 16:04:08 +00006018 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006019 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006020
Douglas Gregora57478e2010-05-01 15:04:51 +00006021 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006022 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006023 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006024 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006025 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006026 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006027 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006028 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006029 }
Douglas Gregor73193272010-09-20 16:48:21 +00006030
6031 SourceLocation Loc = Constructor->getLocation();
6032 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6033
6034 Constructor->setUsed();
6035 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006036
6037 if (ASTMutationListener *L = getASTMutationListener()) {
6038 L->CompletedImplicitDefinition(Constructor);
6039 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006040}
6041
Richard Smith938f40b2011-06-11 17:19:42 +00006042/// Get any existing defaulted default constructor for the given class. Do not
6043/// implicitly define one if it does not exist.
6044static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6045 CXXRecordDecl *D) {
6046 ASTContext &Context = Self.Context;
6047 QualType ClassType = Context.getTypeDeclType(D);
6048 DeclarationName ConstructorName
6049 = Context.DeclarationNames.getCXXConstructorName(
6050 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6051
6052 DeclContext::lookup_const_iterator Con, ConEnd;
6053 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6054 Con != ConEnd; ++Con) {
6055 // A function template cannot be defaulted.
6056 if (isa<FunctionTemplateDecl>(*Con))
6057 continue;
6058
6059 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6060 if (Constructor->isDefaultConstructor())
6061 return Constructor->isDefaulted() ? Constructor : 0;
6062 }
6063 return 0;
6064}
6065
6066void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6067 if (!D) return;
6068 AdjustDeclIfTemplate(D);
6069
6070 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6071 CXXConstructorDecl *CtorDecl
6072 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6073
6074 if (!CtorDecl) return;
6075
6076 // Compute the exception specification for the default constructor.
6077 const FunctionProtoType *CtorTy =
6078 CtorDecl->getType()->castAs<FunctionProtoType>();
6079 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6080 ImplicitExceptionSpecification Spec =
6081 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6082 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6083 assert(EPI.ExceptionSpecType != EST_Delayed);
6084
6085 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6086 }
6087
6088 // If the default constructor is explicitly defaulted, checking the exception
6089 // specification is deferred until now.
6090 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6091 !ClassDecl->isDependentType())
6092 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6093}
6094
Sebastian Redl08905022011-02-05 19:23:19 +00006095void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6096 // We start with an initial pass over the base classes to collect those that
6097 // inherit constructors from. If there are none, we can forgo all further
6098 // processing.
6099 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6100 BasesVector BasesToInheritFrom;
6101 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6102 BaseE = ClassDecl->bases_end();
6103 BaseIt != BaseE; ++BaseIt) {
6104 if (BaseIt->getInheritConstructors()) {
6105 QualType Base = BaseIt->getType();
6106 if (Base->isDependentType()) {
6107 // If we inherit constructors from anything that is dependent, just
6108 // abort processing altogether. We'll get another chance for the
6109 // instantiations.
6110 return;
6111 }
6112 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6113 }
6114 }
6115 if (BasesToInheritFrom.empty())
6116 return;
6117
6118 // Now collect the constructors that we already have in the current class.
6119 // Those take precedence over inherited constructors.
6120 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6121 // unless there is a user-declared constructor with the same signature in
6122 // the class where the using-declaration appears.
6123 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6124 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6125 CtorE = ClassDecl->ctor_end();
6126 CtorIt != CtorE; ++CtorIt) {
6127 ExistingConstructors.insert(
6128 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6129 }
6130
6131 Scope *S = getScopeForContext(ClassDecl);
6132 DeclarationName CreatedCtorName =
6133 Context.DeclarationNames.getCXXConstructorName(
6134 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6135
6136 // Now comes the true work.
6137 // First, we keep a map from constructor types to the base that introduced
6138 // them. Needed for finding conflicting constructors. We also keep the
6139 // actually inserted declarations in there, for pretty diagnostics.
6140 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6141 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6142 ConstructorToSourceMap InheritedConstructors;
6143 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6144 BaseE = BasesToInheritFrom.end();
6145 BaseIt != BaseE; ++BaseIt) {
6146 const RecordType *Base = *BaseIt;
6147 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6148 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6149 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6150 CtorE = BaseDecl->ctor_end();
6151 CtorIt != CtorE; ++CtorIt) {
6152 // Find the using declaration for inheriting this base's constructors.
6153 DeclarationName Name =
6154 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6155 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6156 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6157 SourceLocation UsingLoc = UD ? UD->getLocation() :
6158 ClassDecl->getLocation();
6159
6160 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6161 // from the class X named in the using-declaration consists of actual
6162 // constructors and notional constructors that result from the
6163 // transformation of defaulted parameters as follows:
6164 // - all non-template default constructors of X, and
6165 // - for each non-template constructor of X that has at least one
6166 // parameter with a default argument, the set of constructors that
6167 // results from omitting any ellipsis parameter specification and
6168 // successively omitting parameters with a default argument from the
6169 // end of the parameter-type-list.
6170 CXXConstructorDecl *BaseCtor = *CtorIt;
6171 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6172 const FunctionProtoType *BaseCtorType =
6173 BaseCtor->getType()->getAs<FunctionProtoType>();
6174
6175 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6176 maxParams = BaseCtor->getNumParams();
6177 params <= maxParams; ++params) {
6178 // Skip default constructors. They're never inherited.
6179 if (params == 0)
6180 continue;
6181 // Skip copy and move constructors for the same reason.
6182 if (CanBeCopyOrMove && params == 1)
6183 continue;
6184
6185 // Build up a function type for this particular constructor.
6186 // FIXME: The working paper does not consider that the exception spec
6187 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00006188 // source. This code doesn't yet, either. When it does, this code will
6189 // need to be delayed until after exception specifications and in-class
6190 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00006191 const Type *NewCtorType;
6192 if (params == maxParams)
6193 NewCtorType = BaseCtorType;
6194 else {
6195 llvm::SmallVector<QualType, 16> Args;
6196 for (unsigned i = 0; i < params; ++i) {
6197 Args.push_back(BaseCtorType->getArgType(i));
6198 }
6199 FunctionProtoType::ExtProtoInfo ExtInfo =
6200 BaseCtorType->getExtProtoInfo();
6201 ExtInfo.Variadic = false;
6202 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6203 Args.data(), params, ExtInfo)
6204 .getTypePtr();
6205 }
6206 const Type *CanonicalNewCtorType =
6207 Context.getCanonicalType(NewCtorType);
6208
6209 // Now that we have the type, first check if the class already has a
6210 // constructor with this signature.
6211 if (ExistingConstructors.count(CanonicalNewCtorType))
6212 continue;
6213
6214 // Then we check if we have already declared an inherited constructor
6215 // with this signature.
6216 std::pair<ConstructorToSourceMap::iterator, bool> result =
6217 InheritedConstructors.insert(std::make_pair(
6218 CanonicalNewCtorType,
6219 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6220 if (!result.second) {
6221 // Already in the map. If it came from a different class, that's an
6222 // error. Not if it's from the same.
6223 CanQualType PreviousBase = result.first->second.first;
6224 if (CanonicalBase != PreviousBase) {
6225 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6226 const CXXConstructorDecl *PrevBaseCtor =
6227 PrevCtor->getInheritedConstructor();
6228 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6229
6230 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6231 Diag(BaseCtor->getLocation(),
6232 diag::note_using_decl_constructor_conflict_current_ctor);
6233 Diag(PrevBaseCtor->getLocation(),
6234 diag::note_using_decl_constructor_conflict_previous_ctor);
6235 Diag(PrevCtor->getLocation(),
6236 diag::note_using_decl_constructor_conflict_previous_using);
6237 }
6238 continue;
6239 }
6240
6241 // OK, we're there, now add the constructor.
6242 // C++0x [class.inhctor]p8: [...] that would be performed by a
6243 // user-writtern inline constructor [...]
6244 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6245 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006246 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6247 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006248 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00006249 NewCtor->setAccess(BaseCtor->getAccess());
6250
6251 // Build up the parameter decls and add them.
6252 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6253 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006254 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6255 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006256 /*IdentifierInfo=*/0,
6257 BaseCtorType->getArgType(i),
6258 /*TInfo=*/0, SC_None,
6259 SC_None, /*DefaultArg=*/0));
6260 }
6261 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6262 NewCtor->setInheritedConstructor(BaseCtor);
6263
6264 PushOnScopeChains(NewCtor, S, false);
6265 ClassDecl->addDecl(NewCtor);
6266 result.first->second.second = NewCtor;
6267 }
6268 }
6269 }
6270}
6271
Alexis Huntf91729462011-05-12 22:46:25 +00006272Sema::ImplicitExceptionSpecification
6273Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006274 // C++ [except.spec]p14:
6275 // An implicitly declared special member function (Clause 12) shall have
6276 // an exception-specification.
6277 ImplicitExceptionSpecification ExceptSpec(Context);
6278
6279 // Direct base-class destructors.
6280 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6281 BEnd = ClassDecl->bases_end();
6282 B != BEnd; ++B) {
6283 if (B->isVirtual()) // Handled below.
6284 continue;
6285
6286 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6287 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006288 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006289 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006290
Douglas Gregorf1203042010-07-01 19:09:28 +00006291 // Virtual base-class destructors.
6292 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6293 BEnd = ClassDecl->vbases_end();
6294 B != BEnd; ++B) {
6295 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6296 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006297 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006298 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006299
Douglas Gregorf1203042010-07-01 19:09:28 +00006300 // Field destructors.
6301 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6302 FEnd = ClassDecl->field_end();
6303 F != FEnd; ++F) {
6304 if (const RecordType *RecordTy
6305 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6306 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006307 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006308 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006309
Alexis Huntf91729462011-05-12 22:46:25 +00006310 return ExceptSpec;
6311}
6312
6313CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6314 // C++ [class.dtor]p2:
6315 // If a class has no user-declared destructor, a destructor is
6316 // declared implicitly. An implicitly-declared destructor is an
6317 // inline public member of its class.
6318
6319 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006320 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006321 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6322
Douglas Gregor7454c562010-07-02 20:37:36 +00006323 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006324 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006325
Douglas Gregorf1203042010-07-01 19:09:28 +00006326 CanQualType ClassType
6327 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006328 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006329 DeclarationName Name
6330 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006331 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006332 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006333 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6334 /*isInline=*/true,
6335 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006336 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006337 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006338 Destructor->setImplicit();
6339 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006340
6341 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006342 ++ASTContext::NumImplicitDestructorsDeclared;
6343
6344 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006345 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006346 PushOnScopeChains(Destructor, S, false);
6347 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006348
6349 // This could be uniqued if it ever proves significant.
6350 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006351
6352 if (ShouldDeleteDestructor(Destructor))
6353 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006354
6355 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006356
Douglas Gregorf1203042010-07-01 19:09:28 +00006357 return Destructor;
6358}
6359
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006360void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006361 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006362 assert((Destructor->isDefaulted() &&
6363 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006364 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006365 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006366 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006367
Douglas Gregor54818f02010-05-12 16:39:35 +00006368 if (Destructor->isInvalidDecl())
6369 return;
6370
Douglas Gregora57478e2010-05-01 15:04:51 +00006371 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006372
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006373 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006374 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6375 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006376
Douglas Gregor54818f02010-05-12 16:39:35 +00006377 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006378 Diag(CurrentLocation, diag::note_member_synthesized_at)
6379 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6380
6381 Destructor->setInvalidDecl();
6382 return;
6383 }
6384
Douglas Gregor73193272010-09-20 16:48:21 +00006385 SourceLocation Loc = Destructor->getLocation();
6386 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6387
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006388 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006389 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006390
6391 if (ASTMutationListener *L = getASTMutationListener()) {
6392 L->CompletedImplicitDefinition(Destructor);
6393 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006394}
6395
Sebastian Redl623ea822011-05-19 05:13:44 +00006396void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6397 CXXDestructorDecl *destructor) {
6398 // C++11 [class.dtor]p3:
6399 // A declaration of a destructor that does not have an exception-
6400 // specification is implicitly considered to have the same exception-
6401 // specification as an implicit declaration.
6402 const FunctionProtoType *dtorType = destructor->getType()->
6403 getAs<FunctionProtoType>();
6404 if (dtorType->hasExceptionSpec())
6405 return;
6406
6407 ImplicitExceptionSpecification exceptSpec =
6408 ComputeDefaultedDtorExceptionSpec(classDecl);
6409
6410 // Replace the destructor's type.
6411 FunctionProtoType::ExtProtoInfo epi;
6412 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6413 epi.NumExceptions = exceptSpec.size();
6414 epi.Exceptions = exceptSpec.data();
6415 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6416
6417 destructor->setType(ty);
6418
6419 // FIXME: If the destructor has a body that could throw, and the newly created
6420 // spec doesn't allow exceptions, we should emit a warning, because this
6421 // change in behavior can break conforming C++03 programs at runtime.
6422 // However, we don't have a body yet, so it needs to be done somewhere else.
6423}
6424
Douglas Gregorb139cd52010-05-01 20:49:11 +00006425/// \brief Builds a statement that copies the given entity from \p From to
6426/// \c To.
6427///
6428/// This routine is used to copy the members of a class with an
6429/// implicitly-declared copy assignment operator. When the entities being
6430/// copied are arrays, this routine builds for loops to copy them.
6431///
6432/// \param S The Sema object used for type-checking.
6433///
6434/// \param Loc The location where the implicit copy is being generated.
6435///
6436/// \param T The type of the expressions being copied. Both expressions must
6437/// have this type.
6438///
6439/// \param To The expression we are copying to.
6440///
6441/// \param From The expression we are copying from.
6442///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006443/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6444/// Otherwise, it's a non-static member subobject.
6445///
Douglas Gregorb139cd52010-05-01 20:49:11 +00006446/// \param Depth Internal parameter recording the depth of the recursion.
6447///
6448/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00006449static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00006450BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00006451 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006452 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006453 // C++0x [class.copy]p30:
6454 // Each subobject is assigned in the manner appropriate to its type:
6455 //
6456 // - if the subobject is of class type, the copy assignment operator
6457 // for the class is used (as if by explicit qualification; that is,
6458 // ignoring any possible virtual overriding functions in more derived
6459 // classes);
6460 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6461 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6462
6463 // Look for operator=.
6464 DeclarationName Name
6465 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6466 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6467 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6468
6469 // Filter out any result that isn't a copy-assignment operator.
6470 LookupResult::Filter F = OpLookup.makeFilter();
6471 while (F.hasNext()) {
6472 NamedDecl *D = F.next();
6473 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6474 if (Method->isCopyAssignmentOperator())
6475 continue;
6476
6477 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00006478 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006479 F.done();
6480
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006481 // Suppress the protected check (C++ [class.protected]) for each of the
6482 // assignment operators we found. This strange dance is required when
6483 // we're assigning via a base classes's copy-assignment operator. To
6484 // ensure that we're getting the right base class subobject (without
6485 // ambiguities), we need to cast "this" to that subobject type; to
6486 // ensure that we don't go through the virtual call mechanism, we need
6487 // to qualify the operator= name with the base class (see below). However,
6488 // this means that if the base class has a protected copy assignment
6489 // operator, the protected member access check will fail. So, we
6490 // rewrite "protected" access to "public" access in this case, since we
6491 // know by construction that we're calling from a derived class.
6492 if (CopyingBaseSubobject) {
6493 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6494 L != LEnd; ++L) {
6495 if (L.getAccess() == AS_protected)
6496 L.setAccess(AS_public);
6497 }
6498 }
6499
Douglas Gregorb139cd52010-05-01 20:49:11 +00006500 // Create the nested-name-specifier that will be used to qualify the
6501 // reference to operator=; this is required to suppress the virtual
6502 // call mechanism.
6503 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006504 SS.MakeTrivial(S.Context,
6505 NestedNameSpecifier::Create(S.Context, 0, false,
6506 T.getTypePtr()),
6507 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006508
6509 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00006510 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00006511 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006512 /*FirstQualifierInScope=*/0, OpLookup,
6513 /*TemplateArgs=*/0,
6514 /*SuppressQualifierCheck=*/true);
6515 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006516 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006517
6518 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00006519
John McCalldadc5752010-08-24 06:29:42 +00006520 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006521 OpEqualRef.takeAs<Expr>(),
6522 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006523 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006524 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006525
6526 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006527 }
John McCallab8c2732010-03-16 06:11:48 +00006528
Douglas Gregorb139cd52010-05-01 20:49:11 +00006529 // - if the subobject is of scalar type, the built-in assignment
6530 // operator is used.
6531 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6532 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00006533 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006534 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006535 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006536
6537 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006538 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006539
6540 // - if the subobject is an array, each element is assigned, in the
6541 // manner appropriate to the element type;
6542
6543 // Construct a loop over the array bounds, e.g.,
6544 //
6545 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6546 //
6547 // that will copy each of the array elements.
6548 QualType SizeType = S.Context.getSizeType();
6549
6550 // Create the iteration variable.
6551 IdentifierInfo *IterationVarName = 0;
6552 {
6553 llvm::SmallString<8> Str;
6554 llvm::raw_svector_ostream OS(Str);
6555 OS << "__i" << Depth;
6556 IterationVarName = &S.Context.Idents.get(OS.str());
6557 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00006558 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006559 IterationVarName, SizeType,
6560 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006561 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006562
6563 // Initialize the iteration variable to zero.
6564 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006565 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006566
6567 // Create a reference to the iteration variable; we'll use this several
6568 // times throughout.
6569 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00006570 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006571 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6572
6573 // Create the DeclStmt that holds the iteration variable.
6574 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6575
6576 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006577 llvm::APInt Upper
6578 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00006579 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00006580 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00006581 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6582 BO_NE, S.Context.BoolTy,
6583 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006584
6585 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006586 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00006587 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6588 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006589
6590 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006591 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6592 IterationVarRef, Loc));
6593 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6594 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006595
6596 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00006597 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6598 To, From, CopyingBaseSubobject,
6599 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00006600 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006601 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006602
6603 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00006604 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006605 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00006606 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00006607 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006608}
6609
Alexis Hunt119f3652011-05-14 05:23:20 +00006610std::pair<Sema::ImplicitExceptionSpecification, bool>
6611Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6612 CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006613 // C++ [class.copy]p10:
6614 // If the class definition does not explicitly declare a copy
6615 // assignment operator, one is declared implicitly.
6616 // The implicitly-defined copy assignment operator for a class X
6617 // will have the form
6618 //
6619 // X& X::operator=(const X&)
6620 //
6621 // if
6622 bool HasConstCopyAssignment = true;
6623
6624 // -- each direct base class B of X has a copy assignment operator
6625 // whose parameter is of type const B&, const volatile B& or B,
6626 // and
6627 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6628 BaseEnd = ClassDecl->bases_end();
6629 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00006630 // We'll handle this below
6631 if (LangOpts.CPlusPlus0x && Base->isVirtual())
6632 continue;
6633
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006634 assert(!Base->getType()->isDependentType() &&
6635 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00006636 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6637 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6638 &HasConstCopyAssignment);
6639 }
6640
6641 // In C++0x, the above citation has "or virtual added"
6642 if (LangOpts.CPlusPlus0x) {
6643 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6644 BaseEnd = ClassDecl->vbases_end();
6645 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6646 assert(!Base->getType()->isDependentType() &&
6647 "Cannot generate implicit members for class with dependent bases.");
6648 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6649 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6650 &HasConstCopyAssignment);
6651 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006652 }
6653
6654 // -- for all the nonstatic data members of X that are of a class
6655 // type M (or array thereof), each such class type has a copy
6656 // assignment operator whose parameter is of type const M&,
6657 // const volatile M& or M.
6658 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6659 FieldEnd = ClassDecl->field_end();
6660 HasConstCopyAssignment && Field != FieldEnd;
6661 ++Field) {
6662 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00006663 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6664 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
6665 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006666 }
6667 }
6668
6669 // Otherwise, the implicitly declared copy assignment operator will
6670 // have the form
6671 //
6672 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006673
Douglas Gregor68e11362010-07-01 17:48:08 +00006674 // C++ [except.spec]p14:
6675 // An implicitly declared special member function (Clause 12) shall have an
6676 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00006677
6678 // It is unspecified whether or not an implicit copy assignment operator
6679 // attempts to deduplicate calls to assignment operators of virtual bases are
6680 // made. As such, this exception specification is effectively unspecified.
6681 // Based on a similar decision made for constness in C++0x, we're erring on
6682 // the side of assuming such calls to be made regardless of whether they
6683 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00006684 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00006685 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00006686 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6687 BaseEnd = ClassDecl->bases_end();
6688 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00006689 if (Base->isVirtual())
6690 continue;
6691
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006692 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006693 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00006694 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6695 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00006696 ExceptSpec.CalledDecl(CopyAssign);
6697 }
Alexis Hunt491ec602011-06-21 23:42:56 +00006698
6699 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6700 BaseEnd = ClassDecl->vbases_end();
6701 Base != BaseEnd; ++Base) {
6702 CXXRecordDecl *BaseClassDecl
6703 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6704 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6705 ArgQuals, false, 0))
6706 ExceptSpec.CalledDecl(CopyAssign);
6707 }
6708
Douglas Gregor68e11362010-07-01 17:48:08 +00006709 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6710 FieldEnd = ClassDecl->field_end();
6711 Field != FieldEnd;
6712 ++Field) {
6713 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00006714 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6715 if (CXXMethodDecl *CopyAssign =
6716 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
6717 ExceptSpec.CalledDecl(CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00006718 }
6719 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006720
Alexis Hunt119f3652011-05-14 05:23:20 +00006721 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6722}
6723
6724CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6725 // Note: The following rules are largely analoguous to the copy
6726 // constructor rules. Note that virtual bases are not taken into account
6727 // for determining the argument type of the operator. Note also that
6728 // operators taking an object instead of a reference are allowed.
6729
6730 ImplicitExceptionSpecification Spec(Context);
6731 bool Const;
6732 llvm::tie(Spec, Const) =
6733 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6734
6735 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6736 QualType RetType = Context.getLValueReferenceType(ArgType);
6737 if (Const)
6738 ArgType = ArgType.withConst();
6739 ArgType = Context.getLValueReferenceType(ArgType);
6740
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006741 // An implicitly-declared copy assignment operator is an inline public
6742 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00006743 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006744 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006745 SourceLocation ClassLoc = ClassDecl->getLocation();
6746 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006747 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00006748 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00006749 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006750 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00006751 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00006752 /*isInline=*/true,
6753 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006754 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00006755 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006756 CopyAssignment->setImplicit();
6757 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006758
6759 // Add the parameter to the operator.
6760 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006761 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006762 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006763 SC_None,
6764 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006765 CopyAssignment->setParams(&FromParam, 1);
6766
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006767 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006768 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00006769
Douglas Gregor0be31a22010-07-02 17:43:08 +00006770 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006771 PushOnScopeChains(CopyAssignment, S, false);
6772 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006773
Alexis Huntd74c85f2011-06-22 01:05:13 +00006774 // C++0x [class.copy]p18:
6775 // ... If the class definition declares a move constructor or move
6776 // assignment operator, the implicitly declared copy assignment operator is
6777 // defined as deleted; ...
6778 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
6779 ClassDecl->hasUserDeclaredMoveAssignment() ||
6780 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00006781 CopyAssignment->setDeletedAsWritten();
6782
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006783 AddOverriddenMethods(ClassDecl, CopyAssignment);
6784 return CopyAssignment;
6785}
6786
Douglas Gregorb139cd52010-05-01 20:49:11 +00006787void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6788 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00006789 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006790 CopyAssignOperator->isOverloadedOperator() &&
6791 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006792 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006793 "DefineImplicitCopyAssignment called for wrong function");
6794
6795 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6796
6797 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6798 CopyAssignOperator->setInvalidDecl();
6799 return;
6800 }
6801
6802 CopyAssignOperator->setUsed();
6803
6804 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006805 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006806
6807 // C++0x [class.copy]p30:
6808 // The implicitly-defined or explicitly-defaulted copy assignment operator
6809 // for a non-union class X performs memberwise copy assignment of its
6810 // subobjects. The direct base classes of X are assigned first, in the
6811 // order of their declaration in the base-specifier-list, and then the
6812 // immediate non-static data members of X are assigned, in the order in
6813 // which they were declared in the class definition.
6814
6815 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00006816 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006817
6818 // The parameter for the "other" object, which we are copying from.
6819 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6820 Qualifiers OtherQuals = Other->getType().getQualifiers();
6821 QualType OtherRefType = Other->getType();
6822 if (const LValueReferenceType *OtherRef
6823 = OtherRefType->getAs<LValueReferenceType>()) {
6824 OtherRefType = OtherRef->getPointeeType();
6825 OtherQuals = OtherRefType.getQualifiers();
6826 }
6827
6828 // Our location for everything implicitly-generated.
6829 SourceLocation Loc = CopyAssignOperator->getLocation();
6830
6831 // Construct a reference to the "other" object. We'll be using this
6832 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00006833 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006834 assert(OtherRef && "Reference to parameter cannot fail!");
6835
6836 // Construct the "this" pointer. We'll be using this throughout the generated
6837 // ASTs.
6838 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6839 assert(This && "Reference to this cannot fail!");
6840
6841 // Assign base classes.
6842 bool Invalid = false;
6843 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6844 E = ClassDecl->bases_end(); Base != E; ++Base) {
6845 // Form the assignment:
6846 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6847 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00006848 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006849 Invalid = true;
6850 continue;
6851 }
6852
John McCallcf142162010-08-07 06:22:56 +00006853 CXXCastPath BasePath;
6854 BasePath.push_back(Base);
6855
Douglas Gregorb139cd52010-05-01 20:49:11 +00006856 // Construct the "from" expression, which is an implicit cast to the
6857 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00006858 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00006859 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6860 CK_UncheckedDerivedToBase,
6861 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006862
6863 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00006864 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006865
6866 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00006867 To = ImpCastExprToType(To.take(),
6868 Context.getCVRQualifiedType(BaseType,
6869 CopyAssignOperator->getTypeQualifiers()),
6870 CK_UncheckedDerivedToBase,
6871 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006872
6873 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00006874 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00006875 To.get(), From,
6876 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006877 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006878 Diag(CurrentLocation, diag::note_member_synthesized_at)
6879 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6880 CopyAssignOperator->setInvalidDecl();
6881 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006882 }
6883
6884 // Success! Record the copy.
6885 Statements.push_back(Copy.takeAs<Expr>());
6886 }
6887
6888 // \brief Reference to the __builtin_memcpy function.
6889 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006890 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006891 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006892
6893 // Assign non-static members.
6894 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6895 FieldEnd = ClassDecl->field_end();
6896 Field != FieldEnd; ++Field) {
6897 // Check for members of reference type; we can't copy those.
6898 if (Field->getType()->isReferenceType()) {
6899 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6900 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6901 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006902 Diag(CurrentLocation, diag::note_member_synthesized_at)
6903 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006904 Invalid = true;
6905 continue;
6906 }
6907
6908 // Check for members of const-qualified, non-class type.
6909 QualType BaseType = Context.getBaseElementType(Field->getType());
6910 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6911 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6912 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6913 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006914 Diag(CurrentLocation, diag::note_member_synthesized_at)
6915 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006916 Invalid = true;
6917 continue;
6918 }
John McCall1b1a1db2011-06-17 00:18:42 +00006919
6920 // Suppress assigning zero-width bitfields.
6921 if (const Expr *Width = Field->getBitWidth())
6922 if (Width->EvaluateAsInt(Context) == 0)
6923 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006924
6925 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00006926 if (FieldType->isIncompleteArrayType()) {
6927 assert(ClassDecl->hasFlexibleArrayMember() &&
6928 "Incomplete array type is not valid");
6929 continue;
6930 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006931
6932 // Build references to the field in the object we're copying from and to.
6933 CXXScopeSpec SS; // Intentionally empty
6934 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6935 LookupMemberName);
6936 MemberLookup.addDecl(*Field);
6937 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00006938 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00006939 Loc, /*IsArrow=*/false,
6940 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00006941 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00006942 Loc, /*IsArrow=*/true,
6943 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006944 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6945 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6946
6947 // If the field should be copied with __builtin_memcpy rather than via
6948 // explicit assignments, do so. This optimization only applies for arrays
6949 // of scalars and arrays of class type with trivial copy-assignment
6950 // operators.
John McCall31168b02011-06-15 23:02:42 +00006951 if (FieldType->isArrayType() &&
6952 BaseType.hasTrivialCopyAssignment(Context)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006953 // Compute the size of the memory buffer to be copied.
6954 QualType SizeType = Context.getSizeType();
6955 llvm::APInt Size(Context.getTypeSize(SizeType),
6956 Context.getTypeSizeInChars(BaseType).getQuantity());
6957 for (const ConstantArrayType *Array
6958 = Context.getAsConstantArrayType(FieldType);
6959 Array;
6960 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00006961 llvm::APInt ArraySize
6962 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006963 Size *= ArraySize;
6964 }
6965
6966 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00006967 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6968 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006969
6970 bool NeedsCollectableMemCpy =
6971 (BaseType->isRecordType() &&
6972 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6973
6974 if (NeedsCollectableMemCpy) {
6975 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006976 // Create a reference to the __builtin_objc_memmove_collectable function.
6977 LookupResult R(*this,
6978 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006979 Loc, LookupOrdinaryName);
6980 LookupName(R, TUScope, true);
6981
6982 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6983 if (!CollectableMemCpy) {
6984 // Something went horribly wrong earlier, and we will have
6985 // complained about it.
6986 Invalid = true;
6987 continue;
6988 }
6989
6990 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6991 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006992 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006993 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6994 }
6995 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006996 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006997 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006998 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6999 LookupOrdinaryName);
7000 LookupName(R, TUScope, true);
7001
7002 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7003 if (!BuiltinMemCpy) {
7004 // Something went horribly wrong earlier, and we will have complained
7005 // about it.
7006 Invalid = true;
7007 continue;
7008 }
7009
7010 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7011 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007012 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007013 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7014 }
7015
John McCall37ad5512010-08-23 06:44:23 +00007016 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007017 CallArgs.push_back(To.takeAs<Expr>());
7018 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007019 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00007020 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007021 if (NeedsCollectableMemCpy)
7022 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007023 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007024 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007025 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007026 else
7027 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007028 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007029 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007030 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007031
Douglas Gregorb139cd52010-05-01 20:49:11 +00007032 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7033 Statements.push_back(Call.takeAs<Expr>());
7034 continue;
7035 }
7036
7037 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00007038 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00007039 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007040 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007041 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007042 Diag(CurrentLocation, diag::note_member_synthesized_at)
7043 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7044 CopyAssignOperator->setInvalidDecl();
7045 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007046 }
7047
7048 // Success! Record the copy.
7049 Statements.push_back(Copy.takeAs<Stmt>());
7050 }
7051
7052 if (!Invalid) {
7053 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007054 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007055
John McCalldadc5752010-08-24 06:29:42 +00007056 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007057 if (Return.isInvalid())
7058 Invalid = true;
7059 else {
7060 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007061
7062 if (Trap.hasErrorOccurred()) {
7063 Diag(CurrentLocation, diag::note_member_synthesized_at)
7064 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7065 Invalid = true;
7066 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007067 }
7068 }
7069
7070 if (Invalid) {
7071 CopyAssignOperator->setInvalidDecl();
7072 return;
7073 }
7074
John McCalldadc5752010-08-24 06:29:42 +00007075 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007076 /*isStmtExpr=*/false);
7077 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7078 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007079
7080 if (ASTMutationListener *L = getASTMutationListener()) {
7081 L->CompletedImplicitDefinition(CopyAssignOperator);
7082 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007083}
7084
Alexis Hunt913820d2011-05-13 06:10:58 +00007085std::pair<Sema::ImplicitExceptionSpecification, bool>
7086Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00007087 // C++ [class.copy]p5:
7088 // The implicitly-declared copy constructor for a class X will
7089 // have the form
7090 //
7091 // X::X(const X&)
7092 //
7093 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00007094 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00007095 bool HasConstCopyConstructor = true;
7096
7097 // -- each direct or virtual base class B of X has a copy
7098 // constructor whose first parameter is of type const B& or
7099 // const volatile B&, and
7100 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7101 BaseEnd = ClassDecl->bases_end();
7102 HasConstCopyConstructor && Base != BaseEnd;
7103 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007104 // Virtual bases are handled below.
7105 if (Base->isVirtual())
7106 continue;
7107
Douglas Gregora6d69502010-07-02 23:41:54 +00007108 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007109 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007110 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7111 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00007112 }
7113
7114 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7115 BaseEnd = ClassDecl->vbases_end();
7116 HasConstCopyConstructor && Base != BaseEnd;
7117 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007118 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00007119 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007120 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7121 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007122 }
7123
7124 // -- for all the nonstatic data members of X that are of a
7125 // class type M (or array thereof), each such class type
7126 // has a copy constructor whose first parameter is of type
7127 // const M& or const volatile M&.
7128 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7129 FieldEnd = ClassDecl->field_end();
7130 HasConstCopyConstructor && Field != FieldEnd;
7131 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007132 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007133 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007134 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
7135 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007136 }
7137 }
Douglas Gregor54be3392010-07-01 17:57:27 +00007138 // Otherwise, the implicitly declared copy constructor will have
7139 // the form
7140 //
7141 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00007142
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007143 // C++ [except.spec]p14:
7144 // An implicitly declared special member function (Clause 12) shall have an
7145 // exception-specification. [...]
7146 ImplicitExceptionSpecification ExceptSpec(Context);
7147 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7148 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7149 BaseEnd = ClassDecl->bases_end();
7150 Base != BaseEnd;
7151 ++Base) {
7152 // Virtual bases are handled below.
7153 if (Base->isVirtual())
7154 continue;
7155
Douglas Gregora6d69502010-07-02 23:41:54 +00007156 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007157 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007158 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007159 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007160 ExceptSpec.CalledDecl(CopyConstructor);
7161 }
7162 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7163 BaseEnd = ClassDecl->vbases_end();
7164 Base != BaseEnd;
7165 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007166 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007167 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007168 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007169 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007170 ExceptSpec.CalledDecl(CopyConstructor);
7171 }
7172 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7173 FieldEnd = ClassDecl->field_end();
7174 Field != FieldEnd;
7175 ++Field) {
7176 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007177 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7178 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007179 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00007180 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007181 }
7182 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007183
Alexis Hunt913820d2011-05-13 06:10:58 +00007184 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7185}
7186
7187CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7188 CXXRecordDecl *ClassDecl) {
7189 // C++ [class.copy]p4:
7190 // If the class definition does not explicitly declare a copy
7191 // constructor, one is declared implicitly.
7192
7193 ImplicitExceptionSpecification Spec(Context);
7194 bool Const;
7195 llvm::tie(Spec, Const) =
7196 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7197
7198 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7199 QualType ArgType = ClassType;
7200 if (Const)
7201 ArgType = ArgType.withConst();
7202 ArgType = Context.getLValueReferenceType(ArgType);
7203
7204 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7205
Douglas Gregor54be3392010-07-01 17:57:27 +00007206 DeclarationName Name
7207 = Context.DeclarationNames.getCXXConstructorName(
7208 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007209 SourceLocation ClassLoc = ClassDecl->getLocation();
7210 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00007211
7212 // An implicitly-declared copy constructor is an inline public
7213 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00007214 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00007215 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00007216 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00007217 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00007218 /*TInfo=*/0,
7219 /*isExplicit=*/false,
7220 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00007221 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00007222 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00007223 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00007224 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7225
Douglas Gregora6d69502010-07-02 23:41:54 +00007226 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00007227 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7228
Douglas Gregor54be3392010-07-01 17:57:27 +00007229 // Add the parameter to the constructor.
7230 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007231 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00007232 /*IdentifierInfo=*/0,
7233 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007234 SC_None,
7235 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00007236 CopyConstructor->setParams(&FromParam, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00007237
Douglas Gregor0be31a22010-07-02 17:43:08 +00007238 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00007239 PushOnScopeChains(CopyConstructor, S, false);
7240 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007241
Alexis Huntd74c85f2011-06-22 01:05:13 +00007242 // C++0x [class.copy]p7:
7243 // ... If the class definition declares a move constructor or move
7244 // assignment operator, the implicitly declared constructor is defined as
7245 // deleted; ...
7246 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7247 ClassDecl->hasUserDeclaredMoveAssignment() ||
7248 ShouldDeleteCopyConstructor(CopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007249 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00007250
7251 return CopyConstructor;
7252}
7253
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007254void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00007255 CXXConstructorDecl *CopyConstructor) {
7256 assert((CopyConstructor->isDefaulted() &&
7257 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007258 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007259 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007260
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00007261 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007262 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007263
Douglas Gregora57478e2010-05-01 15:04:51 +00007264 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007265 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007266
Alexis Hunt1d792652011-01-08 20:30:50 +00007267 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007268 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00007269 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00007270 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00007271 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00007272 } else {
7273 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7274 CopyConstructor->getLocation(),
7275 MultiStmtArg(*this, 0, 0),
7276 /*isStmtExpr=*/false)
7277 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00007278 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00007279
7280 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00007281
7282 if (ASTMutationListener *L = getASTMutationListener()) {
7283 L->CompletedImplicitDefinition(CopyConstructor);
7284 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007285}
7286
John McCalldadc5752010-08-24 06:29:42 +00007287ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007288Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00007289 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007290 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007291 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007292 unsigned ConstructKind,
7293 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00007294 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00007295
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007296 // C++0x [class.copy]p34:
7297 // When certain criteria are met, an implementation is allowed to
7298 // omit the copy/move construction of a class object, even if the
7299 // copy/move constructor and/or destructor for the object have
7300 // side effects. [...]
7301 // - when a temporary class object that has not been bound to a
7302 // reference (12.2) would be copied/moved to a class object
7303 // with the same cv-unqualified type, the copy/move operation
7304 // can be omitted by constructing the temporary object
7305 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00007306 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00007307 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007308 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00007309 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00007310 }
Mike Stump11289f42009-09-09 15:08:12 +00007311
7312 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007313 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007314 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00007315}
7316
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007317/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7318/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00007319ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007320Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7321 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007322 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007323 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007324 unsigned ConstructKind,
7325 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007326 unsigned NumExprs = ExprArgs.size();
7327 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00007328
Nick Lewyckyd4693212011-03-25 01:44:32 +00007329 for (specific_attr_iterator<NonNullAttr>
7330 i = Constructor->specific_attr_begin<NonNullAttr>(),
7331 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7332 const NonNullAttr *NonNull = *i;
7333 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7334 }
7335
Douglas Gregor27381f32009-11-23 12:27:39 +00007336 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00007337 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007338 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00007339 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007340 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7341 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007342}
7343
Mike Stump11289f42009-09-09 15:08:12 +00007344bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007345 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007346 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00007347 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00007348 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00007349 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00007350 move(Exprs), false, CXXConstructExpr::CK_Complete,
7351 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007352 if (TempResult.isInvalid())
7353 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007354
Anders Carlsson6eb55572009-08-25 05:12:04 +00007355 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00007356 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00007357 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00007358 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00007359 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00007360
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007361 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00007362}
7363
John McCall03c48482010-02-02 09:10:11 +00007364void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00007365 if (VD->isInvalidDecl()) return;
7366
John McCall03c48482010-02-02 09:10:11 +00007367 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00007368 if (ClassDecl->isInvalidDecl()) return;
7369 if (ClassDecl->hasTrivialDestructor()) return;
7370 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00007371
Chandler Carruth86d17d32011-03-27 21:26:48 +00007372 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7373 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7374 CheckDestructorAccess(VD->getLocation(), Destructor,
7375 PDiag(diag::err_access_dtor_var)
7376 << VD->getDeclName()
7377 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00007378
Chandler Carruth86d17d32011-03-27 21:26:48 +00007379 if (!VD->hasGlobalStorage()) return;
7380
7381 // Emit warning for non-trivial dtor in global scope (a real global,
7382 // class-static, function-static).
7383 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7384
7385 // TODO: this should be re-enabled for static locals by !CXAAtExit
7386 if (!VD->isStaticLocal())
7387 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007388}
7389
Mike Stump11289f42009-09-09 15:08:12 +00007390/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007391/// ActOnDeclarator, when a C++ direct initializer is present.
7392/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00007393void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007394 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007395 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00007396 SourceLocation RParenLoc,
7397 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00007398 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007399
7400 // If there is no declaration, there was an error parsing it. Just ignore
7401 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00007402 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007403 return;
Mike Stump11289f42009-09-09 15:08:12 +00007404
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007405 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7406 if (!VDecl) {
7407 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7408 RealDecl->setInvalidDecl();
7409 return;
7410 }
7411
Richard Smith30482bc2011-02-20 03:19:35 +00007412 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7413 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00007414 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7415 if (Exprs.size() > 1) {
7416 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7417 diag::err_auto_var_init_multiple_expressions)
7418 << VDecl->getDeclName() << VDecl->getType()
7419 << VDecl->getSourceRange();
7420 RealDecl->setInvalidDecl();
7421 return;
7422 }
7423
7424 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00007425 TypeSourceInfo *DeducedType = 0;
7426 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00007427 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7428 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7429 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00007430 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00007431 RealDecl->setInvalidDecl();
7432 return;
7433 }
Richard Smith9647d3c2011-03-17 16:11:59 +00007434 VDecl->setTypeSourceInfo(DeducedType);
7435 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00007436
John McCall31168b02011-06-15 23:02:42 +00007437 // In ARC, infer lifetime.
7438 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7439 VDecl->setInvalidDecl();
7440
Richard Smith30482bc2011-02-20 03:19:35 +00007441 // If this is a redeclaration, check that the type we just deduced matches
7442 // the previously declared type.
7443 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7444 MergeVarDeclTypes(VDecl, Old);
7445 }
7446
Douglas Gregor402250f2009-08-26 21:14:46 +00007447 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007448 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007449 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7450 //
7451 // Clients that want to distinguish between the two forms, can check for
7452 // direct initializer using VarDecl::hasCXXDirectInitializer().
7453 // A major benefit is that clients that don't particularly care about which
7454 // exactly form was it (like the CodeGen) can handle both cases without
7455 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007456
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007457 // C++ 8.5p11:
7458 // The form of initialization (using parentheses or '=') is generally
7459 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007460 // class type.
7461
Douglas Gregor50dc2192010-02-11 22:55:30 +00007462 if (!VDecl->getType()->isDependentType() &&
7463 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00007464 diag::err_typecheck_decl_incomplete_type)) {
7465 VDecl->setInvalidDecl();
7466 return;
7467 }
7468
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007469 // The variable can not have an abstract class type.
7470 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7471 diag::err_abstract_type_in_decl,
7472 AbstractVariableType))
7473 VDecl->setInvalidDecl();
7474
Sebastian Redl5ca79842010-02-01 20:16:42 +00007475 const VarDecl *Def;
7476 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007477 Diag(VDecl->getLocation(), diag::err_redefinition)
7478 << VDecl->getDeclName();
7479 Diag(Def->getLocation(), diag::note_previous_definition);
7480 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007481 return;
7482 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00007483
Douglas Gregorf0f83692010-08-24 05:27:49 +00007484 // C++ [class.static.data]p4
7485 // If a static data member is of const integral or const
7486 // enumeration type, its declaration in the class definition can
7487 // specify a constant-initializer which shall be an integral
7488 // constant expression (5.19). In that case, the member can appear
7489 // in integral constant expressions. The member shall still be
7490 // defined in a namespace scope if it is used in the program and the
7491 // namespace scope definition shall not contain an initializer.
7492 //
7493 // We already performed a redefinition check above, but for static
7494 // data members we also need to check whether there was an in-class
7495 // declaration with an initializer.
7496 const VarDecl* PrevInit = 0;
7497 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7498 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7499 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7500 return;
7501 }
7502
Douglas Gregor71f39c92010-12-16 01:31:22 +00007503 bool IsDependent = false;
7504 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7505 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7506 VDecl->setInvalidDecl();
7507 return;
7508 }
7509
7510 if (Exprs.get()[I]->isTypeDependent())
7511 IsDependent = true;
7512 }
7513
Douglas Gregor50dc2192010-02-11 22:55:30 +00007514 // If either the declaration has a dependent type or if any of the
7515 // expressions is type-dependent, we represent the initialization
7516 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00007517 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00007518 // Let clients know that initialization was done with a direct initializer.
7519 VDecl->setCXXDirectInitializer(true);
7520
7521 // Store the initialization expressions as a ParenListExpr.
7522 unsigned NumExprs = Exprs.size();
7523 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7524 (Expr **)Exprs.release(),
7525 NumExprs, RParenLoc));
7526 return;
7527 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007528
7529 // Capture the variable that is being initialized and the style of
7530 // initialization.
7531 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7532
7533 // FIXME: Poor source location information.
7534 InitializationKind Kind
7535 = InitializationKind::CreateDirect(VDecl->getLocation(),
7536 LParenLoc, RParenLoc);
7537
7538 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00007539 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00007540 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007541 if (Result.isInvalid()) {
7542 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007543 return;
7544 }
John McCallacf0ee52010-10-08 02:01:28 +00007545
7546 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007547
Douglas Gregora40433a2010-12-07 00:41:46 +00007548 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00007549 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007550 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007551
John McCall8b7fd8f12011-01-19 11:48:09 +00007552 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007553}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007554
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007555/// \brief Given a constructor and the set of arguments provided for the
7556/// constructor, convert the arguments and add any required default arguments
7557/// to form a proper call to this constructor.
7558///
7559/// \returns true if an error occurred, false otherwise.
7560bool
7561Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7562 MultiExprArg ArgsPtr,
7563 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00007564 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007565 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7566 unsigned NumArgs = ArgsPtr.size();
7567 Expr **Args = (Expr **)ArgsPtr.get();
7568
7569 const FunctionProtoType *Proto
7570 = Constructor->getType()->getAs<FunctionProtoType>();
7571 assert(Proto && "Constructor without a prototype?");
7572 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007573
7574 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007575 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007576 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007577 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007578 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007579
7580 VariadicCallType CallType =
7581 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7582 llvm::SmallVector<Expr *, 8> AllArgs;
7583 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7584 Proto, 0, Args, NumArgs, AllArgs,
7585 CallType);
7586 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7587 ConvertedArgs.push_back(AllArgs[i]);
7588 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00007589}
7590
Anders Carlssone363c8e2009-12-12 00:32:00 +00007591static inline bool
7592CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7593 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007594 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00007595 if (isa<NamespaceDecl>(DC)) {
7596 return SemaRef.Diag(FnDecl->getLocation(),
7597 diag::err_operator_new_delete_declared_in_namespace)
7598 << FnDecl->getDeclName();
7599 }
7600
7601 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00007602 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007603 return SemaRef.Diag(FnDecl->getLocation(),
7604 diag::err_operator_new_delete_declared_static)
7605 << FnDecl->getDeclName();
7606 }
7607
Anders Carlsson60659a82009-12-12 02:43:16 +00007608 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00007609}
7610
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007611static inline bool
7612CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7613 CanQualType ExpectedResultType,
7614 CanQualType ExpectedFirstParamType,
7615 unsigned DependentParamTypeDiag,
7616 unsigned InvalidParamTypeDiag) {
7617 QualType ResultType =
7618 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7619
7620 // Check that the result type is not dependent.
7621 if (ResultType->isDependentType())
7622 return SemaRef.Diag(FnDecl->getLocation(),
7623 diag::err_operator_new_delete_dependent_result_type)
7624 << FnDecl->getDeclName() << ExpectedResultType;
7625
7626 // Check that the result type is what we expect.
7627 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7628 return SemaRef.Diag(FnDecl->getLocation(),
7629 diag::err_operator_new_delete_invalid_result_type)
7630 << FnDecl->getDeclName() << ExpectedResultType;
7631
7632 // A function template must have at least 2 parameters.
7633 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7634 return SemaRef.Diag(FnDecl->getLocation(),
7635 diag::err_operator_new_delete_template_too_few_parameters)
7636 << FnDecl->getDeclName();
7637
7638 // The function decl must have at least 1 parameter.
7639 if (FnDecl->getNumParams() == 0)
7640 return SemaRef.Diag(FnDecl->getLocation(),
7641 diag::err_operator_new_delete_too_few_parameters)
7642 << FnDecl->getDeclName();
7643
7644 // Check the the first parameter type is not dependent.
7645 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7646 if (FirstParamType->isDependentType())
7647 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7648 << FnDecl->getDeclName() << ExpectedFirstParamType;
7649
7650 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00007651 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007652 ExpectedFirstParamType)
7653 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7654 << FnDecl->getDeclName() << ExpectedFirstParamType;
7655
7656 return false;
7657}
7658
Anders Carlsson12308f42009-12-11 23:23:22 +00007659static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007660CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007661 // C++ [basic.stc.dynamic.allocation]p1:
7662 // A program is ill-formed if an allocation function is declared in a
7663 // namespace scope other than global scope or declared static in global
7664 // scope.
7665 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7666 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007667
7668 CanQualType SizeTy =
7669 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7670
7671 // C++ [basic.stc.dynamic.allocation]p1:
7672 // The return type shall be void*. The first parameter shall have type
7673 // std::size_t.
7674 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7675 SizeTy,
7676 diag::err_operator_new_dependent_param_type,
7677 diag::err_operator_new_param_type))
7678 return true;
7679
7680 // C++ [basic.stc.dynamic.allocation]p1:
7681 // The first parameter shall not have an associated default argument.
7682 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00007683 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007684 diag::err_operator_new_default_arg)
7685 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7686
7687 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00007688}
7689
7690static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00007691CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7692 // C++ [basic.stc.dynamic.deallocation]p1:
7693 // A program is ill-formed if deallocation functions are declared in a
7694 // namespace scope other than global scope or declared static in global
7695 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00007696 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7697 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007698
7699 // C++ [basic.stc.dynamic.deallocation]p2:
7700 // Each deallocation function shall return void and its first parameter
7701 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007702 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7703 SemaRef.Context.VoidPtrTy,
7704 diag::err_operator_delete_dependent_param_type,
7705 diag::err_operator_delete_param_type))
7706 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007707
Anders Carlsson12308f42009-12-11 23:23:22 +00007708 return false;
7709}
7710
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007711/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7712/// of this overloaded operator is well-formed. If so, returns false;
7713/// otherwise, emits appropriate diagnostics and returns true.
7714bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00007715 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007716 "Expected an overloaded operator declaration");
7717
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007718 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7719
Mike Stump11289f42009-09-09 15:08:12 +00007720 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007721 // The allocation and deallocation functions, operator new,
7722 // operator new[], operator delete and operator delete[], are
7723 // described completely in 3.7.3. The attributes and restrictions
7724 // found in the rest of this subclause do not apply to them unless
7725 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00007726 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00007727 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00007728
Anders Carlsson22f443f2009-12-12 00:26:23 +00007729 if (Op == OO_New || Op == OO_Array_New)
7730 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007731
7732 // C++ [over.oper]p6:
7733 // An operator function shall either be a non-static member
7734 // function or be a non-member function and have at least one
7735 // parameter whose type is a class, a reference to a class, an
7736 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00007737 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7738 if (MethodDecl->isStatic())
7739 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007740 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007741 } else {
7742 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00007743 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7744 ParamEnd = FnDecl->param_end();
7745 Param != ParamEnd; ++Param) {
7746 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00007747 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7748 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007749 ClassOrEnumParam = true;
7750 break;
7751 }
7752 }
7753
Douglas Gregord69246b2008-11-17 16:14:12 +00007754 if (!ClassOrEnumParam)
7755 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007756 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007757 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007758 }
7759
7760 // C++ [over.oper]p8:
7761 // An operator function cannot have default arguments (8.3.6),
7762 // except where explicitly stated below.
7763 //
Mike Stump11289f42009-09-09 15:08:12 +00007764 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007765 // (C++ [over.call]p1).
7766 if (Op != OO_Call) {
7767 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7768 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007769 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00007770 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00007771 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007772 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007773 }
7774 }
7775
Douglas Gregor6cf08062008-11-10 13:38:07 +00007776 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7777 { false, false, false }
7778#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7779 , { Unary, Binary, MemberOnly }
7780#include "clang/Basic/OperatorKinds.def"
7781 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007782
Douglas Gregor6cf08062008-11-10 13:38:07 +00007783 bool CanBeUnaryOperator = OperatorUses[Op][0];
7784 bool CanBeBinaryOperator = OperatorUses[Op][1];
7785 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007786
7787 // C++ [over.oper]p8:
7788 // [...] Operator functions cannot have more or fewer parameters
7789 // than the number required for the corresponding operator, as
7790 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00007791 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00007792 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007793 if (Op != OO_Call &&
7794 ((NumParams == 1 && !CanBeUnaryOperator) ||
7795 (NumParams == 2 && !CanBeBinaryOperator) ||
7796 (NumParams < 1) || (NumParams > 2))) {
7797 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007798 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00007799 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007800 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00007801 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007802 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007803 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00007804 assert(CanBeBinaryOperator &&
7805 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007806 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007807 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007808
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007809 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007810 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007811 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007812
Douglas Gregord69246b2008-11-17 16:14:12 +00007813 // Overloaded operators other than operator() cannot be variadic.
7814 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00007815 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007816 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007817 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007818 }
7819
7820 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00007821 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7822 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007823 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007824 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007825 }
7826
7827 // C++ [over.inc]p1:
7828 // The user-defined function called operator++ implements the
7829 // prefix and postfix ++ operator. If this function is a member
7830 // function with no parameters, or a non-member function with one
7831 // parameter of class or enumeration type, it defines the prefix
7832 // increment operator ++ for objects of that type. If the function
7833 // is a member function with one parameter (which shall be of type
7834 // int) or a non-member function with two parameters (the second
7835 // of which shall be of type int), it defines the postfix
7836 // increment operator ++ for objects of that type.
7837 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7838 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7839 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00007840 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007841 ParamIsInt = BT->getKind() == BuiltinType::Int;
7842
Chris Lattner2b786902008-11-21 07:50:02 +00007843 if (!ParamIsInt)
7844 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00007845 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007846 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007847 }
7848
Douglas Gregord69246b2008-11-17 16:14:12 +00007849 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007850}
Chris Lattner3b024a32008-12-17 07:09:26 +00007851
Alexis Huntc88db062010-01-13 09:01:02 +00007852/// CheckLiteralOperatorDeclaration - Check whether the declaration
7853/// of this literal operator function is well-formed. If so, returns
7854/// false; otherwise, emits appropriate diagnostics and returns true.
7855bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7856 DeclContext *DC = FnDecl->getDeclContext();
7857 Decl::Kind Kind = DC->getDeclKind();
7858 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7859 Kind != Decl::LinkageSpec) {
7860 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7861 << FnDecl->getDeclName();
7862 return true;
7863 }
7864
7865 bool Valid = false;
7866
Alexis Hunt7dd26172010-04-07 23:11:06 +00007867 // template <char...> type operator "" name() is the only valid template
7868 // signature, and the only valid signature with no parameters.
7869 if (FnDecl->param_size() == 0) {
7870 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7871 // Must have only one template parameter
7872 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7873 if (Params->size() == 1) {
7874 NonTypeTemplateParmDecl *PmDecl =
7875 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00007876
Alexis Hunt7dd26172010-04-07 23:11:06 +00007877 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00007878 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7879 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7880 Valid = true;
7881 }
7882 }
7883 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00007884 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00007885 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7886
Alexis Huntc88db062010-01-13 09:01:02 +00007887 QualType T = (*Param)->getType();
7888
Alexis Hunt079a6f72010-04-07 22:57:35 +00007889 // unsigned long long int, long double, and any character type are allowed
7890 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00007891 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7892 Context.hasSameType(T, Context.LongDoubleTy) ||
7893 Context.hasSameType(T, Context.CharTy) ||
7894 Context.hasSameType(T, Context.WCharTy) ||
7895 Context.hasSameType(T, Context.Char16Ty) ||
7896 Context.hasSameType(T, Context.Char32Ty)) {
7897 if (++Param == FnDecl->param_end())
7898 Valid = true;
7899 goto FinishedParams;
7900 }
7901
Alexis Hunt079a6f72010-04-07 22:57:35 +00007902 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00007903 const PointerType *PT = T->getAs<PointerType>();
7904 if (!PT)
7905 goto FinishedParams;
7906 T = PT->getPointeeType();
7907 if (!T.isConstQualified())
7908 goto FinishedParams;
7909 T = T.getUnqualifiedType();
7910
7911 // Move on to the second parameter;
7912 ++Param;
7913
7914 // If there is no second parameter, the first must be a const char *
7915 if (Param == FnDecl->param_end()) {
7916 if (Context.hasSameType(T, Context.CharTy))
7917 Valid = true;
7918 goto FinishedParams;
7919 }
7920
7921 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7922 // are allowed as the first parameter to a two-parameter function
7923 if (!(Context.hasSameType(T, Context.CharTy) ||
7924 Context.hasSameType(T, Context.WCharTy) ||
7925 Context.hasSameType(T, Context.Char16Ty) ||
7926 Context.hasSameType(T, Context.Char32Ty)))
7927 goto FinishedParams;
7928
7929 // The second and final parameter must be an std::size_t
7930 T = (*Param)->getType().getUnqualifiedType();
7931 if (Context.hasSameType(T, Context.getSizeType()) &&
7932 ++Param == FnDecl->param_end())
7933 Valid = true;
7934 }
7935
7936 // FIXME: This diagnostic is absolutely terrible.
7937FinishedParams:
7938 if (!Valid) {
7939 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7940 << FnDecl->getDeclName();
7941 return true;
7942 }
7943
7944 return false;
7945}
7946
Douglas Gregor07665a62009-01-05 19:45:36 +00007947/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7948/// linkage specification, including the language and (if present)
7949/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7950/// the location of the language string literal, which is provided
7951/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7952/// the '{' brace. Otherwise, this linkage specification does not
7953/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00007954Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7955 SourceLocation LangLoc,
7956 llvm::StringRef Lang,
7957 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00007958 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007959 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007960 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007961 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007962 Language = LinkageSpecDecl::lang_cxx;
7963 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00007964 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00007965 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00007966 }
Mike Stump11289f42009-09-09 15:08:12 +00007967
Chris Lattner438e5012008-12-17 07:13:27 +00007968 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00007969
Douglas Gregor07665a62009-01-05 19:45:36 +00007970 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007971 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007972 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00007973 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00007974 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00007975}
7976
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00007977/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00007978/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7979/// valid, it's the position of the closing '}' brace in a linkage
7980/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00007981Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007982 Decl *LinkageSpec,
7983 SourceLocation RBraceLoc) {
7984 if (LinkageSpec) {
7985 if (RBraceLoc.isValid()) {
7986 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7987 LSDecl->setRBraceLoc(RBraceLoc);
7988 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007989 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007990 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007991 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00007992}
7993
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007994/// \brief Perform semantic analysis for the variable declaration that
7995/// occurs within a C++ catch clause, returning the newly-created
7996/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007997VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00007998 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007999 SourceLocation StartLoc,
8000 SourceLocation Loc,
8001 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008002 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008003 QualType ExDeclType = TInfo->getType();
8004
Sebastian Redl54c04d42008-12-22 19:15:10 +00008005 // Arrays and functions decay.
8006 if (ExDeclType->isArrayType())
8007 ExDeclType = Context.getArrayDecayedType(ExDeclType);
8008 else if (ExDeclType->isFunctionType())
8009 ExDeclType = Context.getPointerType(ExDeclType);
8010
8011 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8012 // The exception-declaration shall not denote a pointer or reference to an
8013 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00008014 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00008015 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008016 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00008017 Invalid = true;
8018 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008019
Douglas Gregor104ee002010-03-08 01:47:36 +00008020 // GCC allows catching pointers and references to incomplete types
8021 // as an extension; so do we, but we warn by default.
8022
Sebastian Redl54c04d42008-12-22 19:15:10 +00008023 QualType BaseType = ExDeclType;
8024 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00008025 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00008026 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008027 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008028 BaseType = Ptr->getPointeeType();
8029 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00008030 DK = diag::ext_catch_incomplete_ptr;
8031 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00008032 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00008033 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008034 BaseType = Ref->getPointeeType();
8035 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00008036 DK = diag::ext_catch_incomplete_ref;
8037 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008038 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00008039 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00008040 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8041 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00008042 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008043
Mike Stump11289f42009-09-09 15:08:12 +00008044 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008045 RequireNonAbstractType(Loc, ExDeclType,
8046 diag::err_abstract_type_in_decl,
8047 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00008048 Invalid = true;
8049
John McCall2ca705e2010-07-24 00:37:23 +00008050 // Only the non-fragile NeXT runtime currently supports C++ catches
8051 // of ObjC types, and no runtime supports catching ObjC types by value.
8052 if (!Invalid && getLangOptions().ObjC1) {
8053 QualType T = ExDeclType;
8054 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8055 T = RT->getPointeeType();
8056
8057 if (T->isObjCObjectType()) {
8058 Diag(Loc, diag::err_objc_object_catch);
8059 Invalid = true;
8060 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00008061 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00008062 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8063 Invalid = true;
8064 }
8065 }
8066 }
8067
Abramo Bagnaradff19302011-03-08 08:55:46 +00008068 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8069 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00008070 ExDecl->setExceptionVariable(true);
8071
Douglas Gregor6de584c2010-03-05 23:38:39 +00008072 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00008073 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00008074 // C++ [except.handle]p16:
8075 // The object declared in an exception-declaration or, if the
8076 // exception-declaration does not specify a name, a temporary (12.2) is
8077 // copy-initialized (8.5) from the exception object. [...]
8078 // The object is destroyed when the handler exits, after the destruction
8079 // of any automatic objects initialized within the handler.
8080 //
8081 // We just pretend to initialize the object with itself, then make sure
8082 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00008083 QualType initType = ExDeclType;
8084
8085 InitializedEntity entity =
8086 InitializedEntity::InitializeVariable(ExDecl);
8087 InitializationKind initKind =
8088 InitializationKind::CreateCopy(Loc, SourceLocation());
8089
8090 Expr *opaqueValue =
8091 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8092 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8093 ExprResult result = sequence.Perform(*this, entity, initKind,
8094 MultiExprArg(&opaqueValue, 1));
8095 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00008096 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00008097 else {
8098 // If the constructor used was non-trivial, set this as the
8099 // "initializer".
8100 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8101 if (!construct->getConstructor()->isTrivial()) {
8102 Expr *init = MaybeCreateExprWithCleanups(construct);
8103 ExDecl->setInit(init);
8104 }
8105
8106 // And make sure it's destructable.
8107 FinalizeVarWithDestructor(ExDecl, recordType);
8108 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00008109 }
8110 }
8111
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008112 if (Invalid)
8113 ExDecl->setInvalidDecl();
8114
8115 return ExDecl;
8116}
8117
8118/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8119/// handler.
John McCall48871652010-08-21 09:40:31 +00008120Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00008121 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00008122 bool Invalid = D.isInvalidType();
8123
8124 // Check for unexpanded parameter packs.
8125 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8126 UPPC_ExceptionType)) {
8127 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8128 D.getIdentifierLoc());
8129 Invalid = true;
8130 }
8131
Sebastian Redl54c04d42008-12-22 19:15:10 +00008132 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008133 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00008134 LookupOrdinaryName,
8135 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008136 // The scope should be freshly made just for us. There is just no way
8137 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00008138 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00008139 if (PrevDecl->isTemplateParameter()) {
8140 // Maybe we will complain about the shadowed template parameter.
8141 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008142 }
8143 }
8144
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008145 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008146 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8147 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008148 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008149 }
8150
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008151 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008152 D.getSourceRange().getBegin(),
8153 D.getIdentifierLoc(),
8154 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008155 if (Invalid)
8156 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00008157
Sebastian Redl54c04d42008-12-22 19:15:10 +00008158 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008159 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008160 PushOnScopeChains(ExDecl, S);
8161 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008162 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008163
Douglas Gregor758a8692009-06-17 21:51:59 +00008164 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00008165 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008166}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008167
Abramo Bagnaraea947882011-03-08 16:41:52 +00008168Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00008169 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00008170 Expr *AssertMessageExpr_,
8171 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00008172 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008173
Anders Carlsson54b26982009-03-14 00:33:21 +00008174 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8175 llvm::APSInt Value(32);
8176 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008177 Diag(StaticAssertLoc,
8178 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00008179 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008180 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00008181 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008182
Anders Carlsson54b26982009-03-14 00:33:21 +00008183 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008184 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00008185 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00008186 }
8187 }
Mike Stump11289f42009-09-09 15:08:12 +00008188
Douglas Gregoref68fee2010-12-15 23:55:21 +00008189 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8190 return 0;
8191
Abramo Bagnaraea947882011-03-08 16:41:52 +00008192 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8193 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00008194
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008195 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00008196 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008197}
Sebastian Redlf769df52009-03-24 22:27:57 +00008198
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008199/// \brief Perform semantic analysis of the given friend type declaration.
8200///
8201/// \returns A friend declaration that.
8202FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8203 TypeSourceInfo *TSInfo) {
8204 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8205
8206 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008207 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008208
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008209 if (!getLangOptions().CPlusPlus0x) {
8210 // C++03 [class.friend]p2:
8211 // An elaborated-type-specifier shall be used in a friend declaration
8212 // for a class.*
8213 //
8214 // * The class-key of the elaborated-type-specifier is required.
8215 if (!ActiveTemplateInstantiations.empty()) {
8216 // Do not complain about the form of friend template types during
8217 // template instantiation; we will already have complained when the
8218 // template was declared.
8219 } else if (!T->isElaboratedTypeSpecifier()) {
8220 // If we evaluated the type to a record type, suggest putting
8221 // a tag in front.
8222 if (const RecordType *RT = T->getAs<RecordType>()) {
8223 RecordDecl *RD = RT->getDecl();
8224
8225 std::string InsertionText = std::string(" ") + RD->getKindName();
8226
8227 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8228 << (unsigned) RD->getTagKind()
8229 << T
8230 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8231 InsertionText);
8232 } else {
8233 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8234 << T
8235 << SourceRange(FriendLoc, TypeRange.getEnd());
8236 }
8237 } else if (T->getAs<EnumType>()) {
8238 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008239 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008240 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008241 }
8242 }
8243
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008244 // C++0x [class.friend]p3:
8245 // If the type specifier in a friend declaration designates a (possibly
8246 // cv-qualified) class type, that class is declared as a friend; otherwise,
8247 // the friend declaration is ignored.
8248
8249 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8250 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008251
8252 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8253}
8254
John McCallace48cd2010-10-19 01:40:49 +00008255/// Handle a friend tag declaration where the scope specifier was
8256/// templated.
8257Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8258 unsigned TagSpec, SourceLocation TagLoc,
8259 CXXScopeSpec &SS,
8260 IdentifierInfo *Name, SourceLocation NameLoc,
8261 AttributeList *Attr,
8262 MultiTemplateParamsArg TempParamLists) {
8263 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8264
8265 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00008266 bool Invalid = false;
8267
8268 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008269 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00008270 TempParamLists.get(),
8271 TempParamLists.size(),
8272 /*friend*/ true,
8273 isExplicitSpecialization,
8274 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00008275 if (TemplateParams->size() > 0) {
8276 // This is a declaration of a class template.
8277 if (Invalid)
8278 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008279
John McCallace48cd2010-10-19 01:40:49 +00008280 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8281 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008282 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008283 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008284 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00008285 } else {
8286 // The "template<>" header is extraneous.
8287 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8288 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8289 isExplicitSpecialization = true;
8290 }
8291 }
8292
8293 if (Invalid) return 0;
8294
8295 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8296
8297 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00008298 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00008299 if (TempParamLists.get()[I]->size()) {
8300 isAllExplicitSpecializations = false;
8301 break;
8302 }
8303 }
8304
8305 // FIXME: don't ignore attributes.
8306
8307 // If it's explicit specializations all the way down, just forget
8308 // about the template header and build an appropriate non-templated
8309 // friend. TODO: for source fidelity, remember the headers.
8310 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008311 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00008312 ElaboratedTypeKeyword Keyword
8313 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008314 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008315 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00008316 if (T.isNull())
8317 return 0;
8318
8319 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8320 if (isa<DependentNameType>(T)) {
8321 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8322 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008323 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008324 TL.setNameLoc(NameLoc);
8325 } else {
8326 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8327 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008328 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008329 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8330 }
8331
8332 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8333 TSI, FriendLoc);
8334 Friend->setAccess(AS_public);
8335 CurContext->addDecl(Friend);
8336 return Friend;
8337 }
8338
8339 // Handle the case of a templated-scope friend class. e.g.
8340 // template <class T> class A<T>::B;
8341 // FIXME: we don't support these right now.
8342 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8343 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8344 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8345 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8346 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008347 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00008348 TL.setNameLoc(NameLoc);
8349
8350 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8351 TSI, FriendLoc);
8352 Friend->setAccess(AS_public);
8353 Friend->setUnsupportedFriend(true);
8354 CurContext->addDecl(Friend);
8355 return Friend;
8356}
8357
8358
John McCall11083da2009-09-16 22:47:08 +00008359/// Handle a friend type declaration. This works in tandem with
8360/// ActOnTag.
8361///
8362/// Notes on friend class templates:
8363///
8364/// We generally treat friend class declarations as if they were
8365/// declaring a class. So, for example, the elaborated type specifier
8366/// in a friend declaration is required to obey the restrictions of a
8367/// class-head (i.e. no typedefs in the scope chain), template
8368/// parameters are required to match up with simple template-ids, &c.
8369/// However, unlike when declaring a template specialization, it's
8370/// okay to refer to a template specialization without an empty
8371/// template parameter declaration, e.g.
8372/// friend class A<T>::B<unsigned>;
8373/// We permit this as a special case; if there are any template
8374/// parameters present at all, require proper matching, i.e.
8375/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00008376Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00008377 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008378 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00008379
8380 assert(DS.isFriendSpecified());
8381 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8382
John McCall11083da2009-09-16 22:47:08 +00008383 // Try to convert the decl specifier to a type. This works for
8384 // friend templates because ActOnTag never produces a ClassTemplateDecl
8385 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00008386 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00008387 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8388 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00008389 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00008390 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008391
Douglas Gregor6c110f32010-12-16 01:14:37 +00008392 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8393 return 0;
8394
John McCall11083da2009-09-16 22:47:08 +00008395 // This is definitely an error in C++98. It's probably meant to
8396 // be forbidden in C++0x, too, but the specification is just
8397 // poorly written.
8398 //
8399 // The problem is with declarations like the following:
8400 // template <T> friend A<T>::foo;
8401 // where deciding whether a class C is a friend or not now hinges
8402 // on whether there exists an instantiation of A that causes
8403 // 'foo' to equal C. There are restrictions on class-heads
8404 // (which we declare (by fiat) elaborated friend declarations to
8405 // be) that makes this tractable.
8406 //
8407 // FIXME: handle "template <> friend class A<T>;", which
8408 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00008409 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00008410 Diag(Loc, diag::err_tagless_friend_type_template)
8411 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008412 return 0;
John McCall11083da2009-09-16 22:47:08 +00008413 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008414
John McCallaa74a0c2009-08-28 07:59:38 +00008415 // C++98 [class.friend]p1: A friend of a class is a function
8416 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00008417 // This is fixed in DR77, which just barely didn't make the C++03
8418 // deadline. It's also a very silly restriction that seriously
8419 // affects inner classes and which nobody else seems to implement;
8420 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00008421 //
8422 // But note that we could warn about it: it's always useless to
8423 // friend one of your own members (it's not, however, worthless to
8424 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00008425
John McCall11083da2009-09-16 22:47:08 +00008426 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008427 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00008428 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008429 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00008430 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00008431 TSI,
John McCall11083da2009-09-16 22:47:08 +00008432 DS.getFriendSpecLoc());
8433 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008434 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8435
8436 if (!D)
John McCall48871652010-08-21 09:40:31 +00008437 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008438
John McCall11083da2009-09-16 22:47:08 +00008439 D->setAccess(AS_public);
8440 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00008441
John McCall48871652010-08-21 09:40:31 +00008442 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00008443}
8444
John McCallde3fd222010-10-12 23:13:28 +00008445Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8446 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008447 const DeclSpec &DS = D.getDeclSpec();
8448
8449 assert(DS.isFriendSpecified());
8450 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8451
8452 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00008453 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8454 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00008455
8456 // C++ [class.friend]p1
8457 // A friend of a class is a function or class....
8458 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00008459 // It *doesn't* see through dependent types, which is correct
8460 // according to [temp.arg.type]p3:
8461 // If a declaration acquires a function type through a
8462 // type dependent on a template-parameter and this causes
8463 // a declaration that does not use the syntactic form of a
8464 // function declarator to have a function type, the program
8465 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00008466 if (!T->isFunctionType()) {
8467 Diag(Loc, diag::err_unexpected_friend);
8468
8469 // It might be worthwhile to try to recover by creating an
8470 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00008471 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008472 }
8473
8474 // C++ [namespace.memdef]p3
8475 // - If a friend declaration in a non-local class first declares a
8476 // class or function, the friend class or function is a member
8477 // of the innermost enclosing namespace.
8478 // - The name of the friend is not found by simple name lookup
8479 // until a matching declaration is provided in that namespace
8480 // scope (either before or after the class declaration granting
8481 // friendship).
8482 // - If a friend function is called, its name may be found by the
8483 // name lookup that considers functions from namespaces and
8484 // classes associated with the types of the function arguments.
8485 // - When looking for a prior declaration of a class or a function
8486 // declared as a friend, scopes outside the innermost enclosing
8487 // namespace scope are not considered.
8488
John McCallde3fd222010-10-12 23:13:28 +00008489 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008490 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8491 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00008492 assert(Name);
8493
Douglas Gregor6c110f32010-12-16 01:14:37 +00008494 // Check for unexpanded parameter packs.
8495 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8496 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8497 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8498 return 0;
8499
John McCall07e91c02009-08-06 02:15:43 +00008500 // The context we found the declaration in, or in which we should
8501 // create the declaration.
8502 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00008503 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008504 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00008505 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00008506
John McCallde3fd222010-10-12 23:13:28 +00008507 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00008508
John McCallde3fd222010-10-12 23:13:28 +00008509 // There are four cases here.
8510 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00008511 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00008512 // there as appropriate.
8513 // Recover from invalid scope qualifiers as if they just weren't there.
8514 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00008515 // C++0x [namespace.memdef]p3:
8516 // If the name in a friend declaration is neither qualified nor
8517 // a template-id and the declaration is a function or an
8518 // elaborated-type-specifier, the lookup to determine whether
8519 // the entity has been previously declared shall not consider
8520 // any scopes outside the innermost enclosing namespace.
8521 // C++0x [class.friend]p11:
8522 // If a friend declaration appears in a local class and the name
8523 // specified is an unqualified name, a prior declaration is
8524 // looked up without considering scopes that are outside the
8525 // innermost enclosing non-class scope. For a friend function
8526 // declaration, if there is no prior declaration, the program is
8527 // ill-formed.
8528 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00008529 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00008530
John McCallf7cfb222010-10-13 05:45:15 +00008531 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00008532 DC = CurContext;
8533 while (true) {
8534 // Skip class contexts. If someone can cite chapter and verse
8535 // for this behavior, that would be nice --- it's what GCC and
8536 // EDG do, and it seems like a reasonable intent, but the spec
8537 // really only says that checks for unqualified existing
8538 // declarations should stop at the nearest enclosing namespace,
8539 // not that they should only consider the nearest enclosing
8540 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008541 while (DC->isRecord())
8542 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00008543
John McCall1f82f242009-11-18 22:49:29 +00008544 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00008545
8546 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00008547 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00008548 break;
John McCallf7cfb222010-10-13 05:45:15 +00008549
John McCallf4776592010-10-14 22:22:28 +00008550 if (isTemplateId) {
8551 if (isa<TranslationUnitDecl>(DC)) break;
8552 } else {
8553 if (DC->isFileContext()) break;
8554 }
John McCall07e91c02009-08-06 02:15:43 +00008555 DC = DC->getParent();
8556 }
8557
8558 // C++ [class.friend]p1: A friend of a class is a function or
8559 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00008560 // C++0x changes this for both friend types and functions.
8561 // Most C++ 98 compilers do seem to give an error here, so
8562 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00008563 if (!Previous.empty() && DC->Equals(CurContext)
8564 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00008565 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00008566
John McCallccbc0322010-10-13 06:22:15 +00008567 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00008568
John McCallde3fd222010-10-12 23:13:28 +00008569 // - There's a non-dependent scope specifier, in which case we
8570 // compute it and do a previous lookup there for a function
8571 // or function template.
8572 } else if (!SS.getScopeRep()->isDependent()) {
8573 DC = computeDeclContext(SS);
8574 if (!DC) return 0;
8575
8576 if (RequireCompleteDeclContext(SS, DC)) return 0;
8577
8578 LookupQualifiedName(Previous, DC);
8579
8580 // Ignore things found implicitly in the wrong scope.
8581 // TODO: better diagnostics for this case. Suggesting the right
8582 // qualified scope would be nice...
8583 LookupResult::Filter F = Previous.makeFilter();
8584 while (F.hasNext()) {
8585 NamedDecl *D = F.next();
8586 if (!DC->InEnclosingNamespaceSetOf(
8587 D->getDeclContext()->getRedeclContext()))
8588 F.erase();
8589 }
8590 F.done();
8591
8592 if (Previous.empty()) {
8593 D.setInvalidType();
8594 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8595 return 0;
8596 }
8597
8598 // C++ [class.friend]p1: A friend of a class is a function or
8599 // class that is not a member of the class . . .
8600 if (DC->Equals(CurContext))
8601 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8602
8603 // - There's a scope specifier that does not match any template
8604 // parameter lists, in which case we use some arbitrary context,
8605 // create a method or method template, and wait for instantiation.
8606 // - There's a scope specifier that does match some template
8607 // parameter lists, which we don't handle right now.
8608 } else {
8609 DC = CurContext;
8610 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00008611 }
8612
John McCallf7cfb222010-10-13 05:45:15 +00008613 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00008614 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00008615 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8616 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8617 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00008618 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00008619 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8620 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00008621 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008622 }
John McCall07e91c02009-08-06 02:15:43 +00008623 }
8624
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008625 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00008626 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00008627 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00008628 IsDefinition,
8629 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00008630 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00008631
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008632 assert(ND->getDeclContext() == DC);
8633 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00008634
John McCall759e32b2009-08-31 22:39:49 +00008635 // Add the function declaration to the appropriate lookup tables,
8636 // adjusting the redeclarations list as necessary. We don't
8637 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00008638 //
John McCall759e32b2009-08-31 22:39:49 +00008639 // Also update the scope-based lookup if the target context's
8640 // lookup context is in lexical scope.
8641 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008642 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008643 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008644 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008645 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008646 }
John McCallaa74a0c2009-08-28 07:59:38 +00008647
8648 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008649 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00008650 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00008651 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00008652 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00008653
John McCallde3fd222010-10-12 23:13:28 +00008654 if (ND->isInvalidDecl())
8655 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00008656 else {
8657 FunctionDecl *FD;
8658 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8659 FD = FTD->getTemplatedDecl();
8660 else
8661 FD = cast<FunctionDecl>(ND);
8662
8663 // Mark templated-scope function declarations as unsupported.
8664 if (FD->getNumTemplateParameterLists())
8665 FrD->setUnsupportedFriend(true);
8666 }
John McCallde3fd222010-10-12 23:13:28 +00008667
John McCall48871652010-08-21 09:40:31 +00008668 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00008669}
8670
John McCall48871652010-08-21 09:40:31 +00008671void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8672 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00008673
Sebastian Redlf769df52009-03-24 22:27:57 +00008674 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8675 if (!Fn) {
8676 Diag(DelLoc, diag::err_deleted_non_function);
8677 return;
8678 }
8679 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8680 Diag(DelLoc, diag::err_deleted_decl_not_first);
8681 Diag(Prev->getLocation(), diag::note_previous_declaration);
8682 // If the declaration wasn't the first, we delete the function anyway for
8683 // recovery.
8684 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008685 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00008686}
Sebastian Redl4c018662009-04-27 21:33:24 +00008687
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008688void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8689 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8690
8691 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +00008692 if (MD->getParent()->isDependentType()) {
8693 MD->setDefaulted();
8694 MD->setExplicitlyDefaulted();
8695 return;
8696 }
8697
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008698 CXXSpecialMember Member = getSpecialMember(MD);
8699 if (Member == CXXInvalid) {
8700 Diag(DefaultLoc, diag::err_default_special_members);
8701 return;
8702 }
8703
8704 MD->setDefaulted();
8705 MD->setExplicitlyDefaulted();
8706
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008707 // If this definition appears within the record, do the checking when
8708 // the record is complete.
8709 const FunctionDecl *Primary = MD;
8710 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8711 // Find the uninstantiated declaration that actually had the '= default'
8712 // on it.
8713 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8714
8715 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008716 return;
8717
8718 switch (Member) {
8719 case CXXDefaultConstructor: {
8720 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8721 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008722 if (!CD->isInvalidDecl())
8723 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8724 break;
8725 }
8726
8727 case CXXCopyConstructor: {
8728 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8729 CheckExplicitlyDefaultedCopyConstructor(CD);
8730 if (!CD->isInvalidDecl())
8731 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008732 break;
8733 }
Alexis Huntf91729462011-05-12 22:46:25 +00008734
Alexis Huntc9a55732011-05-14 05:23:28 +00008735 case CXXCopyAssignment: {
8736 CheckExplicitlyDefaultedCopyAssignment(MD);
8737 if (!MD->isInvalidDecl())
8738 DefineImplicitCopyAssignment(DefaultLoc, MD);
8739 break;
8740 }
8741
Alexis Huntf91729462011-05-12 22:46:25 +00008742 case CXXDestructor: {
8743 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8744 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008745 if (!DD->isInvalidDecl())
8746 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00008747 break;
8748 }
8749
Alexis Hunt119c10e2011-05-25 23:16:36 +00008750 case CXXMoveConstructor:
8751 case CXXMoveAssignment:
8752 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8753 break;
8754
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008755 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00008756 // FIXME: Do the rest once we have move functions
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008757 break;
8758 }
8759 } else {
8760 Diag(DefaultLoc, diag::err_default_special_members);
8761 }
8762}
8763
Sebastian Redl4c018662009-04-27 21:33:24 +00008764static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00008765 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00008766 Stmt *SubStmt = *CI;
8767 if (!SubStmt)
8768 continue;
8769 if (isa<ReturnStmt>(SubStmt))
8770 Self.Diag(SubStmt->getSourceRange().getBegin(),
8771 diag::err_return_in_constructor_handler);
8772 if (!isa<Expr>(SubStmt))
8773 SearchForReturnInStmt(Self, SubStmt);
8774 }
8775}
8776
8777void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8778 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8779 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8780 SearchForReturnInStmt(*this, Handler);
8781 }
8782}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008783
Mike Stump11289f42009-09-09 15:08:12 +00008784bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008785 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00008786 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8787 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008788
Chandler Carruth284bb2e2010-02-15 11:53:20 +00008789 if (Context.hasSameType(NewTy, OldTy) ||
8790 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008791 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008792
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008793 // Check if the return types are covariant
8794 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00008795
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008796 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008797 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8798 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008799 NewClassTy = NewPT->getPointeeType();
8800 OldClassTy = OldPT->getPointeeType();
8801 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008802 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8803 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8804 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8805 NewClassTy = NewRT->getPointeeType();
8806 OldClassTy = OldRT->getPointeeType();
8807 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008808 }
8809 }
Mike Stump11289f42009-09-09 15:08:12 +00008810
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008811 // The return types aren't either both pointers or references to a class type.
8812 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00008813 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008814 diag::err_different_return_type_for_overriding_virtual_function)
8815 << New->getDeclName() << NewTy << OldTy;
8816 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00008817
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008818 return true;
8819 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008820
Anders Carlssone60365b2009-12-31 18:34:24 +00008821 // C++ [class.virtual]p6:
8822 // If the return type of D::f differs from the return type of B::f, the
8823 // class type in the return type of D::f shall be complete at the point of
8824 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008825 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8826 if (!RT->isBeingDefined() &&
8827 RequireCompleteType(New->getLocation(), NewClassTy,
8828 PDiag(diag::err_covariant_return_incomplete)
8829 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00008830 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008831 }
Anders Carlssone60365b2009-12-31 18:34:24 +00008832
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008833 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008834 // Check if the new class derives from the old class.
8835 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8836 Diag(New->getLocation(),
8837 diag::err_covariant_return_not_derived)
8838 << New->getDeclName() << NewTy << OldTy;
8839 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8840 return true;
8841 }
Mike Stump11289f42009-09-09 15:08:12 +00008842
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008843 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00008844 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00008845 diag::err_covariant_return_inaccessible_base,
8846 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8847 // FIXME: Should this point to the return type?
8848 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00008849 // FIXME: this note won't trigger for delayed access control
8850 // diagnostics, and it's impossible to get an undelayed error
8851 // here from access control during the original parse because
8852 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008853 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8854 return true;
8855 }
8856 }
Mike Stump11289f42009-09-09 15:08:12 +00008857
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008858 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008859 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008860 Diag(New->getLocation(),
8861 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008862 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008863 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8864 return true;
8865 };
Mike Stump11289f42009-09-09 15:08:12 +00008866
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008867
8868 // The new class type must have the same or less qualifiers as the old type.
8869 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8870 Diag(New->getLocation(),
8871 diag::err_covariant_return_type_class_type_more_qualified)
8872 << New->getDeclName() << NewTy << OldTy;
8873 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8874 return true;
8875 };
Mike Stump11289f42009-09-09 15:08:12 +00008876
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008877 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008878}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008879
Douglas Gregor21920e372009-12-01 17:24:26 +00008880/// \brief Mark the given method pure.
8881///
8882/// \param Method the method to be marked pure.
8883///
8884/// \param InitRange the source range that covers the "0" initializer.
8885bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008886 SourceLocation EndLoc = InitRange.getEnd();
8887 if (EndLoc.isValid())
8888 Method->setRangeEnd(EndLoc);
8889
Douglas Gregor21920e372009-12-01 17:24:26 +00008890 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8891 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00008892 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008893 }
Douglas Gregor21920e372009-12-01 17:24:26 +00008894
8895 if (!Method->isInvalidDecl())
8896 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8897 << Method->getDeclName() << InitRange;
8898 return true;
8899}
8900
John McCall1f4ee7b2009-12-19 09:28:58 +00008901/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8902/// an initializer for the out-of-line declaration 'Dcl'. The scope
8903/// is a fresh scope pushed for just this purpose.
8904///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008905/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8906/// static data member of class X, names should be looked up in the scope of
8907/// class X.
John McCall48871652010-08-21 09:40:31 +00008908void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008909 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008910 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008911
John McCall1f4ee7b2009-12-19 09:28:58 +00008912 // We should only get called for declarations with scope specifiers, like:
8913 // int foo::bar;
8914 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008915 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008916}
8917
8918/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00008919/// initializer for the out-of-line declaration 'D'.
8920void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008921 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008922 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008923
John McCall1f4ee7b2009-12-19 09:28:58 +00008924 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008925 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008926}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008927
8928/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8929/// C++ if/switch/while/for statement.
8930/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00008931DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008932 // C++ 6.4p2:
8933 // The declarator shall not specify a function or an array.
8934 // The type-specifier-seq shall not contain typedef and shall not declare a
8935 // new class or enumeration.
8936 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8937 "Parser allowed 'typedef' as storage class of condition decl.");
8938
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008939 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00008940 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
8941 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008942
8943 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
8944 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
8945 // would be created and CXXConditionDeclExpr wants a VarDecl.
8946 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
8947 << D.getSourceRange();
8948 return DeclResult();
8949 } else if (OwnedTag && OwnedTag->isDefinition()) {
8950 // The type-specifier-seq shall not declare a new class or enumeration.
8951 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
8952 }
8953
John McCall48871652010-08-21 09:40:31 +00008954 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008955 if (!Dcl)
8956 return DeclResult();
8957
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008958 return Dcl;
8959}
Anders Carlssonf98849e2009-12-02 17:15:43 +00008960
Douglas Gregor88d292c2010-05-13 16:44:06 +00008961void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8962 bool DefinitionRequired) {
8963 // Ignore any vtable uses in unevaluated operands or for classes that do
8964 // not have a vtable.
8965 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8966 CurContext->isDependentContext() ||
8967 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00008968 return;
8969
Douglas Gregor88d292c2010-05-13 16:44:06 +00008970 // Try to insert this class into the map.
8971 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8972 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8973 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8974 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00008975 // If we already had an entry, check to see if we are promoting this vtable
8976 // to required a definition. If so, we need to reappend to the VTableUses
8977 // list, since we may have already processed the first entry.
8978 if (DefinitionRequired && !Pos.first->second) {
8979 Pos.first->second = true;
8980 } else {
8981 // Otherwise, we can early exit.
8982 return;
8983 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008984 }
8985
8986 // Local classes need to have their virtual members marked
8987 // immediately. For all other classes, we mark their virtual members
8988 // at the end of the translation unit.
8989 if (Class->isLocalClass())
8990 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00008991 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00008992 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00008993}
8994
Douglas Gregor88d292c2010-05-13 16:44:06 +00008995bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008996 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00008997 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00008998
Douglas Gregor88d292c2010-05-13 16:44:06 +00008999 // Note: The VTableUses vector could grow as a result of marking
9000 // the members of a class as "used", so we check the size each
9001 // time through the loop and prefer indices (with are stable) to
9002 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00009003 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009004 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00009005 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00009006 if (!Class)
9007 continue;
9008
9009 SourceLocation Loc = VTableUses[I].second;
9010
9011 // If this class has a key function, but that key function is
9012 // defined in another translation unit, we don't need to emit the
9013 // vtable even though we're using it.
9014 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009015 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00009016 switch (KeyFunction->getTemplateSpecializationKind()) {
9017 case TSK_Undeclared:
9018 case TSK_ExplicitSpecialization:
9019 case TSK_ExplicitInstantiationDeclaration:
9020 // The key function is in another translation unit.
9021 continue;
9022
9023 case TSK_ExplicitInstantiationDefinition:
9024 case TSK_ImplicitInstantiation:
9025 // We will be instantiating the key function.
9026 break;
9027 }
9028 } else if (!KeyFunction) {
9029 // If we have a class with no key function that is the subject
9030 // of an explicit instantiation declaration, suppress the
9031 // vtable; it will live with the explicit instantiation
9032 // definition.
9033 bool IsExplicitInstantiationDeclaration
9034 = Class->getTemplateSpecializationKind()
9035 == TSK_ExplicitInstantiationDeclaration;
9036 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9037 REnd = Class->redecls_end();
9038 R != REnd; ++R) {
9039 TemplateSpecializationKind TSK
9040 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9041 if (TSK == TSK_ExplicitInstantiationDeclaration)
9042 IsExplicitInstantiationDeclaration = true;
9043 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9044 IsExplicitInstantiationDeclaration = false;
9045 break;
9046 }
9047 }
9048
9049 if (IsExplicitInstantiationDeclaration)
9050 continue;
9051 }
9052
9053 // Mark all of the virtual members of this class as referenced, so
9054 // that we can build a vtable. Then, tell the AST consumer that a
9055 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00009056 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009057 MarkVirtualMembersReferenced(Loc, Class);
9058 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9059 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9060
9061 // Optionally warn if we're emitting a weak vtable.
9062 if (Class->getLinkage() == ExternalLinkage &&
9063 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009064 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00009065 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9066 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00009067 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009068 VTableUses.clear();
9069
Douglas Gregor97509692011-04-22 22:25:37 +00009070 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00009071}
Anders Carlsson82fccd02009-12-07 08:24:59 +00009072
Rafael Espindola5b334082010-03-26 00:36:59 +00009073void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9074 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00009075 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9076 e = RD->method_end(); i != e; ++i) {
9077 CXXMethodDecl *MD = *i;
9078
9079 // C++ [basic.def.odr]p2:
9080 // [...] A virtual member function is used if it is not pure. [...]
9081 if (MD->isVirtual() && !MD->isPure())
9082 MarkDeclarationReferenced(Loc, MD);
9083 }
Rafael Espindola5b334082010-03-26 00:36:59 +00009084
9085 // Only classes that have virtual bases need a VTT.
9086 if (RD->getNumVBases() == 0)
9087 return;
9088
9089 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9090 e = RD->bases_end(); i != e; ++i) {
9091 const CXXRecordDecl *Base =
9092 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00009093 if (Base->getNumVBases() == 0)
9094 continue;
9095 MarkVirtualMembersReferenced(Loc, Base);
9096 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00009097}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009098
9099/// SetIvarInitializers - This routine builds initialization ASTs for the
9100/// Objective-C implementation whose ivars need be initialized.
9101void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9102 if (!getLangOptions().CPlusPlus)
9103 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00009104 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009105 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9106 CollectIvarsToConstructOrDestruct(OID, ivars);
9107 if (ivars.empty())
9108 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00009109 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009110 for (unsigned i = 0; i < ivars.size(); i++) {
9111 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00009112 if (Field->isInvalidDecl())
9113 continue;
9114
Alexis Hunt1d792652011-01-08 20:30:50 +00009115 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009116 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9117 InitializationKind InitKind =
9118 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9119
9120 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00009121 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00009122 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00009123 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009124 // Note, MemberInit could actually come back empty if no initialization
9125 // is required (e.g., because it would call a trivial default constructor)
9126 if (!MemberInit.get() || MemberInit.isInvalid())
9127 continue;
John McCallacf0ee52010-10-08 02:01:28 +00009128
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009129 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00009130 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9131 SourceLocation(),
9132 MemberInit.takeAs<Expr>(),
9133 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009134 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00009135
9136 // Be sure that the destructor is accessible and is marked as referenced.
9137 if (const RecordType *RecordTy
9138 = Context.getBaseElementType(Field->getType())
9139 ->getAs<RecordType>()) {
9140 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00009141 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00009142 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9143 CheckDestructorAccess(Field->getLocation(), Destructor,
9144 PDiag(diag::err_access_dtor_ivar)
9145 << Context.getBaseElementType(Field->getType()));
9146 }
9147 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009148 }
9149 ObjCImplementation->setIvarInitializers(Context,
9150 AllToInit.data(), AllToInit.size());
9151 }
9152}
Alexis Hunt6118d662011-05-04 05:57:24 +00009153
Alexis Hunt27a761d2011-05-04 23:29:54 +00009154static
9155void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9156 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9157 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9158 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9159 Sema &S) {
9160 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9161 CE = Current.end();
9162 if (Ctor->isInvalidDecl())
9163 return;
9164
9165 const FunctionDecl *FNTarget = 0;
9166 CXXConstructorDecl *Target;
9167
9168 // We ignore the result here since if we don't have a body, Target will be
9169 // null below.
9170 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9171 Target
9172= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9173
9174 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9175 // Avoid dereferencing a null pointer here.
9176 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9177
9178 if (!Current.insert(Canonical))
9179 return;
9180
9181 // We know that beyond here, we aren't chaining into a cycle.
9182 if (!Target || !Target->isDelegatingConstructor() ||
9183 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9184 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9185 Valid.insert(*CI);
9186 Current.clear();
9187 // We've hit a cycle.
9188 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9189 Current.count(TCanonical)) {
9190 // If we haven't diagnosed this cycle yet, do so now.
9191 if (!Invalid.count(TCanonical)) {
9192 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00009193 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00009194 << Ctor;
9195
9196 // Don't add a note for a function delegating directo to itself.
9197 if (TCanonical != Canonical)
9198 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9199
9200 CXXConstructorDecl *C = Target;
9201 while (C->getCanonicalDecl() != Canonical) {
9202 (void)C->getTargetConstructor()->hasBody(FNTarget);
9203 assert(FNTarget && "Ctor cycle through bodiless function");
9204
9205 C
9206 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9207 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9208 }
9209 }
9210
9211 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9212 Invalid.insert(*CI);
9213 Current.clear();
9214 } else {
9215 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9216 }
9217}
9218
9219
Alexis Hunt6118d662011-05-04 05:57:24 +00009220void Sema::CheckDelegatingCtorCycles() {
9221 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9222
Alexis Hunt27a761d2011-05-04 23:29:54 +00009223 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9224 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00009225
9226 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00009227 I = DelegatingCtorDecls.begin(),
9228 E = DelegatingCtorDecls.end();
9229 I != E; ++I) {
9230 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00009231 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00009232
9233 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9234 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00009235}