blob: 29e81d3f7f3f5578eb22b162cf1979eaa5b26778 [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");
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000116 // If we have an MSAny spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny)
118 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.
126 if (EST == EST_MSAny || EST == EST_None) {
127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
132 // If this function has a basic noexcept, it doesn't affect the outcome.
133 if (EST == EST_BasicNoexcept)
134 return;
135
136 // If we have a throw-all spec at this point, ignore the function.
137 if (ComputedEST == EST_None)
138 return;
139
140 // If we're still at noexcept(true) and there's a nothrow() callee,
141 // change to that specification.
142 if (EST == EST_DynamicNone) {
143 if (ComputedEST == EST_BasicNoexcept)
144 ComputedEST = EST_DynamicNone;
145 return;
146 }
147
148 // Check out noexcept specs.
149 if (EST == EST_ComputedNoexcept) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000150 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000151 assert(NR != FunctionProtoType::NR_NoNoexcept &&
152 "Must have noexcept result for EST_ComputedNoexcept.");
153 assert(NR != FunctionProtoType::NR_Dependent &&
154 "Should not generate implicit declarations for dependent cases, "
155 "and don't know how to handle them anyway.");
156
157 // noexcept(false) -> no spec on the new function
158 if (NR == FunctionProtoType::NR_Throw) {
159 ClearExceptions();
160 ComputedEST = EST_None;
161 }
162 // noexcept(true) won't change anything either.
163 return;
164 }
165
166 assert(EST == EST_Dynamic && "EST case not considered earlier.");
167 assert(ComputedEST != EST_None &&
168 "Shouldn't collect exceptions when throw-all is guaranteed.");
169 ComputedEST = EST_Dynamic;
170 // Record the exceptions in this function's exception specification.
171 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
172 EEnd = Proto->exception_end();
173 E != EEnd; ++E)
Alexis Hunt913820d2011-05-13 06:10:58 +0000174 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 Exceptions.push_back(*E);
176}
177
Anders Carlssonc80a1272009-08-25 02:29:20 +0000178bool
John McCallb268a282010-08-23 23:25:46 +0000179Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000180 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000181 if (RequireCompleteType(Param->getLocation(), Param->getType(),
182 diag::err_typecheck_decl_incomplete_type)) {
183 Param->setInvalidDecl();
184 return true;
185 }
186
Anders Carlssonc80a1272009-08-25 02:29:20 +0000187 // C++ [dcl.fct.default]p5
188 // A default argument expression is implicitly converted (clause
189 // 4) to the parameter type. The default argument expression has
190 // the same semantic constraints as the initializer expression in
191 // a declaration of a variable of the parameter type, using the
192 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000193 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
194 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000195 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
196 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000197 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000198 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000199 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000200 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000201 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000202 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000203
John McCallacf0ee52010-10-08 02:01:28 +0000204 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000205 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000206
Anders Carlssonc80a1272009-08-25 02:29:20 +0000207 // Okay: add the default argument to the parameter
208 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000209
Douglas Gregor758cb672010-10-12 18:23:32 +0000210 // We have already instantiated this parameter; provide each of the
211 // instantiations with the uninstantiated default argument.
212 UnparsedDefaultArgInstantiationsMap::iterator InstPos
213 = UnparsedDefaultArgInstantiations.find(Param);
214 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
215 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
216 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
217
218 // We're done tracking this parameter's instantiations.
219 UnparsedDefaultArgInstantiations.erase(InstPos);
220 }
221
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000222 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000223}
224
Chris Lattner58258242008-04-10 02:22:51 +0000225/// ActOnParamDefaultArgument - Check whether the default argument
226/// provided for a function parameter is well-formed. If so, attach it
227/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000228void
John McCall48871652010-08-21 09:40:31 +0000229Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000230 Expr *DefaultArg) {
231 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000232 return;
Mike Stump11289f42009-09-09 15:08:12 +0000233
John McCall48871652010-08-21 09:40:31 +0000234 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000235 UnparsedDefaultArgLocs.erase(Param);
236
Chris Lattner199abbc2008-04-08 05:04:30 +0000237 // Default arguments are only permitted in C++
238 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000239 Diag(EqualLoc, diag::err_param_default_argument)
240 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000241 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000242 return;
243 }
244
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000245 // Check for unexpanded parameter packs.
246 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
247 Param->setInvalidDecl();
248 return;
249 }
250
Anders Carlssonf1c26952009-08-25 01:02:06 +0000251 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000252 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
253 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000254 Param->setInvalidDecl();
255 return;
256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
John McCallb268a282010-08-23 23:25:46 +0000258 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000259}
260
Douglas Gregor58354032008-12-24 00:01:03 +0000261/// ActOnParamUnparsedDefaultArgument - We've seen a default
262/// argument for a function parameter, but we can't parse it yet
263/// because we're inside a class definition. Note that this default
264/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000265void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000266 SourceLocation EqualLoc,
267 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000268 if (!param)
269 return;
Mike Stump11289f42009-09-09 15:08:12 +0000270
John McCall48871652010-08-21 09:40:31 +0000271 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000272 if (Param)
273 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlsson84613c42009-06-12 16:51:40 +0000275 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000276}
277
Douglas Gregor4d87df52008-12-16 21:30:33 +0000278/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
279/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000280void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000281 if (!param)
282 return;
Mike Stump11289f42009-09-09 15:08:12 +0000283
John McCall48871652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Anders Carlsson84613c42009-06-12 16:51:40 +0000286 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000287
Anders Carlsson84613c42009-06-12 16:51:40 +0000288 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000289}
290
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000291/// CheckExtraCXXDefaultArguments - Check for any extra default
292/// arguments in the declarator, which is not a function declaration
293/// or definition and therefore is not permitted to have default
294/// arguments. This routine should be invoked for every declarator
295/// that is not a function declaration or definition.
296void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
297 // C++ [dcl.fct.default]p3
298 // A default argument expression shall be specified only in the
299 // parameter-declaration-clause of a function declaration or in a
300 // template-parameter (14.1). It shall not be specified for a
301 // parameter pack. If it is specified in a
302 // parameter-declaration-clause, it shall not occur within a
303 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000304 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000305 DeclaratorChunk &chunk = D.getTypeObject(i);
306 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000307 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
308 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000309 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000310 if (Param->hasUnparsedDefaultArg()) {
311 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000312 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
313 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
314 delete Toks;
315 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000316 } else if (Param->getDefaultArg()) {
317 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
318 << Param->getDefaultArg()->getSourceRange();
319 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000320 }
321 }
322 }
323 }
324}
325
Chris Lattner199abbc2008-04-08 05:04:30 +0000326// MergeCXXFunctionDecl - Merge two declarations of the same C++
327// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000328// type. Subroutine of MergeFunctionDecl. Returns true if there was an
329// error, false otherwise.
330bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
331 bool Invalid = false;
332
Chris Lattner199abbc2008-04-08 05:04:30 +0000333 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000334 // For non-template functions, default arguments can be added in
335 // later declarations of a function in the same
336 // scope. Declarations in different scopes have completely
337 // distinct sets of default arguments. That is, declarations in
338 // inner scopes do not acquire default arguments from
339 // declarations in outer scopes, and vice versa. In a given
340 // function declaration, all parameters subsequent to a
341 // parameter with a default argument shall have default
342 // arguments supplied in this or previous declarations. A
343 // default argument shall not be redefined by a later
344 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000345 //
346 // C++ [dcl.fct.default]p6:
347 // Except for member functions of class templates, the default arguments
348 // in a member function definition that appears outside of the class
349 // definition are added to the set of default arguments provided by the
350 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000351 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
352 ParmVarDecl *OldParam = Old->getParamDecl(p);
353 ParmVarDecl *NewParam = New->getParamDecl(p);
354
Douglas Gregorc732aba2009-09-11 18:44:32 +0000355 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000356
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000357 unsigned DiagDefaultParamID =
358 diag::err_param_default_argument_redefinition;
359
360 // MSVC accepts that default parameters be redefined for member functions
361 // of template class. The new default parameter's value is ignored.
362 Invalid = true;
363 if (getLangOptions().Microsoft) {
364 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
365 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000366 // Merge the old default argument into the new parameter.
367 NewParam->setHasInheritedDefaultArg();
368 if (OldParam->hasUninstantiatedDefaultArg())
369 NewParam->setUninstantiatedDefaultArg(
370 OldParam->getUninstantiatedDefaultArg());
371 else
372 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000373 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000374 Invalid = false;
375 }
376 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000377
Francois Pichet8cb243a2011-04-10 04:58:30 +0000378 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
379 // hint here. Alternatively, we could walk the type-source information
380 // for NewParam to find the last source location in the type... but it
381 // isn't worth the effort right now. This is the kind of test case that
382 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000383 // int f(int);
384 // void g(int (*fp)(int) = f);
385 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000386 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000387 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000388
389 // Look for the function declaration where the default argument was
390 // actually written, which may be a declaration prior to Old.
391 for (FunctionDecl *Older = Old->getPreviousDeclaration();
392 Older; Older = Older->getPreviousDeclaration()) {
393 if (!Older->getParamDecl(p)->hasDefaultArg())
394 break;
395
396 OldParam = Older->getParamDecl(p);
397 }
398
399 Diag(OldParam->getLocation(), diag::note_previous_definition)
400 << OldParam->getDefaultArgRange();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000401 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000402 // Merge the old default argument into the new parameter.
403 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000404 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000405 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000406 if (OldParam->hasUninstantiatedDefaultArg())
407 NewParam->setUninstantiatedDefaultArg(
408 OldParam->getUninstantiatedDefaultArg());
409 else
John McCalle61b02b2010-05-04 01:53:42 +0000410 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000411 } else if (NewParam->hasDefaultArg()) {
412 if (New->getDescribedFunctionTemplate()) {
413 // Paragraph 4, quoted above, only applies to non-template functions.
414 Diag(NewParam->getLocation(),
415 diag::err_param_default_argument_template_redecl)
416 << NewParam->getDefaultArgRange();
417 Diag(Old->getLocation(), diag::note_template_prev_declaration)
418 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000419 } else if (New->getTemplateSpecializationKind()
420 != TSK_ImplicitInstantiation &&
421 New->getTemplateSpecializationKind() != TSK_Undeclared) {
422 // C++ [temp.expr.spec]p21:
423 // Default function arguments shall not be specified in a declaration
424 // or a definition for one of the following explicit specializations:
425 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000426 // - the explicit specialization of a member function template;
427 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000428 // template where the class template specialization to which the
429 // member function specialization belongs is implicitly
430 // instantiated.
431 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
432 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
433 << New->getDeclName()
434 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000435 } else if (New->getDeclContext()->isDependentContext()) {
436 // C++ [dcl.fct.default]p6 (DR217):
437 // Default arguments for a member function of a class template shall
438 // be specified on the initial declaration of the member function
439 // within the class template.
440 //
441 // Reading the tea leaves a bit in DR217 and its reference to DR205
442 // leads me to the conclusion that one cannot add default function
443 // arguments for an out-of-line definition of a member function of a
444 // dependent type.
445 int WhichKind = 2;
446 if (CXXRecordDecl *Record
447 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
448 if (Record->getDescribedClassTemplate())
449 WhichKind = 0;
450 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
451 WhichKind = 1;
452 else
453 WhichKind = 2;
454 }
455
456 Diag(NewParam->getLocation(),
457 diag::err_param_default_argument_member_template_redecl)
458 << WhichKind
459 << NewParam->getDefaultArgRange();
Alexis Huntd051b872011-05-26 01:26:05 +0000460 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
461 CXXSpecialMember NewSM = getSpecialMember(Ctor),
462 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
463 if (NewSM != OldSM) {
464 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
465 << NewParam->getDefaultArgRange() << NewSM;
466 Diag(Old->getLocation(), diag::note_previous_declaration_special)
467 << OldSM;
468 }
Douglas Gregorc732aba2009-09-11 18:44:32 +0000469 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000470 }
471 }
472
Douglas Gregorf40863c2010-02-12 07:32:17 +0000473 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000474 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000475
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000476 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000477}
478
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000479/// \brief Merge the exception specifications of two variable declarations.
480///
481/// This is called when there's a redeclaration of a VarDecl. The function
482/// checks if the redeclaration might have an exception specification and
483/// validates compatibility and merges the specs if necessary.
484void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
485 // Shortcut if exceptions are disabled.
486 if (!getLangOptions().CXXExceptions)
487 return;
488
489 assert(Context.hasSameType(New->getType(), Old->getType()) &&
490 "Should only be called if types are otherwise the same.");
491
492 QualType NewType = New->getType();
493 QualType OldType = Old->getType();
494
495 // We're only interested in pointers and references to functions, as well
496 // as pointers to member functions.
497 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
498 NewType = R->getPointeeType();
499 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
500 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
501 NewType = P->getPointeeType();
502 OldType = OldType->getAs<PointerType>()->getPointeeType();
503 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
504 NewType = M->getPointeeType();
505 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
506 }
507
508 if (!NewType->isFunctionProtoType())
509 return;
510
511 // There's lots of special cases for functions. For function pointers, system
512 // libraries are hopefully not as broken so that we don't need these
513 // workarounds.
514 if (CheckEquivalentExceptionSpec(
515 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
516 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
517 New->setInvalidDecl();
518 }
519}
520
Chris Lattner199abbc2008-04-08 05:04:30 +0000521/// CheckCXXDefaultArguments - Verify that the default arguments for a
522/// function declaration are well-formed according to C++
523/// [dcl.fct.default].
524void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
525 unsigned NumParams = FD->getNumParams();
526 unsigned p;
527
528 // Find first parameter with a default argument
529 for (p = 0; p < NumParams; ++p) {
530 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000531 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000532 break;
533 }
534
535 // C++ [dcl.fct.default]p4:
536 // In a given function declaration, all parameters
537 // subsequent to a parameter with a default argument shall
538 // have default arguments supplied in this or previous
539 // declarations. A default argument shall not be redefined
540 // by a later declaration (not even to the same value).
541 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000542 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000543 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000544 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000545 if (Param->isInvalidDecl())
546 /* We already complained about this parameter. */;
547 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000548 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000549 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000550 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000551 else
Mike Stump11289f42009-09-09 15:08:12 +0000552 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000553 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattner199abbc2008-04-08 05:04:30 +0000555 LastMissingDefaultArg = p;
556 }
557 }
558
559 if (LastMissingDefaultArg > 0) {
560 // Some default arguments were missing. Clear out all of the
561 // default arguments up to (and including) the last missing
562 // default argument, so that we leave the function parameters
563 // in a semantically valid state.
564 for (p = 0; p <= LastMissingDefaultArg; ++p) {
565 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000566 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000567 Param->setDefaultArg(0);
568 }
569 }
570 }
571}
Douglas Gregor556877c2008-04-13 21:30:24 +0000572
Douglas Gregor61956c42008-10-31 09:07:45 +0000573/// isCurrentClassName - Determine whether the identifier II is the
574/// name of the class type currently being defined. In the case of
575/// nested classes, this will only return true if II is the name of
576/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000577bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
578 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000579 assert(getLangOptions().CPlusPlus && "No class names in C!");
580
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000581 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000582 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000583 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000584 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
585 } else
586 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
587
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000588 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000589 return &II == CurDecl->getIdentifier();
590 else
591 return false;
592}
593
Mike Stump11289f42009-09-09 15:08:12 +0000594/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000595///
596/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
597/// and returns NULL otherwise.
598CXXBaseSpecifier *
599Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
600 SourceRange SpecifierRange,
601 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000602 TypeSourceInfo *TInfo,
603 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000604 QualType BaseType = TInfo->getType();
605
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 // C++ [class.union]p1:
607 // A union shall not have base classes.
608 if (Class->isUnion()) {
609 Diag(Class->getLocation(), diag::err_base_clause_on_union)
610 << SpecifierRange;
611 return 0;
612 }
613
Douglas Gregor752a5952011-01-03 22:36:02 +0000614 if (EllipsisLoc.isValid() &&
615 !TInfo->getType()->containsUnexpandedParameterPack()) {
616 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
617 << TInfo->getTypeLoc().getSourceRange();
618 EllipsisLoc = SourceLocation();
619 }
620
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000622 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000623 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000624 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000625
626 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000627
628 // Base specifiers must be record types.
629 if (!BaseType->isRecordType()) {
630 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
631 return 0;
632 }
633
634 // C++ [class.union]p1:
635 // A union shall not be used as a base class.
636 if (BaseType->isUnionType()) {
637 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
638 return 0;
639 }
640
641 // C++ [class.derived]p2:
642 // The class-name in a base-specifier shall not be an incompletely
643 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000644 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000645 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000646 << SpecifierRange)) {
647 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000649 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000650
Eli Friedmanc96d4962009-08-15 21:55:26 +0000651 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000652 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000653 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000654 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000655 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000656 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
657 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000658
Anders Carlsson65c76d32011-03-25 14:55:14 +0000659 // C++ [class]p3:
660 // If a class is marked final and it appears as a base-type-specifier in
661 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000662 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000663 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
664 << CXXBaseDecl->getDeclName();
665 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
666 << CXXBaseDecl->getDeclName();
667 return 0;
668 }
669
John McCall3696dcb2010-08-17 07:23:57 +0000670 if (BaseDecl->isInvalidDecl())
671 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000672
673 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000674 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000675 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000676 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000677}
678
Douglas Gregor556877c2008-04-13 21:30:24 +0000679/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
680/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000681/// example:
682/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000683/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000684BaseResult
John McCall48871652010-08-21 09:40:31 +0000685Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000686 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000687 ParsedType basetype, SourceLocation BaseLoc,
688 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000689 if (!classdecl)
690 return true;
691
Douglas Gregorc40290e2009-03-09 23:48:35 +0000692 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000693 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000694 if (!Class)
695 return true;
696
Nick Lewycky19b9f952010-07-26 16:56:01 +0000697 TypeSourceInfo *TInfo = 0;
698 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000699
Douglas Gregor752a5952011-01-03 22:36:02 +0000700 if (EllipsisLoc.isInvalid() &&
701 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000702 UPPC_BaseType))
703 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000704
Douglas Gregor463421d2009-03-03 04:44:36 +0000705 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000706 Virtual, Access, TInfo,
707 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000708 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000709
Douglas Gregor463421d2009-03-03 04:44:36 +0000710 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000711}
Douglas Gregor556877c2008-04-13 21:30:24 +0000712
Douglas Gregor463421d2009-03-03 04:44:36 +0000713/// \brief Performs the actual work of attaching the given base class
714/// specifiers to a C++ class.
715bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
716 unsigned NumBases) {
717 if (NumBases == 0)
718 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000719
720 // Used to keep track of which base types we have already seen, so
721 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000722 // that the key is always the unqualified canonical type of the base
723 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000724 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
725
726 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000727 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000728 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000729 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000730 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000731 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000732 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000733 if (!Class->hasObjectMember()) {
734 if (const RecordType *FDTTy =
735 NewBaseType.getTypePtr()->getAs<RecordType>())
736 if (FDTTy->getDecl()->hasObjectMember())
737 Class->setHasObjectMember(true);
738 }
739
Douglas Gregor29a92472008-10-22 17:49:05 +0000740 if (KnownBaseTypes[NewBaseType]) {
741 // C++ [class.mi]p3:
742 // A class shall not be specified as a direct base class of a
743 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000744 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000745 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000746 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000747 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000748
749 // Delete the duplicate base class specifier; we're going to
750 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000751 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000752
753 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000754 } else {
755 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000756 KnownBaseTypes[NewBaseType] = Bases[idx];
757 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000758 }
759 }
760
761 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000762 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000763
764 // Delete the remaining (good) base class specifiers, since their
765 // data has been copied into the CXXRecordDecl.
766 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000767 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000768
769 return Invalid;
770}
771
772/// ActOnBaseSpecifiers - Attach the given base specifiers to the
773/// class, after checking whether there are any duplicate base
774/// classes.
John McCall48871652010-08-21 09:40:31 +0000775void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000776 unsigned NumBases) {
777 if (!ClassDecl || !Bases || !NumBases)
778 return;
779
780 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000781 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000782 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000783}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000784
John McCalle78aac42010-03-10 03:28:59 +0000785static CXXRecordDecl *GetClassForType(QualType T) {
786 if (const RecordType *RT = T->getAs<RecordType>())
787 return cast<CXXRecordDecl>(RT->getDecl());
788 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
789 return ICT->getDecl();
790 else
791 return 0;
792}
793
Douglas Gregor36d1b142009-10-06 17:59:45 +0000794/// \brief Determine whether the type \p Derived is a C++ class that is
795/// derived from the type \p Base.
796bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
797 if (!getLangOptions().CPlusPlus)
798 return false;
John McCalle78aac42010-03-10 03:28:59 +0000799
800 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
801 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000802 return false;
803
John McCalle78aac42010-03-10 03:28:59 +0000804 CXXRecordDecl *BaseRD = GetClassForType(Base);
805 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000806 return false;
807
John McCall67da35c2010-02-04 22:26:26 +0000808 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
809 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000810}
811
812/// \brief Determine whether the type \p Derived is a C++ class that is
813/// derived from the type \p Base.
814bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
815 if (!getLangOptions().CPlusPlus)
816 return false;
817
John McCalle78aac42010-03-10 03:28:59 +0000818 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
819 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000820 return false;
821
John McCalle78aac42010-03-10 03:28:59 +0000822 CXXRecordDecl *BaseRD = GetClassForType(Base);
823 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000824 return false;
825
Douglas Gregor36d1b142009-10-06 17:59:45 +0000826 return DerivedRD->isDerivedFrom(BaseRD, Paths);
827}
828
Anders Carlssona70cff62010-04-24 19:06:50 +0000829void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000830 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000831 assert(BasePathArray.empty() && "Base path array must be empty!");
832 assert(Paths.isRecordingPaths() && "Must record paths!");
833
834 const CXXBasePath &Path = Paths.front();
835
836 // We first go backward and check if we have a virtual base.
837 // FIXME: It would be better if CXXBasePath had the base specifier for
838 // the nearest virtual base.
839 unsigned Start = 0;
840 for (unsigned I = Path.size(); I != 0; --I) {
841 if (Path[I - 1].Base->isVirtual()) {
842 Start = I - 1;
843 break;
844 }
845 }
846
847 // Now add all bases.
848 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000849 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000850}
851
Douglas Gregor88d292c2010-05-13 16:44:06 +0000852/// \brief Determine whether the given base path includes a virtual
853/// base class.
John McCallcf142162010-08-07 06:22:56 +0000854bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
855 for (CXXCastPath::const_iterator B = BasePath.begin(),
856 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000857 B != BEnd; ++B)
858 if ((*B)->isVirtual())
859 return true;
860
861 return false;
862}
863
Douglas Gregor36d1b142009-10-06 17:59:45 +0000864/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
865/// conversion (where Derived and Base are class types) is
866/// well-formed, meaning that the conversion is unambiguous (and
867/// that all of the base classes are accessible). Returns true
868/// and emits a diagnostic if the code is ill-formed, returns false
869/// otherwise. Loc is the location where this routine should point to
870/// if there is an error, and Range is the source range to highlight
871/// if there is an error.
872bool
873Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000874 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000875 unsigned AmbigiousBaseConvID,
876 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000877 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000878 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000879 // First, determine whether the path from Derived to Base is
880 // ambiguous. This is slightly more expensive than checking whether
881 // the Derived to Base conversion exists, because here we need to
882 // explore multiple paths to determine if there is an ambiguity.
883 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
884 /*DetectVirtual=*/false);
885 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
886 assert(DerivationOkay &&
887 "Can only be used with a derived-to-base conversion");
888 (void)DerivationOkay;
889
890 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000891 if (InaccessibleBaseID) {
892 // Check that the base class can be accessed.
893 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
894 InaccessibleBaseID)) {
895 case AR_inaccessible:
896 return true;
897 case AR_accessible:
898 case AR_dependent:
899 case AR_delayed:
900 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000901 }
John McCall5b0829a2010-02-10 09:31:12 +0000902 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000903
904 // Build a base path if necessary.
905 if (BasePath)
906 BuildBasePathArray(Paths, *BasePath);
907 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000908 }
909
910 // We know that the derived-to-base conversion is ambiguous, and
911 // we're going to produce a diagnostic. Perform the derived-to-base
912 // search just one more time to compute all of the possible paths so
913 // that we can print them out. This is more expensive than any of
914 // the previous derived-to-base checks we've done, but at this point
915 // performance isn't as much of an issue.
916 Paths.clear();
917 Paths.setRecordingPaths(true);
918 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
919 assert(StillOkay && "Can only be used with a derived-to-base conversion");
920 (void)StillOkay;
921
922 // Build up a textual representation of the ambiguous paths, e.g.,
923 // D -> B -> A, that will be used to illustrate the ambiguous
924 // conversions in the diagnostic. We only print one of the paths
925 // to each base class subobject.
926 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
927
928 Diag(Loc, AmbigiousBaseConvID)
929 << Derived << Base << PathDisplayStr << Range << Name;
930 return true;
931}
932
933bool
934Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000935 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000936 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000937 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000938 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000939 IgnoreAccess ? 0
940 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000941 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000942 Loc, Range, DeclarationName(),
943 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000944}
945
946
947/// @brief Builds a string representing ambiguous paths from a
948/// specific derived class to different subobjects of the same base
949/// class.
950///
951/// This function builds a string that can be used in error messages
952/// to show the different paths that one can take through the
953/// inheritance hierarchy to go from the derived class to different
954/// subobjects of a base class. The result looks something like this:
955/// @code
956/// struct D -> struct B -> struct A
957/// struct D -> struct C -> struct A
958/// @endcode
959std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
960 std::string PathDisplayStr;
961 std::set<unsigned> DisplayedPaths;
962 for (CXXBasePaths::paths_iterator Path = Paths.begin();
963 Path != Paths.end(); ++Path) {
964 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
965 // We haven't displayed a path to this particular base
966 // class subobject yet.
967 PathDisplayStr += "\n ";
968 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
969 for (CXXBasePath::const_iterator Element = Path->begin();
970 Element != Path->end(); ++Element)
971 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
972 }
973 }
974
975 return PathDisplayStr;
976}
977
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000978//===----------------------------------------------------------------------===//
979// C++ class member Handling
980//===----------------------------------------------------------------------===//
981
Abramo Bagnarad7340582010-06-05 05:09:32 +0000982/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000983Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
984 SourceLocation ASLoc,
985 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000986 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000987 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000988 ASLoc, ColonLoc);
989 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000990 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000991}
992
Anders Carlssonfd835532011-01-20 05:57:14 +0000993/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000994void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000995 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
996 if (!MD || !MD->isVirtual())
997 return;
998
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000999 if (MD->isDependentContext())
1000 return;
1001
Anders Carlssonfd835532011-01-20 05:57:14 +00001002 // C++0x [class.virtual]p3:
1003 // If a virtual function is marked with the virt-specifier override and does
1004 // not override a member function of a base class,
1005 // the program is ill-formed.
1006 bool HasOverriddenMethods =
1007 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001008 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001009 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001010 diag::err_function_marked_override_not_overriding)
1011 << MD->getDeclName();
1012 return;
1013 }
1014}
1015
Anders Carlsson3f610c72011-01-20 16:25:36 +00001016/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1017/// function overrides a virtual member function marked 'final', according to
1018/// C++0x [class.virtual]p3.
1019bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1020 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001021 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001022 return false;
1023
1024 Diag(New->getLocation(), diag::err_final_function_overridden)
1025 << New->getDeclName();
1026 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1027 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001028}
1029
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001030/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1031/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1032/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +00001033/// any.
John McCall48871652010-08-21 09:40:31 +00001034Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001035Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001036 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +00001037 ExprTy *BW, const VirtSpecifiers &VS,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001038 ExprTy *InitExpr, bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001039 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001040 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1041 DeclarationName Name = NameInfo.getName();
1042 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001043
1044 // For anonymous bitfields, the location should point to the type.
1045 if (Loc.isInvalid())
1046 Loc = D.getSourceRange().getBegin();
1047
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001048 Expr *BitWidth = static_cast<Expr*>(BW);
1049 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001050
John McCallb1cd7da2010-06-04 08:34:12 +00001051 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001052 assert(!DS.isFriendSpecified());
1053
John McCallb1cd7da2010-06-04 08:34:12 +00001054 bool isFunc = false;
1055 if (D.isFunctionDeclarator())
1056 isFunc = true;
1057 else if (D.getNumTypeObjects() == 0 &&
1058 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +00001059 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +00001060 isFunc = TDType->isFunctionType();
1061 }
1062
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001063 // C++ 9.2p6: A member shall not be declared to have automatic storage
1064 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001065 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1066 // data members and cannot be applied to names declared const or static,
1067 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001068 switch (DS.getStorageClassSpec()) {
1069 case DeclSpec::SCS_unspecified:
1070 case DeclSpec::SCS_typedef:
1071 case DeclSpec::SCS_static:
1072 // FALL THROUGH.
1073 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001074 case DeclSpec::SCS_mutable:
1075 if (isFunc) {
1076 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001077 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001078 else
Chris Lattner3b054132008-11-19 05:08:23 +00001079 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Sebastian Redl8071edb2008-11-17 23:24:37 +00001081 // FIXME: It would be nicer if the keyword was ignored only for this
1082 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001083 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001084 }
1085 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001086 default:
1087 if (DS.getStorageClassSpecLoc().isValid())
1088 Diag(DS.getStorageClassSpecLoc(),
1089 diag::err_storageclass_invalid_for_member);
1090 else
1091 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1092 D.getMutableDeclSpec().ClearStorageClassSpecs();
1093 }
1094
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001095 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1096 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001097 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001098
1099 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001100 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001101 CXXScopeSpec &SS = D.getCXXScopeSpec();
1102
Douglas Gregora007d362010-10-13 22:19:53 +00001103 if (SS.isSet() && !SS.isInvalid()) {
1104 // The user provided a superfluous scope specifier inside a class
1105 // definition:
1106 //
1107 // class X {
1108 // int X::member;
1109 // };
1110 DeclContext *DC = 0;
1111 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1112 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1113 << Name << FixItHint::CreateRemoval(SS.getRange());
1114 else
1115 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1116 << Name << SS.getRange();
1117
1118 SS.clear();
1119 }
1120
Douglas Gregor3447e762009-08-20 22:52:58 +00001121 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001122 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001123 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1124 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001125 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001126 } else {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001127 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001128 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001129 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001130 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001131
1132 // Non-instance-fields can't have a bitfield.
1133 if (BitWidth) {
1134 if (Member->isInvalidDecl()) {
1135 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001136 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001137 // C++ 9.6p3: A bit-field shall not be a static member.
1138 // "static member 'A' cannot be a bit-field"
1139 Diag(Loc, diag::err_static_not_bitfield)
1140 << Name << BitWidth->getSourceRange();
1141 } else if (isa<TypedefDecl>(Member)) {
1142 // "typedef member 'x' cannot be a bit-field"
1143 Diag(Loc, diag::err_typedef_not_bitfield)
1144 << Name << BitWidth->getSourceRange();
1145 } else {
1146 // A function typedef ("typedef int f(); f a;").
1147 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1148 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001149 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001150 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152
Chris Lattnerd26760a2009-03-05 23:01:03 +00001153 BitWidth = 0;
1154 Member->setInvalidDecl();
1155 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001156
1157 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001158
Douglas Gregor3447e762009-08-20 22:52:58 +00001159 // If we have declared a member function template, set the access of the
1160 // templated declaration as well.
1161 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1162 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001163 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001164
Anders Carlsson13a69102011-01-20 04:34:22 +00001165 if (VS.isOverrideSpecified()) {
1166 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1167 if (!MD || !MD->isVirtual()) {
1168 Diag(Member->getLocStart(),
1169 diag::override_keyword_only_allowed_on_virtual_member_functions)
1170 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001171 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001172 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001173 }
1174 if (VS.isFinalSpecified()) {
1175 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1176 if (!MD || !MD->isVirtual()) {
1177 Diag(Member->getLocStart(),
1178 diag::override_keyword_only_allowed_on_virtual_member_functions)
1179 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001180 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001181 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001182 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001183
Douglas Gregorf2f08062011-03-08 17:10:18 +00001184 if (VS.getLastLocation().isValid()) {
1185 // Update the end location of a method that has a virt-specifiers.
1186 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1187 MD->setRangeEnd(VS.getLastLocation());
1188 }
1189
Anders Carlssonc87f8612011-01-20 06:29:02 +00001190 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001191
Douglas Gregor92751d42008-11-17 22:58:34 +00001192 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001193
Douglas Gregor0c880302009-03-11 23:00:04 +00001194 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001195 AddInitializerToDecl(Member, Init, false,
1196 DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001197
Richard Smithb2bc2e62011-02-21 20:05:19 +00001198 FinalizeDeclaration(Member);
1199
John McCall25849ca2011-02-15 07:12:36 +00001200 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001201 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001202 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001203}
1204
Douglas Gregor15e77a22009-12-31 09:10:24 +00001205/// \brief Find the direct and/or virtual base specifiers that
1206/// correspond to the given base type, for use in base initialization
1207/// within a constructor.
1208static bool FindBaseInitializer(Sema &SemaRef,
1209 CXXRecordDecl *ClassDecl,
1210 QualType BaseType,
1211 const CXXBaseSpecifier *&DirectBaseSpec,
1212 const CXXBaseSpecifier *&VirtualBaseSpec) {
1213 // First, check for a direct base class.
1214 DirectBaseSpec = 0;
1215 for (CXXRecordDecl::base_class_const_iterator Base
1216 = ClassDecl->bases_begin();
1217 Base != ClassDecl->bases_end(); ++Base) {
1218 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1219 // We found a direct base of this type. That's what we're
1220 // initializing.
1221 DirectBaseSpec = &*Base;
1222 break;
1223 }
1224 }
1225
1226 // Check for a virtual base class.
1227 // FIXME: We might be able to short-circuit this if we know in advance that
1228 // there are no virtual bases.
1229 VirtualBaseSpec = 0;
1230 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1231 // We haven't found a base yet; search the class hierarchy for a
1232 // virtual base class.
1233 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1234 /*DetectVirtual=*/false);
1235 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1236 BaseType, Paths)) {
1237 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1238 Path != Paths.end(); ++Path) {
1239 if (Path->back().Base->isVirtual()) {
1240 VirtualBaseSpec = Path->back().Base;
1241 break;
1242 }
1243 }
1244 }
1245 }
1246
1247 return DirectBaseSpec || VirtualBaseSpec;
1248}
1249
Douglas Gregore8381c02008-11-05 04:29:56 +00001250/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001251MemInitResult
John McCall48871652010-08-21 09:40:31 +00001252Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001253 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001254 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001255 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001256 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001257 SourceLocation IdLoc,
1258 SourceLocation LParenLoc,
1259 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001260 SourceLocation RParenLoc,
1261 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001262 if (!ConstructorD)
1263 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001264
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001265 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001266
1267 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001268 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001269 if (!Constructor) {
1270 // The user wrote a constructor initializer on a function that is
1271 // not a C++ constructor. Ignore the error for now, because we may
1272 // have more member initializers coming; we'll diagnose it just
1273 // once in ActOnMemInitializers.
1274 return true;
1275 }
1276
1277 CXXRecordDecl *ClassDecl = Constructor->getParent();
1278
1279 // C++ [class.base.init]p2:
1280 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001281 // constructor's class and, if not found in that scope, are looked
1282 // up in the scope containing the constructor's definition.
1283 // [Note: if the constructor's class contains a member with the
1284 // same name as a direct or virtual base class of the class, a
1285 // mem-initializer-id naming the member or base class and composed
1286 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001287 // mem-initializer-id for the hidden base class may be specified
1288 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001289 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001290 // Look for a member, first.
1291 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001292 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001293 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001294 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001295 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001296
Douglas Gregor44e7df62011-01-04 00:32:56 +00001297 if (Member) {
1298 if (EllipsisLoc.isValid())
1299 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1300 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1301
Francois Pichetd583da02010-12-04 09:14:42 +00001302 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001303 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001304 }
1305
Francois Pichetd583da02010-12-04 09:14:42 +00001306 // Handle anonymous union case.
1307 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001308 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1309 if (EllipsisLoc.isValid())
1310 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1311 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1312
Francois Pichetd583da02010-12-04 09:14:42 +00001313 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1314 NumArgs, IdLoc,
1315 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001316 }
Francois Pichetd583da02010-12-04 09:14:42 +00001317 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001318 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001319 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001320 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001321 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001322
1323 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001324 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001325 } else {
1326 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1327 LookupParsedName(R, S, &SS);
1328
1329 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1330 if (!TyD) {
1331 if (R.isAmbiguous()) return true;
1332
John McCallda6841b2010-04-09 19:01:14 +00001333 // We don't want access-control diagnostics here.
1334 R.suppressDiagnostics();
1335
Douglas Gregora3b624a2010-01-19 06:46:48 +00001336 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1337 bool NotUnknownSpecialization = false;
1338 DeclContext *DC = computeDeclContext(SS, false);
1339 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1340 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1341
1342 if (!NotUnknownSpecialization) {
1343 // When the scope specifier can refer to a member of an unknown
1344 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001345 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1346 SS.getWithLocInContext(Context),
1347 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001348 if (BaseType.isNull())
1349 return true;
1350
Douglas Gregora3b624a2010-01-19 06:46:48 +00001351 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001352 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001353 }
1354 }
1355
Douglas Gregor15e77a22009-12-31 09:10:24 +00001356 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001357 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001358 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1359 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001360 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001361 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001362 // We have found a non-static data member with a similar
1363 // name to what was typed; complain and initialize that
1364 // member.
1365 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1366 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001367 << FixItHint::CreateReplacement(R.getNameLoc(),
1368 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001369 Diag(Member->getLocation(), diag::note_previous_decl)
1370 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001371
1372 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1373 LParenLoc, RParenLoc);
1374 }
1375 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1376 const CXXBaseSpecifier *DirectBaseSpec;
1377 const CXXBaseSpecifier *VirtualBaseSpec;
1378 if (FindBaseInitializer(*this, ClassDecl,
1379 Context.getTypeDeclType(Type),
1380 DirectBaseSpec, VirtualBaseSpec)) {
1381 // We have found a direct or virtual base class with a
1382 // similar name to what was typed; complain and initialize
1383 // that base class.
1384 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1385 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001386 << FixItHint::CreateReplacement(R.getNameLoc(),
1387 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001388
1389 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1390 : VirtualBaseSpec;
1391 Diag(BaseSpec->getSourceRange().getBegin(),
1392 diag::note_base_class_specified_here)
1393 << BaseSpec->getType()
1394 << BaseSpec->getSourceRange();
1395
Douglas Gregor15e77a22009-12-31 09:10:24 +00001396 TyD = Type;
1397 }
1398 }
1399 }
1400
Douglas Gregora3b624a2010-01-19 06:46:48 +00001401 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001402 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1403 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1404 return true;
1405 }
John McCallb5a0d312009-12-21 10:41:20 +00001406 }
1407
Douglas Gregora3b624a2010-01-19 06:46:48 +00001408 if (BaseType.isNull()) {
1409 BaseType = Context.getTypeDeclType(TyD);
1410 if (SS.isSet()) {
1411 NestedNameSpecifier *Qualifier =
1412 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001413
Douglas Gregora3b624a2010-01-19 06:46:48 +00001414 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001415 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001416 }
John McCallb5a0d312009-12-21 10:41:20 +00001417 }
1418 }
Mike Stump11289f42009-09-09 15:08:12 +00001419
John McCallbcd03502009-12-07 02:54:59 +00001420 if (!TInfo)
1421 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001422
John McCallbcd03502009-12-07 02:54:59 +00001423 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001424 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001425}
1426
John McCalle22a04a2009-11-04 23:02:40 +00001427/// Checks an initializer expression for use of uninitialized fields, such as
1428/// containing the field that is being initialized. Returns true if there is an
1429/// uninitialized field was used an updates the SourceLocation parameter; false
1430/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001431static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001432 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001433 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001434 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1435
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001436 if (isa<CallExpr>(S)) {
1437 // Do not descend into function calls or constructors, as the use
1438 // of an uninitialized field may be valid. One would have to inspect
1439 // the contents of the function/ctor to determine if it is safe or not.
1440 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1441 // may be safe, depending on what the function/ctor does.
1442 return false;
1443 }
1444 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1445 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001446
1447 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1448 // The member expression points to a static data member.
1449 assert(VD->isStaticDataMember() &&
1450 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001451 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001452 return false;
1453 }
1454
1455 if (isa<EnumConstantDecl>(RhsField)) {
1456 // The member expression points to an enum.
1457 return false;
1458 }
1459
John McCalle22a04a2009-11-04 23:02:40 +00001460 if (RhsField == LhsField) {
1461 // Initializing a field with itself. Throw a warning.
1462 // But wait; there are exceptions!
1463 // Exception #1: The field may not belong to this record.
1464 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001465 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001466 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1467 // Even though the field matches, it does not belong to this record.
1468 return false;
1469 }
1470 // None of the exceptions triggered; return true to indicate an
1471 // uninitialized field was used.
1472 *L = ME->getMemberLoc();
1473 return true;
1474 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001475 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001476 // sizeof/alignof doesn't reference contents, do not warn.
1477 return false;
1478 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1479 // address-of doesn't reference contents (the pointer may be dereferenced
1480 // in the same expression but it would be rare; and weird).
1481 if (UOE->getOpcode() == UO_AddrOf)
1482 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001483 }
John McCall8322c3a2011-02-13 04:07:26 +00001484 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001485 if (!*it) {
1486 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001487 continue;
1488 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001489 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1490 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001491 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001492 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001493}
1494
John McCallfaf5fb42010-08-26 23:41:50 +00001495MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001496Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001497 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001498 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001499 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001500 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1501 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1502 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001503 "Member must be a FieldDecl or IndirectFieldDecl");
1504
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001505 if (Member->isInvalidDecl())
1506 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001507
John McCalle22a04a2009-11-04 23:02:40 +00001508 // Diagnose value-uses of fields to initialize themselves, e.g.
1509 // foo(foo)
1510 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001511 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001512 for (unsigned i = 0; i < NumArgs; ++i) {
1513 SourceLocation L;
1514 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1515 // FIXME: Return true in the case when other fields are used before being
1516 // uninitialized. For example, let this field be the i'th field. When
1517 // initializing the i'th field, throw a warning if any of the >= i'th
1518 // fields are used, as they are not yet initialized.
1519 // Right now we are only handling the case where the i'th field uses
1520 // itself in its initializer.
1521 Diag(L, diag::warn_field_is_uninit);
1522 }
1523 }
1524
Eli Friedman8e1433b2009-07-29 19:44:27 +00001525 bool HasDependentArg = false;
1526 for (unsigned i = 0; i < NumArgs; i++)
1527 HasDependentArg |= Args[i]->isTypeDependent();
1528
Chandler Carruthd44c3102010-12-06 09:23:57 +00001529 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001530 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001531 // Can't check initialization for a member of dependent type or when
1532 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001533 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1534 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001535
1536 // Erase any temporaries within this evaluation context; we're not
1537 // going to track them in the AST, since we'll be rebuilding the
1538 // ASTs during template instantiation.
1539 ExprTemporaries.erase(
1540 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1541 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001542 } else {
1543 // Initialize the member.
1544 InitializedEntity MemberEntity =
1545 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1546 : InitializedEntity::InitializeMember(IndirectMember, 0);
1547 InitializationKind Kind =
1548 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001549
Chandler Carruthd44c3102010-12-06 09:23:57 +00001550 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1551
1552 ExprResult MemberInit =
1553 InitSeq.Perform(*this, MemberEntity, Kind,
1554 MultiExprArg(*this, Args, NumArgs), 0);
1555 if (MemberInit.isInvalid())
1556 return true;
1557
1558 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1559
1560 // C++0x [class.base.init]p7:
1561 // The initialization of each base and member constitutes a
1562 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001563 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001564 if (MemberInit.isInvalid())
1565 return true;
1566
1567 // If we are in a dependent context, template instantiation will
1568 // perform this type-checking again. Just save the arguments that we
1569 // received in a ParenListExpr.
1570 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1571 // of the information that we have about the member
1572 // initializer. However, deconstructing the ASTs is a dicey process,
1573 // and this approach is far more likely to get the corner cases right.
1574 if (CurContext->isDependentContext())
1575 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1576 RParenLoc);
1577 else
1578 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001579 }
1580
Chandler Carruthd44c3102010-12-06 09:23:57 +00001581 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001582 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001583 IdLoc, LParenLoc, Init,
1584 RParenLoc);
1585 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001586 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001587 IdLoc, LParenLoc, Init,
1588 RParenLoc);
1589 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001590}
1591
John McCallfaf5fb42010-08-26 23:41:50 +00001592MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001593Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1594 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001595 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001596 SourceLocation LParenLoc,
1597 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001598 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001599 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1600 if (!LangOpts.CPlusPlus0x)
1601 return Diag(Loc, diag::err_delegation_0x_only)
1602 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001603
Alexis Huntc5575cc2011-02-26 19:13:13 +00001604 // Initialize the object.
1605 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1606 QualType(ClassDecl->getTypeForDecl(), 0));
1607 InitializationKind Kind =
1608 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1609
1610 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1611
1612 ExprResult DelegationInit =
1613 InitSeq.Perform(*this, DelegationEntity, Kind,
1614 MultiExprArg(*this, Args, NumArgs), 0);
1615 if (DelegationInit.isInvalid())
1616 return true;
1617
1618 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001619 CXXConstructorDecl *Constructor
1620 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001621 assert(Constructor && "Delegating constructor with no target?");
1622
1623 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1624
1625 // C++0x [class.base.init]p7:
1626 // The initialization of each base and member constitutes a
1627 // full-expression.
1628 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1629 if (DelegationInit.isInvalid())
1630 return true;
1631
1632 // If we are in a dependent context, template instantiation will
1633 // perform this type-checking again. Just save the arguments that we
1634 // received in a ParenListExpr.
1635 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1636 // of the information that we have about the base
1637 // initializer. However, deconstructing the ASTs is a dicey process,
1638 // and this approach is far more likely to get the corner cases right.
1639 if (CurContext->isDependentContext()) {
1640 ExprResult Init
1641 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1642 NumArgs, RParenLoc));
1643 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1644 Constructor, Init.takeAs<Expr>(),
1645 RParenLoc);
1646 }
1647
1648 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1649 DelegationInit.takeAs<Expr>(),
1650 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001651}
1652
1653MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001654Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001655 Expr **Args, unsigned NumArgs,
1656 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001657 CXXRecordDecl *ClassDecl,
1658 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001659 bool HasDependentArg = false;
1660 for (unsigned i = 0; i < NumArgs; i++)
1661 HasDependentArg |= Args[i]->isTypeDependent();
1662
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001663 SourceLocation BaseLoc
1664 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1665
1666 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1667 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1668 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1669
1670 // C++ [class.base.init]p2:
1671 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001672 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001673 // of that class, the mem-initializer is ill-formed. A
1674 // mem-initializer-list can initialize a base class using any
1675 // name that denotes that base class type.
1676 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1677
Douglas Gregor44e7df62011-01-04 00:32:56 +00001678 if (EllipsisLoc.isValid()) {
1679 // This is a pack expansion.
1680 if (!BaseType->containsUnexpandedParameterPack()) {
1681 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1682 << SourceRange(BaseLoc, RParenLoc);
1683
1684 EllipsisLoc = SourceLocation();
1685 }
1686 } else {
1687 // Check for any unexpanded parameter packs.
1688 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1689 return true;
1690
1691 for (unsigned I = 0; I != NumArgs; ++I)
1692 if (DiagnoseUnexpandedParameterPack(Args[I]))
1693 return true;
1694 }
1695
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001696 // Check for direct and virtual base classes.
1697 const CXXBaseSpecifier *DirectBaseSpec = 0;
1698 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1699 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001700 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1701 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001702 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1703 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001704
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001705 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1706 VirtualBaseSpec);
1707
1708 // C++ [base.class.init]p2:
1709 // Unless the mem-initializer-id names a nonstatic data member of the
1710 // constructor's class or a direct or virtual base of that class, the
1711 // mem-initializer is ill-formed.
1712 if (!DirectBaseSpec && !VirtualBaseSpec) {
1713 // If the class has any dependent bases, then it's possible that
1714 // one of those types will resolve to the same type as
1715 // BaseType. Therefore, just treat this as a dependent base
1716 // class initialization. FIXME: Should we try to check the
1717 // initialization anyway? It seems odd.
1718 if (ClassDecl->hasAnyDependentBases())
1719 Dependent = true;
1720 else
1721 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1722 << BaseType << Context.getTypeDeclType(ClassDecl)
1723 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1724 }
1725 }
1726
1727 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001728 // Can't check initialization for a base of dependent type or when
1729 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001730 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001731 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1732 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001733
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001734 // Erase any temporaries within this evaluation context; we're not
1735 // going to track them in the AST, since we'll be rebuilding the
1736 // ASTs during template instantiation.
1737 ExprTemporaries.erase(
1738 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1739 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001740
Alexis Hunt1d792652011-01-08 20:30:50 +00001741 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001742 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001743 LParenLoc,
1744 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001745 RParenLoc,
1746 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001747 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001748
1749 // C++ [base.class.init]p2:
1750 // If a mem-initializer-id is ambiguous because it designates both
1751 // a direct non-virtual base class and an inherited virtual base
1752 // class, the mem-initializer is ill-formed.
1753 if (DirectBaseSpec && VirtualBaseSpec)
1754 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001755 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001756
1757 CXXBaseSpecifier *BaseSpec
1758 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1759 if (!BaseSpec)
1760 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1761
1762 // Initialize the base.
1763 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001764 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001765 InitializationKind Kind =
1766 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1767
1768 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1769
John McCalldadc5752010-08-24 06:29:42 +00001770 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001771 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001772 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001773 if (BaseInit.isInvalid())
1774 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001775
1776 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001777
1778 // C++0x [class.base.init]p7:
1779 // The initialization of each base and member constitutes a
1780 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001781 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001782 if (BaseInit.isInvalid())
1783 return true;
1784
1785 // If we are in a dependent context, template instantiation will
1786 // perform this type-checking again. Just save the arguments that we
1787 // received in a ParenListExpr.
1788 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1789 // of the information that we have about the base
1790 // initializer. However, deconstructing the ASTs is a dicey process,
1791 // and this approach is far more likely to get the corner cases right.
1792 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001793 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001794 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1795 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001796 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001797 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001798 LParenLoc,
1799 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001800 RParenLoc,
1801 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001802 }
1803
Alexis Hunt1d792652011-01-08 20:30:50 +00001804 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001805 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001806 LParenLoc,
1807 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001808 RParenLoc,
1809 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001810}
1811
Anders Carlsson1b00e242010-04-23 03:10:23 +00001812/// ImplicitInitializerKind - How an implicit base or member initializer should
1813/// initialize its base or member.
1814enum ImplicitInitializerKind {
1815 IIK_Default,
1816 IIK_Copy,
1817 IIK_Move
1818};
1819
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001820static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001821BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001822 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001823 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001824 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001825 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001826 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001827 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1828 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001829
John McCalldadc5752010-08-24 06:29:42 +00001830 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001831
1832 switch (ImplicitInitKind) {
1833 case IIK_Default: {
1834 InitializationKind InitKind
1835 = InitializationKind::CreateDefault(Constructor->getLocation());
1836 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1837 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001838 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001839 break;
1840 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001841
Anders Carlsson1b00e242010-04-23 03:10:23 +00001842 case IIK_Copy: {
1843 ParmVarDecl *Param = Constructor->getParamDecl(0);
1844 QualType ParamType = Param->getType().getNonReferenceType();
1845
1846 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001847 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001848 Constructor->getLocation(), ParamType,
1849 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001850
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001851 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001852 QualType ArgTy =
1853 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1854 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001855
1856 CXXCastPath BasePath;
1857 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001858 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1859 CK_UncheckedDerivedToBase,
1860 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001861
Anders Carlsson1b00e242010-04-23 03:10:23 +00001862 InitializationKind InitKind
1863 = InitializationKind::CreateDirect(Constructor->getLocation(),
1864 SourceLocation(), SourceLocation());
1865 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1866 &CopyCtorArg, 1);
1867 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001868 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001869 break;
1870 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001871
Anders Carlsson1b00e242010-04-23 03:10:23 +00001872 case IIK_Move:
1873 assert(false && "Unhandled initializer kind!");
1874 }
John McCallb268a282010-08-23 23:25:46 +00001875
Douglas Gregora40433a2010-12-07 00:41:46 +00001876 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001877 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001878 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001879
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001880 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001881 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001882 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1883 SourceLocation()),
1884 BaseSpec->isVirtual(),
1885 SourceLocation(),
1886 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001887 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001888 SourceLocation());
1889
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001890 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001891}
1892
Anders Carlsson3c1db572010-04-23 02:15:47 +00001893static bool
1894BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001895 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001896 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001897 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001898 if (Field->isInvalidDecl())
1899 return true;
1900
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001901 SourceLocation Loc = Constructor->getLocation();
1902
Anders Carlsson423f5d82010-04-23 16:04:08 +00001903 if (ImplicitInitKind == IIK_Copy) {
1904 ParmVarDecl *Param = Constructor->getParamDecl(0);
1905 QualType ParamType = Param->getType().getNonReferenceType();
1906
1907 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001908 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001909 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001910
1911 // Build a reference to this field within the parameter.
1912 CXXScopeSpec SS;
1913 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1914 Sema::LookupMemberName);
1915 MemberLookup.addDecl(Field, AS_public);
1916 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001917 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001918 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001919 ParamType, Loc,
1920 /*IsArrow=*/false,
1921 SS,
1922 /*FirstQualifierInScope=*/0,
1923 MemberLookup,
1924 /*TemplateArgs=*/0);
1925 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001926 return true;
1927
Douglas Gregor94f9a482010-05-05 05:51:00 +00001928 // When the field we are copying is an array, create index variables for
1929 // each dimension of the array. We use these index variables to subscript
1930 // the source array, and other clients (e.g., CodeGen) will perform the
1931 // necessary iteration with these index variables.
1932 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1933 QualType BaseType = Field->getType();
1934 QualType SizeType = SemaRef.Context.getSizeType();
1935 while (const ConstantArrayType *Array
1936 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1937 // Create the iteration variable for this array index.
1938 IdentifierInfo *IterationVarName = 0;
1939 {
1940 llvm::SmallString<8> Str;
1941 llvm::raw_svector_ostream OS(Str);
1942 OS << "__i" << IndexVariables.size();
1943 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1944 }
1945 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00001946 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001947 IterationVarName, SizeType,
1948 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001949 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001950 IndexVariables.push_back(IterationVar);
1951
1952 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001953 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001954 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001955 assert(!IterationVarRef.isInvalid() &&
1956 "Reference to invented variable cannot fail!");
1957
1958 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001959 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001960 Loc,
John McCallb268a282010-08-23 23:25:46 +00001961 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001962 Loc);
1963 if (CopyCtorArg.isInvalid())
1964 return true;
1965
1966 BaseType = Array->getElementType();
1967 }
1968
1969 // Construct the entity that we will be initializing. For an array, this
1970 // will be first element in the array, which may require several levels
1971 // of array-subscript entities.
1972 llvm::SmallVector<InitializedEntity, 4> Entities;
1973 Entities.reserve(1 + IndexVariables.size());
1974 Entities.push_back(InitializedEntity::InitializeMember(Field));
1975 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1976 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1977 0,
1978 Entities.back()));
1979
1980 // Direct-initialize to use the copy constructor.
1981 InitializationKind InitKind =
1982 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1983
1984 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1985 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1986 &CopyCtorArgE, 1);
1987
John McCalldadc5752010-08-24 06:29:42 +00001988 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001989 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001990 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001991 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001992 if (MemberInit.isInvalid())
1993 return true;
1994
1995 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001996 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001997 MemberInit.takeAs<Expr>(), Loc,
1998 IndexVariables.data(),
1999 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002000 return false;
2001 }
2002
Anders Carlsson423f5d82010-04-23 16:04:08 +00002003 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2004
Anders Carlsson3c1db572010-04-23 02:15:47 +00002005 QualType FieldBaseElementType =
2006 SemaRef.Context.getBaseElementType(Field->getType());
2007
Anders Carlsson3c1db572010-04-23 02:15:47 +00002008 if (FieldBaseElementType->isRecordType()) {
2009 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002010 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002011 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002012
2013 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002014 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002015 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002016
Douglas Gregora40433a2010-12-07 00:41:46 +00002017 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002018 if (MemberInit.isInvalid())
2019 return true;
2020
2021 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002022 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002023 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002024 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002025 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002026 return false;
2027 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002028
Alexis Hunt8b455182011-05-17 00:19:05 +00002029 if (!Field->getParent()->isUnion()) {
2030 if (FieldBaseElementType->isReferenceType()) {
2031 SemaRef.Diag(Constructor->getLocation(),
2032 diag::err_uninitialized_member_in_ctor)
2033 << (int)Constructor->isImplicit()
2034 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2035 << 0 << Field->getDeclName();
2036 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2037 return true;
2038 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002039
Alexis Hunt8b455182011-05-17 00:19:05 +00002040 if (FieldBaseElementType.isConstQualified()) {
2041 SemaRef.Diag(Constructor->getLocation(),
2042 diag::err_uninitialized_member_in_ctor)
2043 << (int)Constructor->isImplicit()
2044 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2045 << 1 << Field->getDeclName();
2046 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2047 return true;
2048 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002049 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002050
2051 // Nothing to initialize.
2052 CXXMemberInit = 0;
2053 return false;
2054}
John McCallbc83b3f2010-05-20 23:23:51 +00002055
2056namespace {
2057struct BaseAndFieldInfo {
2058 Sema &S;
2059 CXXConstructorDecl *Ctor;
2060 bool AnyErrorsInInits;
2061 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002062 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2063 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002064
2065 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2066 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2067 // FIXME: Handle implicit move constructors.
2068 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2069 IIK = IIK_Copy;
2070 else
2071 IIK = IIK_Default;
2072 }
2073};
2074}
2075
2076static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2077 FieldDecl *Top, FieldDecl *Field) {
2078
Chandler Carruth139e9622010-06-30 02:59:29 +00002079 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002080 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002081 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002082 return false;
2083 }
2084
2085 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2086 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2087 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002088 CXXRecordDecl *FieldClassDecl
2089 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002090
2091 // Even though union members never have non-trivial default
2092 // constructions in C++03, we still build member initializers for aggregate
2093 // record types which can be union members, and C++0x allows non-trivial
2094 // default constructors for union members, so we ensure that only one
2095 // member is initialized for these.
2096 if (FieldClassDecl->isUnion()) {
2097 // First check for an explicit initializer for one field.
2098 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2099 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002100 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002101 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002102
2103 // Once we've initialized a field of an anonymous union, the union
2104 // field in the class is also initialized, so exit immediately.
2105 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002106 } else if ((*FA)->isAnonymousStructOrUnion()) {
2107 if (CollectFieldInitializer(Info, Top, *FA))
2108 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002109 }
2110 }
2111
2112 // Fallthrough and construct a default initializer for the union as
2113 // a whole, which can call its default constructor if such a thing exists
2114 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2115 // behavior going forward with C++0x, when anonymous unions there are
2116 // finalized, we should revisit this.
2117 } else {
2118 // For structs, we simply descend through to initialize all members where
2119 // necessary.
2120 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2121 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2122 if (CollectFieldInitializer(Info, Top, *FA))
2123 return true;
2124 }
2125 }
John McCallbc83b3f2010-05-20 23:23:51 +00002126 }
2127
2128 // Don't try to build an implicit initializer if there were semantic
2129 // errors in any of the initializers (and therefore we might be
2130 // missing some that the user actually wrote).
2131 if (Info.AnyErrorsInInits)
2132 return false;
2133
Alexis Hunt1d792652011-01-08 20:30:50 +00002134 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002135 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2136 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002137
Francois Pichetd583da02010-12-04 09:14:42 +00002138 if (Init)
2139 Info.AllToInit.push_back(Init);
2140
John McCallbc83b3f2010-05-20 23:23:51 +00002141 return false;
2142}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002143
2144bool
2145Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2146 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002147 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002148 Constructor->setNumCtorInitializers(1);
2149 CXXCtorInitializer **initializer =
2150 new (Context) CXXCtorInitializer*[1];
2151 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2152 Constructor->setCtorInitializers(initializer);
2153
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002154 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2155 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2156 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2157 }
2158
Alexis Hunte2622992011-05-05 00:05:47 +00002159 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002160
Alexis Hunt61bc1732011-05-01 07:04:31 +00002161 return false;
2162}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002163
Eli Friedman9cf6b592009-11-09 19:20:36 +00002164bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002165Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2166 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002167 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002168 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002169 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002170 // Just store the initializers as written, they will be checked during
2171 // instantiation.
2172 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002173 Constructor->setNumCtorInitializers(NumInitializers);
2174 CXXCtorInitializer **baseOrMemberInitializers =
2175 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002176 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002177 NumInitializers * sizeof(CXXCtorInitializer*));
2178 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002179 }
2180
2181 return false;
2182 }
2183
John McCallbc83b3f2010-05-20 23:23:51 +00002184 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002185
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002186 // We need to build the initializer AST according to order of construction
2187 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002188 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002189 if (!ClassDecl)
2190 return true;
2191
Eli Friedman9cf6b592009-11-09 19:20:36 +00002192 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002193
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002194 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002195 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002196
2197 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002198 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002199 else
Francois Pichetd583da02010-12-04 09:14:42 +00002200 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002201 }
2202
Anders Carlsson43c64af2010-04-21 19:52:01 +00002203 // Keep track of the direct virtual bases.
2204 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2205 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2206 E = ClassDecl->bases_end(); I != E; ++I) {
2207 if (I->isVirtual())
2208 DirectVBases.insert(I);
2209 }
2210
Anders Carlssondb0a9652010-04-02 06:26:44 +00002211 // Push virtual bases before others.
2212 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2213 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2214
Alexis Hunt1d792652011-01-08 20:30:50 +00002215 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002216 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2217 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002218 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002219 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002220 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002221 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002222 VBase, IsInheritedVirtualBase,
2223 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002224 HadError = true;
2225 continue;
2226 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002227
John McCallbc83b3f2010-05-20 23:23:51 +00002228 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002229 }
2230 }
Mike Stump11289f42009-09-09 15:08:12 +00002231
John McCallbc83b3f2010-05-20 23:23:51 +00002232 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002233 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2234 E = ClassDecl->bases_end(); Base != E; ++Base) {
2235 // Virtuals are in the virtual base list and already constructed.
2236 if (Base->isVirtual())
2237 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002238
Alexis Hunt1d792652011-01-08 20:30:50 +00002239 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002240 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2241 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002242 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002243 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002244 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002245 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002246 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002247 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002248 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002249 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002250
John McCallbc83b3f2010-05-20 23:23:51 +00002251 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002252 }
2253 }
Mike Stump11289f42009-09-09 15:08:12 +00002254
John McCallbc83b3f2010-05-20 23:23:51 +00002255 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002256 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002257 E = ClassDecl->field_end(); Field != E; ++Field) {
2258 if ((*Field)->getType()->isIncompleteArrayType()) {
2259 assert(ClassDecl->hasFlexibleArrayMember() &&
2260 "Incomplete array type is not valid");
2261 continue;
2262 }
John McCallbc83b3f2010-05-20 23:23:51 +00002263 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002264 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002265 }
Mike Stump11289f42009-09-09 15:08:12 +00002266
John McCallbc83b3f2010-05-20 23:23:51 +00002267 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002268 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002269 Constructor->setNumCtorInitializers(NumInitializers);
2270 CXXCtorInitializer **baseOrMemberInitializers =
2271 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002272 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002273 NumInitializers * sizeof(CXXCtorInitializer*));
2274 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002275
John McCalla6309952010-03-16 21:39:52 +00002276 // Constructors implicitly reference the base and member
2277 // destructors.
2278 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2279 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002280 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002281
2282 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002283}
2284
Eli Friedman952c15d2009-07-21 19:28:10 +00002285static void *GetKeyForTopLevelField(FieldDecl *Field) {
2286 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002287 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002288 if (RT->getDecl()->isAnonymousStructOrUnion())
2289 return static_cast<void *>(RT->getDecl());
2290 }
2291 return static_cast<void *>(Field);
2292}
2293
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002294static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002295 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002296}
2297
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002298static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002299 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002300 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002301 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002302
Eli Friedman952c15d2009-07-21 19:28:10 +00002303 // For fields injected into the class via declaration of an anonymous union,
2304 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002305 FieldDecl *Field = Member->getAnyMember();
2306
John McCall23eebd92010-04-10 09:28:51 +00002307 // If the field is a member of an anonymous struct or union, our key
2308 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002309 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002310 if (RD->isAnonymousStructOrUnion()) {
2311 while (true) {
2312 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2313 if (Parent->isAnonymousStructOrUnion())
2314 RD = Parent;
2315 else
2316 break;
2317 }
2318
Anders Carlsson83ac3122010-03-30 16:19:37 +00002319 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002320 }
Mike Stump11289f42009-09-09 15:08:12 +00002321
Anders Carlssona942dcd2010-03-30 15:39:27 +00002322 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002323}
2324
Anders Carlssone857b292010-04-02 03:37:03 +00002325static void
2326DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002327 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002328 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002329 unsigned NumInits) {
2330 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002331 return;
Mike Stump11289f42009-09-09 15:08:12 +00002332
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002333 // Don't check initializers order unless the warning is enabled at the
2334 // location of at least one initializer.
2335 bool ShouldCheckOrder = false;
2336 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002337 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002338 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2339 Init->getSourceLocation())
2340 != Diagnostic::Ignored) {
2341 ShouldCheckOrder = true;
2342 break;
2343 }
2344 }
2345 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002346 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002347
John McCallbb7b6582010-04-10 07:37:23 +00002348 // Build the list of bases and members in the order that they'll
2349 // actually be initialized. The explicit initializers should be in
2350 // this same order but may be missing things.
2351 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002352
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002353 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2354
John McCallbb7b6582010-04-10 07:37:23 +00002355 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002356 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002357 ClassDecl->vbases_begin(),
2358 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002359 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002360
John McCallbb7b6582010-04-10 07:37:23 +00002361 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002362 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002363 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002364 if (Base->isVirtual())
2365 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002366 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002367 }
Mike Stump11289f42009-09-09 15:08:12 +00002368
John McCallbb7b6582010-04-10 07:37:23 +00002369 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002370 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2371 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002372 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002373
John McCallbb7b6582010-04-10 07:37:23 +00002374 unsigned NumIdealInits = IdealInitKeys.size();
2375 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002376
Alexis Hunt1d792652011-01-08 20:30:50 +00002377 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002378 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002379 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002380 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002381
2382 // Scan forward to try to find this initializer in the idealized
2383 // initializers list.
2384 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2385 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002386 break;
John McCallbb7b6582010-04-10 07:37:23 +00002387
2388 // If we didn't find this initializer, it must be because we
2389 // scanned past it on a previous iteration. That can only
2390 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002391 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002392 Sema::SemaDiagnosticBuilder D =
2393 SemaRef.Diag(PrevInit->getSourceLocation(),
2394 diag::warn_initializer_out_of_order);
2395
Francois Pichetd583da02010-12-04 09:14:42 +00002396 if (PrevInit->isAnyMemberInitializer())
2397 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002398 else
2399 D << 1 << PrevInit->getBaseClassInfo()->getType();
2400
Francois Pichetd583da02010-12-04 09:14:42 +00002401 if (Init->isAnyMemberInitializer())
2402 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002403 else
2404 D << 1 << Init->getBaseClassInfo()->getType();
2405
2406 // Move back to the initializer's location in the ideal list.
2407 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2408 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002409 break;
John McCallbb7b6582010-04-10 07:37:23 +00002410
2411 assert(IdealIndex != NumIdealInits &&
2412 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002413 }
John McCallbb7b6582010-04-10 07:37:23 +00002414
2415 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002416 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002417}
2418
John McCall23eebd92010-04-10 09:28:51 +00002419namespace {
2420bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002421 CXXCtorInitializer *Init,
2422 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002423 if (!PrevInit) {
2424 PrevInit = Init;
2425 return false;
2426 }
2427
2428 if (FieldDecl *Field = Init->getMember())
2429 S.Diag(Init->getSourceLocation(),
2430 diag::err_multiple_mem_initialization)
2431 << Field->getDeclName()
2432 << Init->getSourceRange();
2433 else {
John McCall424cec92011-01-19 06:33:43 +00002434 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002435 assert(BaseClass && "neither field nor base");
2436 S.Diag(Init->getSourceLocation(),
2437 diag::err_multiple_base_initialization)
2438 << QualType(BaseClass, 0)
2439 << Init->getSourceRange();
2440 }
2441 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2442 << 0 << PrevInit->getSourceRange();
2443
2444 return true;
2445}
2446
Alexis Hunt1d792652011-01-08 20:30:50 +00002447typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002448typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2449
2450bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002451 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002452 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002453 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002454 RecordDecl *Parent = Field->getParent();
2455 if (!Parent->isAnonymousStructOrUnion())
2456 return false;
2457
2458 NamedDecl *Child = Field;
2459 do {
2460 if (Parent->isUnion()) {
2461 UnionEntry &En = Unions[Parent];
2462 if (En.first && En.first != Child) {
2463 S.Diag(Init->getSourceLocation(),
2464 diag::err_multiple_mem_union_initialization)
2465 << Field->getDeclName()
2466 << Init->getSourceRange();
2467 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2468 << 0 << En.second->getSourceRange();
2469 return true;
2470 } else if (!En.first) {
2471 En.first = Child;
2472 En.second = Init;
2473 }
2474 }
2475
2476 Child = Parent;
2477 Parent = cast<RecordDecl>(Parent->getDeclContext());
2478 } while (Parent->isAnonymousStructOrUnion());
2479
2480 return false;
2481}
2482}
2483
Anders Carlssone857b292010-04-02 03:37:03 +00002484/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002485void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002486 SourceLocation ColonLoc,
2487 MemInitTy **meminits, unsigned NumMemInits,
2488 bool AnyErrors) {
2489 if (!ConstructorDecl)
2490 return;
2491
2492 AdjustDeclIfTemplate(ConstructorDecl);
2493
2494 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002495 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002496
2497 if (!Constructor) {
2498 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2499 return;
2500 }
2501
Alexis Hunt1d792652011-01-08 20:30:50 +00002502 CXXCtorInitializer **MemInits =
2503 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002504
2505 // Mapping for the duplicate initializers check.
2506 // For member initializers, this is keyed with a FieldDecl*.
2507 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002508 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002509
2510 // Mapping for the inconsistent anonymous-union initializers check.
2511 RedundantUnionMap MemberUnions;
2512
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002513 bool HadError = false;
2514 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002515 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002516
Abramo Bagnara341d7832010-05-26 18:09:23 +00002517 // Set the source order index.
2518 Init->setSourceOrder(i);
2519
Francois Pichetd583da02010-12-04 09:14:42 +00002520 if (Init->isAnyMemberInitializer()) {
2521 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002522 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2523 CheckRedundantUnionInit(*this, Init, MemberUnions))
2524 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002525 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002526 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2527 if (CheckRedundantInit(*this, Init, Members[Key]))
2528 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002529 } else {
2530 assert(Init->isDelegatingInitializer());
2531 // This must be the only initializer
2532 if (i != 0 || NumMemInits > 1) {
2533 Diag(MemInits[0]->getSourceLocation(),
2534 diag::err_delegating_initializer_alone)
2535 << MemInits[0]->getSourceRange();
2536 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002537 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002538 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002539 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002540 // Return immediately as the initializer is set.
2541 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002542 }
Anders Carlssone857b292010-04-02 03:37:03 +00002543 }
2544
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002545 if (HadError)
2546 return;
2547
Anders Carlssone857b292010-04-02 03:37:03 +00002548 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002549
Alexis Hunt1d792652011-01-08 20:30:50 +00002550 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002551}
2552
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002553void
John McCalla6309952010-03-16 21:39:52 +00002554Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2555 CXXRecordDecl *ClassDecl) {
2556 // Ignore dependent contexts.
2557 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002558 return;
John McCall1064d7e2010-03-16 05:22:47 +00002559
2560 // FIXME: all the access-control diagnostics are positioned on the
2561 // field/base declaration. That's probably good; that said, the
2562 // user might reasonably want to know why the destructor is being
2563 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002564
Anders Carlssondee9a302009-11-17 04:44:12 +00002565 // Non-static data members.
2566 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2567 E = ClassDecl->field_end(); I != E; ++I) {
2568 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002569 if (Field->isInvalidDecl())
2570 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002571 QualType FieldType = Context.getBaseElementType(Field->getType());
2572
2573 const RecordType* RT = FieldType->getAs<RecordType>();
2574 if (!RT)
2575 continue;
2576
2577 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002578 if (FieldClassDecl->isInvalidDecl())
2579 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002580 if (FieldClassDecl->hasTrivialDestructor())
2581 continue;
2582
Douglas Gregore71edda2010-07-01 22:47:18 +00002583 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002584 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002585 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002586 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002587 << Field->getDeclName()
2588 << FieldType);
2589
John McCalla6309952010-03-16 21:39:52 +00002590 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002591 }
2592
John McCall1064d7e2010-03-16 05:22:47 +00002593 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2594
Anders Carlssondee9a302009-11-17 04:44:12 +00002595 // Bases.
2596 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2597 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002598 // Bases are always records in a well-formed non-dependent class.
2599 const RecordType *RT = Base->getType()->getAs<RecordType>();
2600
2601 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002602 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002603 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002604
John McCall1064d7e2010-03-16 05:22:47 +00002605 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002606 // If our base class is invalid, we probably can't get its dtor anyway.
2607 if (BaseClassDecl->isInvalidDecl())
2608 continue;
2609 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002610 if (BaseClassDecl->hasTrivialDestructor())
2611 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002612
Douglas Gregore71edda2010-07-01 22:47:18 +00002613 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002614 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002615
2616 // FIXME: caret should be on the start of the class name
2617 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002618 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002619 << Base->getType()
2620 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002621
John McCalla6309952010-03-16 21:39:52 +00002622 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002623 }
2624
2625 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002626 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2627 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002628
2629 // Bases are always records in a well-formed non-dependent class.
2630 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2631
2632 // Ignore direct virtual bases.
2633 if (DirectVirtualBases.count(RT))
2634 continue;
2635
John McCall1064d7e2010-03-16 05:22:47 +00002636 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002637 // If our base class is invalid, we probably can't get its dtor anyway.
2638 if (BaseClassDecl->isInvalidDecl())
2639 continue;
2640 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002641 if (BaseClassDecl->hasTrivialDestructor())
2642 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002643
Douglas Gregore71edda2010-07-01 22:47:18 +00002644 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002645 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002646 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002647 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002648 << VBase->getType());
2649
John McCalla6309952010-03-16 21:39:52 +00002650 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002651 }
2652}
2653
John McCall48871652010-08-21 09:40:31 +00002654void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002655 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002656 return;
Mike Stump11289f42009-09-09 15:08:12 +00002657
Mike Stump11289f42009-09-09 15:08:12 +00002658 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002659 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002660 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002661}
2662
Mike Stump11289f42009-09-09 15:08:12 +00002663bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002664 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002665 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002666 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002667 else
John McCall02db245d2010-08-18 09:41:07 +00002668 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002669}
2670
Anders Carlssoneabf7702009-08-27 00:13:57 +00002671bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002672 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002673 if (!getLangOptions().CPlusPlus)
2674 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002675
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002676 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002677 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002678
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002679 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002680 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002681 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002682 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002683
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002684 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002685 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002686 }
Mike Stump11289f42009-09-09 15:08:12 +00002687
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002688 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002689 if (!RT)
2690 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002691
John McCall67da35c2010-02-04 22:26:26 +00002692 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002693
John McCall02db245d2010-08-18 09:41:07 +00002694 // We can't answer whether something is abstract until it has a
2695 // definition. If it's currently being defined, we'll walk back
2696 // over all the declarations when we have a full definition.
2697 const CXXRecordDecl *Def = RD->getDefinition();
2698 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002699 return false;
2700
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002701 if (!RD->isAbstract())
2702 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002703
Anders Carlssoneabf7702009-08-27 00:13:57 +00002704 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002705 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002706
John McCall02db245d2010-08-18 09:41:07 +00002707 return true;
2708}
2709
2710void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2711 // Check if we've already emitted the list of pure virtual functions
2712 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002713 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002714 return;
Mike Stump11289f42009-09-09 15:08:12 +00002715
Douglas Gregor4165bd62010-03-23 23:47:56 +00002716 CXXFinalOverriderMap FinalOverriders;
2717 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002718
Anders Carlssona2f74f32010-06-03 01:00:02 +00002719 // Keep a set of seen pure methods so we won't diagnose the same method
2720 // more than once.
2721 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2722
Douglas Gregor4165bd62010-03-23 23:47:56 +00002723 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2724 MEnd = FinalOverriders.end();
2725 M != MEnd;
2726 ++M) {
2727 for (OverridingMethods::iterator SO = M->second.begin(),
2728 SOEnd = M->second.end();
2729 SO != SOEnd; ++SO) {
2730 // C++ [class.abstract]p4:
2731 // A class is abstract if it contains or inherits at least one
2732 // pure virtual function for which the final overrider is pure
2733 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002734
Douglas Gregor4165bd62010-03-23 23:47:56 +00002735 //
2736 if (SO->second.size() != 1)
2737 continue;
2738
2739 if (!SO->second.front().Method->isPure())
2740 continue;
2741
Anders Carlssona2f74f32010-06-03 01:00:02 +00002742 if (!SeenPureMethods.insert(SO->second.front().Method))
2743 continue;
2744
Douglas Gregor4165bd62010-03-23 23:47:56 +00002745 Diag(SO->second.front().Method->getLocation(),
2746 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002747 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002748 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002749 }
2750
2751 if (!PureVirtualClassDiagSet)
2752 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2753 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002754}
2755
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002756namespace {
John McCall02db245d2010-08-18 09:41:07 +00002757struct AbstractUsageInfo {
2758 Sema &S;
2759 CXXRecordDecl *Record;
2760 CanQualType AbstractType;
2761 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002762
John McCall02db245d2010-08-18 09:41:07 +00002763 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2764 : S(S), Record(Record),
2765 AbstractType(S.Context.getCanonicalType(
2766 S.Context.getTypeDeclType(Record))),
2767 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002768
John McCall02db245d2010-08-18 09:41:07 +00002769 void DiagnoseAbstractType() {
2770 if (Invalid) return;
2771 S.DiagnoseAbstractType(Record);
2772 Invalid = true;
2773 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002774
John McCall02db245d2010-08-18 09:41:07 +00002775 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2776};
2777
2778struct CheckAbstractUsage {
2779 AbstractUsageInfo &Info;
2780 const NamedDecl *Ctx;
2781
2782 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2783 : Info(Info), Ctx(Ctx) {}
2784
2785 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2786 switch (TL.getTypeLocClass()) {
2787#define ABSTRACT_TYPELOC(CLASS, PARENT)
2788#define TYPELOC(CLASS, PARENT) \
2789 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2790#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002791 }
John McCall02db245d2010-08-18 09:41:07 +00002792 }
Mike Stump11289f42009-09-09 15:08:12 +00002793
John McCall02db245d2010-08-18 09:41:07 +00002794 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2795 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2796 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002797 if (!TL.getArg(I))
2798 continue;
2799
John McCall02db245d2010-08-18 09:41:07 +00002800 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2801 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002802 }
John McCall02db245d2010-08-18 09:41:07 +00002803 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002804
John McCall02db245d2010-08-18 09:41:07 +00002805 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2806 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2807 }
Mike Stump11289f42009-09-09 15:08:12 +00002808
John McCall02db245d2010-08-18 09:41:07 +00002809 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2810 // Visit the type parameters from a permissive context.
2811 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2812 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2813 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2814 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2815 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2816 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002817 }
John McCall02db245d2010-08-18 09:41:07 +00002818 }
Mike Stump11289f42009-09-09 15:08:12 +00002819
John McCall02db245d2010-08-18 09:41:07 +00002820 // Visit pointee types from a permissive context.
2821#define CheckPolymorphic(Type) \
2822 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2823 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2824 }
2825 CheckPolymorphic(PointerTypeLoc)
2826 CheckPolymorphic(ReferenceTypeLoc)
2827 CheckPolymorphic(MemberPointerTypeLoc)
2828 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002829
John McCall02db245d2010-08-18 09:41:07 +00002830 /// Handle all the types we haven't given a more specific
2831 /// implementation for above.
2832 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2833 // Every other kind of type that we haven't called out already
2834 // that has an inner type is either (1) sugar or (2) contains that
2835 // inner type in some way as a subobject.
2836 if (TypeLoc Next = TL.getNextTypeLoc())
2837 return Visit(Next, Sel);
2838
2839 // If there's no inner type and we're in a permissive context,
2840 // don't diagnose.
2841 if (Sel == Sema::AbstractNone) return;
2842
2843 // Check whether the type matches the abstract type.
2844 QualType T = TL.getType();
2845 if (T->isArrayType()) {
2846 Sel = Sema::AbstractArrayType;
2847 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002848 }
John McCall02db245d2010-08-18 09:41:07 +00002849 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2850 if (CT != Info.AbstractType) return;
2851
2852 // It matched; do some magic.
2853 if (Sel == Sema::AbstractArrayType) {
2854 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2855 << T << TL.getSourceRange();
2856 } else {
2857 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2858 << Sel << T << TL.getSourceRange();
2859 }
2860 Info.DiagnoseAbstractType();
2861 }
2862};
2863
2864void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2865 Sema::AbstractDiagSelID Sel) {
2866 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2867}
2868
2869}
2870
2871/// Check for invalid uses of an abstract type in a method declaration.
2872static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2873 CXXMethodDecl *MD) {
2874 // No need to do the check on definitions, which require that
2875 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002876 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00002877 return;
2878
2879 // For safety's sake, just ignore it if we don't have type source
2880 // information. This should never happen for non-implicit methods,
2881 // but...
2882 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2883 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2884}
2885
2886/// Check for invalid uses of an abstract type within a class definition.
2887static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2888 CXXRecordDecl *RD) {
2889 for (CXXRecordDecl::decl_iterator
2890 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2891 Decl *D = *I;
2892 if (D->isImplicit()) continue;
2893
2894 // Methods and method templates.
2895 if (isa<CXXMethodDecl>(D)) {
2896 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2897 } else if (isa<FunctionTemplateDecl>(D)) {
2898 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2899 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2900
2901 // Fields and static variables.
2902 } else if (isa<FieldDecl>(D)) {
2903 FieldDecl *FD = cast<FieldDecl>(D);
2904 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2905 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2906 } else if (isa<VarDecl>(D)) {
2907 VarDecl *VD = cast<VarDecl>(D);
2908 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2909 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2910
2911 // Nested classes and class templates.
2912 } else if (isa<CXXRecordDecl>(D)) {
2913 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2914 } else if (isa<ClassTemplateDecl>(D)) {
2915 CheckAbstractClassUsage(Info,
2916 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2917 }
2918 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002919}
2920
Douglas Gregorc99f1552009-12-03 18:33:45 +00002921/// \brief Perform semantic checks on a class definition that has been
2922/// completing, introducing implicitly-declared members, checking for
2923/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002924void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002925 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002926 return;
2927
John McCall02db245d2010-08-18 09:41:07 +00002928 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2929 AbstractUsageInfo Info(*this, Record);
2930 CheckAbstractClassUsage(Info, Record);
2931 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002932
2933 // If this is not an aggregate type and has no user-declared constructor,
2934 // complain about any non-static data members of reference or const scalar
2935 // type, since they will never get initializers.
2936 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2937 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2938 bool Complained = false;
2939 for (RecordDecl::field_iterator F = Record->field_begin(),
2940 FEnd = Record->field_end();
2941 F != FEnd; ++F) {
2942 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002943 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002944 if (!Complained) {
2945 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2946 << Record->getTagKind() << Record;
2947 Complained = true;
2948 }
2949
2950 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2951 << F->getType()->isReferenceType()
2952 << F->getDeclName();
2953 }
2954 }
2955 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002956
Anders Carlssone771e762011-01-25 18:08:22 +00002957 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002958 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002959
2960 if (Record->getIdentifier()) {
2961 // C++ [class.mem]p13:
2962 // If T is the name of a class, then each of the following shall have a
2963 // name different from T:
2964 // - every member of every anonymous union that is a member of class T.
2965 //
2966 // C++ [class.mem]p14:
2967 // In addition, if class T has a user-declared constructor (12.1), every
2968 // non-static data member of class T shall have a name different from T.
2969 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002970 R.first != R.second; ++R.first) {
2971 NamedDecl *D = *R.first;
2972 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2973 isa<IndirectFieldDecl>(D)) {
2974 Diag(D->getLocation(), diag::err_member_name_of_class)
2975 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002976 break;
2977 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002978 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002979 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002980
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002981 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002982 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002983 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002984 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002985 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2986 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2987 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002988
2989 // See if a method overloads virtual methods in a base
2990 /// class without overriding any.
2991 if (!Record->isDependentType()) {
2992 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2993 MEnd = Record->method_end();
2994 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00002995 if (!(*M)->isStatic())
2996 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002997 }
2998 }
Sebastian Redl08905022011-02-05 19:23:19 +00002999
3000 // Declare inherited constructors. We do this eagerly here because:
3001 // - The standard requires an eager diagnostic for conflicting inherited
3002 // constructors from different classes.
3003 // - The lazy declaration of the other implicit constructors is so as to not
3004 // waste space and performance on classes that are not meant to be
3005 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3006 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003007 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003008
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003009 if (!Record->isDependentType())
3010 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003011}
3012
3013void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003014 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3015 ME = Record->method_end();
3016 MI != ME; ++MI) {
3017 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3018 switch (getSpecialMember(*MI)) {
3019 case CXXDefaultConstructor:
3020 CheckExplicitlyDefaultedDefaultConstructor(
3021 cast<CXXConstructorDecl>(*MI));
3022 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003023
Alexis Huntf91729462011-05-12 22:46:25 +00003024 case CXXDestructor:
3025 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3026 break;
3027
3028 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003029 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3030 break;
3031
Alexis Huntf91729462011-05-12 22:46:25 +00003032 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003033 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003034 break;
3035
Alexis Hunt119c10e2011-05-25 23:16:36 +00003036 case CXXMoveConstructor:
3037 case CXXMoveAssignment:
3038 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3039 break;
3040
Alexis Huntf91729462011-05-12 22:46:25 +00003041 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00003042 // FIXME: Do moves once they exist
Alexis Huntf91729462011-05-12 22:46:25 +00003043 llvm_unreachable("non-special member explicitly defaulted!");
3044 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003045 }
3046 }
3047
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003048}
3049
3050void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3051 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3052
3053 // Whether this was the first-declared instance of the constructor.
3054 // This affects whether we implicitly add an exception spec (and, eventually,
3055 // constexpr). It is also ill-formed to explicitly default a constructor such
3056 // that it would be deleted. (C++0x [decl.fct.def.default])
3057 bool First = CD == CD->getCanonicalDecl();
3058
Alexis Hunt913820d2011-05-13 06:10:58 +00003059 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003060 if (CD->getNumParams() != 0) {
3061 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3062 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003063 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003064 }
3065
3066 ImplicitExceptionSpecification Spec
3067 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3068 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3069 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3070 *ExceptionType = Context.getFunctionType(
3071 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3072
3073 if (CtorType->hasExceptionSpec()) {
3074 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003075 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003076 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003077 PDiag(),
3078 ExceptionType, SourceLocation(),
3079 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003080 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003081 }
3082 } else if (First) {
3083 // We set the declaration to have the computed exception spec here.
3084 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003085 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003086 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3087 }
Alexis Huntb3153022011-05-12 03:51:48 +00003088
Alexis Hunt913820d2011-05-13 06:10:58 +00003089 if (HadError) {
3090 CD->setInvalidDecl();
3091 return;
3092 }
3093
Alexis Huntb3153022011-05-12 03:51:48 +00003094 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003095 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003096 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003097 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003098 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003099 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003100 CD->setInvalidDecl();
3101 }
3102 }
3103}
3104
3105void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3106 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3107
3108 // Whether this was the first-declared instance of the constructor.
3109 bool First = CD == CD->getCanonicalDecl();
3110
3111 bool HadError = false;
3112 if (CD->getNumParams() != 1) {
3113 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3114 << CD->getSourceRange();
3115 HadError = true;
3116 }
3117
3118 ImplicitExceptionSpecification Spec(Context);
3119 bool Const;
3120 llvm::tie(Spec, Const) =
3121 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3122
3123 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3124 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3125 *ExceptionType = Context.getFunctionType(
3126 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3127
3128 // Check for parameter type matching.
3129 // This is a copy ctor so we know it's a cv-qualified reference to T.
3130 QualType ArgType = CtorType->getArgType(0);
3131 if (ArgType->getPointeeType().isVolatileQualified()) {
3132 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3133 HadError = true;
3134 }
3135 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3136 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3137 HadError = true;
3138 }
3139
3140 if (CtorType->hasExceptionSpec()) {
3141 if (CheckEquivalentExceptionSpec(
3142 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003143 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003144 PDiag(),
3145 ExceptionType, SourceLocation(),
3146 CtorType, CD->getLocation())) {
3147 HadError = true;
3148 }
3149 } else if (First) {
3150 // We set the declaration to have the computed exception spec here.
3151 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003152 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003153 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3154 }
3155
3156 if (HadError) {
3157 CD->setInvalidDecl();
3158 return;
3159 }
3160
3161 if (ShouldDeleteCopyConstructor(CD)) {
3162 if (First) {
3163 CD->setDeletedAsWritten();
3164 } else {
3165 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003166 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003167 CD->setInvalidDecl();
3168 }
Alexis Huntb3153022011-05-12 03:51:48 +00003169 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003170}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003171
Alexis Huntc9a55732011-05-14 05:23:28 +00003172void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3173 assert(MD->isExplicitlyDefaulted());
3174
3175 // Whether this was the first-declared instance of the operator
3176 bool First = MD == MD->getCanonicalDecl();
3177
3178 bool HadError = false;
3179 if (MD->getNumParams() != 1) {
3180 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3181 << MD->getSourceRange();
3182 HadError = true;
3183 }
3184
3185 QualType ReturnType =
3186 MD->getType()->getAs<FunctionType>()->getResultType();
3187 if (!ReturnType->isLValueReferenceType() ||
3188 !Context.hasSameType(
3189 Context.getCanonicalType(ReturnType->getPointeeType()),
3190 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3191 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3192 HadError = true;
3193 }
3194
3195 ImplicitExceptionSpecification Spec(Context);
3196 bool Const;
3197 llvm::tie(Spec, Const) =
3198 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3199
3200 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3201 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3202 *ExceptionType = Context.getFunctionType(
3203 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3204
Alexis Huntc9a55732011-05-14 05:23:28 +00003205 QualType ArgType = OperType->getArgType(0);
Alexis Hunt604aeb32011-05-17 20:44:43 +00003206 if (!ArgType->isReferenceType()) {
3207 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003208 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003209 } else {
3210 if (ArgType->getPointeeType().isVolatileQualified()) {
3211 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3212 HadError = true;
3213 }
3214 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3215 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3216 HadError = true;
3217 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003218 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003219
Alexis Huntc9a55732011-05-14 05:23:28 +00003220 if (OperType->getTypeQuals()) {
3221 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3222 HadError = true;
3223 }
3224
3225 if (OperType->hasExceptionSpec()) {
3226 if (CheckEquivalentExceptionSpec(
3227 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003228 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003229 PDiag(),
3230 ExceptionType, SourceLocation(),
3231 OperType, MD->getLocation())) {
3232 HadError = true;
3233 }
3234 } else if (First) {
3235 // We set the declaration to have the computed exception spec here.
3236 // We duplicate the one parameter type.
3237 EPI.RefQualifier = OperType->getRefQualifier();
3238 EPI.ExtInfo = OperType->getExtInfo();
3239 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3240 }
3241
3242 if (HadError) {
3243 MD->setInvalidDecl();
3244 return;
3245 }
3246
3247 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3248 if (First) {
3249 MD->setDeletedAsWritten();
3250 } else {
3251 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003252 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003253 MD->setInvalidDecl();
3254 }
3255 }
3256}
3257
Alexis Huntf91729462011-05-12 22:46:25 +00003258void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3259 assert(DD->isExplicitlyDefaulted());
3260
3261 // Whether this was the first-declared instance of the destructor.
3262 bool First = DD == DD->getCanonicalDecl();
3263
3264 ImplicitExceptionSpecification Spec
3265 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3266 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3267 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3268 *ExceptionType = Context.getFunctionType(
3269 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3270
3271 if (DtorType->hasExceptionSpec()) {
3272 if (CheckEquivalentExceptionSpec(
3273 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003274 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00003275 PDiag(),
3276 ExceptionType, SourceLocation(),
3277 DtorType, DD->getLocation())) {
3278 DD->setInvalidDecl();
3279 return;
3280 }
3281 } else if (First) {
3282 // We set the declaration to have the computed exception spec here.
3283 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003284 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003285 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3286 }
3287
3288 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003289 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003290 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003291 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003292 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003293 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003294 DD->setInvalidDecl();
3295 }
Alexis Huntf91729462011-05-12 22:46:25 +00003296 }
Alexis Huntf91729462011-05-12 22:46:25 +00003297}
3298
Alexis Huntea6f0322011-05-11 22:34:38 +00003299bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3300 CXXRecordDecl *RD = CD->getParent();
3301 assert(!RD->isDependentType() && "do deletion after instantiation");
3302 if (!LangOpts.CPlusPlus0x)
3303 return false;
3304
Alexis Hunte77a28f2011-05-18 03:41:58 +00003305 SourceLocation Loc = CD->getLocation();
3306
Alexis Huntea6f0322011-05-11 22:34:38 +00003307 // Do access control from the constructor
3308 ContextRAII CtorContext(*this, CD);
3309
3310 bool Union = RD->isUnion();
3311 bool AllConst = true;
3312
Alexis Huntea6f0322011-05-11 22:34:38 +00003313 // We do this because we should never actually use an anonymous
3314 // union's constructor.
3315 if (Union && RD->isAnonymousStructOrUnion())
3316 return false;
3317
3318 // FIXME: We should put some diagnostic logic right into this function.
3319
3320 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00003321 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00003322
3323 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3324 BE = RD->bases_end();
3325 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003326 // We'll handle this one later
3327 if (BI->isVirtual())
3328 continue;
3329
Alexis Huntea6f0322011-05-11 22:34:38 +00003330 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3331 assert(BaseDecl && "base isn't a CXXRecordDecl");
3332
3333 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00003334 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00003335 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3336 if (BaseDtor->isDeleted())
3337 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003338 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003339 AR_accessible)
3340 return true;
3341
Alexis Huntea6f0322011-05-11 22:34:38 +00003342 // -- any [direct base class either] has no default constructor or
3343 // overload resolution as applied to [its] default constructor
3344 // results in an ambiguity or in a function that is deleted or
3345 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003346 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3347 if (!BaseDefault || BaseDefault->isDeleted())
3348 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003349
Alexis Hunteef8ee02011-06-10 03:50:41 +00003350 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3351 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003352 return true;
3353 }
3354
3355 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3356 BE = RD->vbases_end();
3357 BI != BE; ++BI) {
3358 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3359 assert(BaseDecl && "base isn't a CXXRecordDecl");
3360
3361 // -- any [virtual base class] has a type with a destructor that is
3362 // delete or inaccessible from the defaulted default constructor
3363 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3364 if (BaseDtor->isDeleted())
3365 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003366 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003367 AR_accessible)
3368 return true;
3369
3370 // -- any [virtual base class either] has no default constructor or
3371 // overload resolution as applied to [its] default constructor
3372 // results in an ambiguity or in a function that is deleted or
3373 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003374 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3375 if (!BaseDefault || BaseDefault->isDeleted())
3376 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003377
Alexis Hunteef8ee02011-06-10 03:50:41 +00003378 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3379 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003380 return true;
3381 }
3382
3383 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3384 FE = RD->field_end();
3385 FI != FE; ++FI) {
3386 QualType FieldType = Context.getBaseElementType(FI->getType());
3387 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3388
3389 // -- any non-static data member with no brace-or-equal-initializer is of
3390 // reference type
3391 if (FieldType->isReferenceType())
3392 return true;
3393
3394 // -- X is a union and all its variant members are of const-qualified type
3395 // (or array thereof)
3396 if (Union && !FieldType.isConstQualified())
3397 AllConst = false;
3398
3399 if (FieldRecord) {
3400 // -- X is a union-like class that has a variant member with a non-trivial
3401 // default constructor
3402 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3403 return true;
3404
3405 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3406 if (FieldDtor->isDeleted())
3407 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003408 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003409 AR_accessible)
3410 return true;
3411
3412 // -- any non-variant non-static data member of const-qualified type (or
3413 // array thereof) with no brace-or-equal-initializer does not have a
3414 // user-provided default constructor
3415 if (FieldType.isConstQualified() &&
3416 !FieldRecord->hasUserProvidedDefaultConstructor())
3417 return true;
3418
3419 if (!Union && FieldRecord->isUnion() &&
3420 FieldRecord->isAnonymousStructOrUnion()) {
3421 // We're okay to reuse AllConst here since we only care about the
3422 // value otherwise if we're in a union.
3423 AllConst = true;
3424
3425 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3426 UE = FieldRecord->field_end();
3427 UI != UE; ++UI) {
3428 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3429 CXXRecordDecl *UnionFieldRecord =
3430 UnionFieldType->getAsCXXRecordDecl();
3431
3432 if (!UnionFieldType.isConstQualified())
3433 AllConst = false;
3434
3435 if (UnionFieldRecord &&
3436 !UnionFieldRecord->hasTrivialDefaultConstructor())
3437 return true;
3438 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003439
Alexis Huntea6f0322011-05-11 22:34:38 +00003440 if (AllConst)
3441 return true;
3442
3443 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003444 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003445 continue;
3446 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003447
3448 // -- any non-static data member ... has class type M (or array thereof)
3449 // and either M has no default constructor or overload resolution as
3450 // applied to M's default constructor results in an ambiguity or in a
3451 // function that is deleted or inaccessible from the defaulted default
3452 // constructor.
3453 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3454 if (!FieldDefault || FieldDefault->isDeleted())
3455 return true;
3456 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3457 PDiag()) != AR_accessible)
3458 return true;
Alexis Hunta671bca2011-05-20 21:43:47 +00003459 } else if (!Union && FieldType.isConstQualified()) {
3460 // -- any non-variant non-static data member of const-qualified type (or
3461 // array thereof) with no brace-or-equal-initializer does not have a
3462 // user-provided default constructor
3463 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003464 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003465 }
3466
3467 if (Union && AllConst)
3468 return true;
3469
3470 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003471}
3472
Alexis Hunt913820d2011-05-13 06:10:58 +00003473bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003474 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003475 assert(!RD->isDependentType() && "do deletion after instantiation");
3476 if (!LangOpts.CPlusPlus0x)
3477 return false;
3478
Alexis Hunte77a28f2011-05-18 03:41:58 +00003479 SourceLocation Loc = CD->getLocation();
3480
Alexis Hunt913820d2011-05-13 06:10:58 +00003481 // Do access control from the constructor
3482 ContextRAII CtorContext(*this, CD);
3483
Alexis Huntc9a55732011-05-14 05:23:28 +00003484 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003485
Alexis Huntc9a55732011-05-14 05:23:28 +00003486 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3487 "copy assignment arg has no pointee type");
3488 bool ConstArg =
3489 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Alexis Hunt913820d2011-05-13 06:10:58 +00003490
3491 // We do this because we should never actually use an anonymous
3492 // union's constructor.
3493 if (Union && RD->isAnonymousStructOrUnion())
3494 return false;
3495
3496 // FIXME: We should put some diagnostic logic right into this function.
3497
3498 // C++0x [class.copy]/11
3499 // A defaulted [copy] constructor for class X is defined as delete if X has:
3500
3501 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3502 BE = RD->bases_end();
3503 BI != BE; ++BI) {
3504 // We'll handle this one later
3505 if (BI->isVirtual())
3506 continue;
3507
3508 QualType BaseType = BI->getType();
3509 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3510 assert(BaseDecl && "base isn't a CXXRecordDecl");
3511
3512 // -- any [direct base class] of a type with a destructor that is deleted or
3513 // inaccessible from the defaulted constructor
3514 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3515 if (BaseDtor->isDeleted())
3516 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003517 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003518 AR_accessible)
3519 return true;
3520
3521 // -- a [direct base class] B that cannot be [copied] because overload
3522 // resolution, as applied to B's [copy] constructor, results in an
3523 // ambiguity or a function that is deleted or inaccessible from the
3524 // defaulted constructor
3525 InitializedEntity BaseEntity =
3526 InitializedEntity::InitializeBase(Context, BI, 0);
3527 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003528 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Hunt913820d2011-05-13 06:10:58 +00003529
3530 // Construct a fake expression to perform the copy overloading.
3531 QualType ArgType = BaseType.getUnqualifiedType();
Alexis Hunt913820d2011-05-13 06:10:58 +00003532 if (ConstArg)
3533 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003534 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Alexis Hunt913820d2011-05-13 06:10:58 +00003535
3536 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1);
3537
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003538 if (InitSeq.Failed())
Alexis Hunt913820d2011-05-13 06:10:58 +00003539 return true;
3540 }
3541
3542 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3543 BE = RD->vbases_end();
3544 BI != BE; ++BI) {
3545 QualType BaseType = BI->getType();
3546 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3547 assert(BaseDecl && "base isn't a CXXRecordDecl");
3548
Alexis Hunteef8ee02011-06-10 03:50:41 +00003549 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00003550 // inaccessible from the defaulted constructor
3551 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3552 if (BaseDtor->isDeleted())
3553 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003554 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003555 AR_accessible)
3556 return true;
3557
3558 // -- a [virtual base class] B that cannot be [copied] because overload
3559 // resolution, as applied to B's [copy] constructor, results in an
3560 // ambiguity or a function that is deleted or inaccessible from the
3561 // defaulted constructor
3562 InitializedEntity BaseEntity =
3563 InitializedEntity::InitializeBase(Context, BI, BI);
3564 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003565 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Hunt913820d2011-05-13 06:10:58 +00003566
3567 // Construct a fake expression to perform the copy overloading.
3568 QualType ArgType = BaseType.getUnqualifiedType();
Alexis Hunt913820d2011-05-13 06:10:58 +00003569 if (ConstArg)
3570 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003571 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Alexis Hunt913820d2011-05-13 06:10:58 +00003572
3573 InitializationSequence InitSeq(*this, BaseEntity, Kind, &Arg, 1);
3574
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003575 if (InitSeq.Failed())
Alexis Hunt913820d2011-05-13 06:10:58 +00003576 return true;
3577 }
3578
3579 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3580 FE = RD->field_end();
3581 FI != FE; ++FI) {
3582 QualType FieldType = Context.getBaseElementType(FI->getType());
3583
3584 // -- for a copy constructor, a non-static data member of rvalue reference
3585 // type
3586 if (FieldType->isRValueReferenceType())
3587 return true;
3588
3589 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3590
3591 if (FieldRecord) {
3592 // This is an anonymous union
3593 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3594 // Anonymous unions inside unions do not variant members create
3595 if (!Union) {
3596 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3597 UE = FieldRecord->field_end();
3598 UI != UE; ++UI) {
3599 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3600 CXXRecordDecl *UnionFieldRecord =
3601 UnionFieldType->getAsCXXRecordDecl();
3602
3603 // -- a variant member with a non-trivial [copy] constructor and X
3604 // is a union-like class
3605 if (UnionFieldRecord &&
3606 !UnionFieldRecord->hasTrivialCopyConstructor())
3607 return true;
3608 }
3609 }
3610
3611 // Don't try to initalize an anonymous union
3612 continue;
3613 } else {
3614 // -- a variant member with a non-trivial [copy] constructor and X is a
3615 // union-like class
3616 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3617 return true;
3618
3619 // -- any [non-static data member] of a type with a destructor that is
3620 // deleted or inaccessible from the defaulted constructor
3621 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3622 if (FieldDtor->isDeleted())
3623 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003624 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003625 AR_accessible)
3626 return true;
3627 }
3628 }
3629
Alexis Huntb5b14c82011-05-13 21:10:11 +00003630 llvm::SmallVector<InitializedEntity, 4> Entities;
3631 QualType CurType = FI->getType();
3632 Entities.push_back(InitializedEntity::InitializeMember(*FI, 0));
3633 while (CurType->isArrayType()) {
3634 Entities.push_back(InitializedEntity::InitializeElement(Context, 0,
3635 Entities.back()));
3636 CurType = Context.getAsArrayType(CurType)->getElementType();
3637 }
3638
Alexis Hunt913820d2011-05-13 06:10:58 +00003639 InitializationKind Kind =
Alexis Hunte77a28f2011-05-18 03:41:58 +00003640 InitializationKind::CreateDirect(Loc, Loc, Loc);
Alexis Hunt913820d2011-05-13 06:10:58 +00003641
3642 // Construct a fake expression to perform the copy overloading.
3643 QualType ArgType = FieldType;
3644 if (ArgType->isReferenceType())
3645 ArgType = ArgType->getPointeeType();
Alexis Huntc9a55732011-05-14 05:23:28 +00003646 else if (ConstArg)
Alexis Hunt913820d2011-05-13 06:10:58 +00003647 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003648 Expr *Arg = new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue);
Alexis Hunt913820d2011-05-13 06:10:58 +00003649
Alexis Huntb5b14c82011-05-13 21:10:11 +00003650 InitializationSequence InitSeq(*this, Entities.back(), Kind, &Arg, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00003651
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003652 if (InitSeq.Failed())
Alexis Hunt913820d2011-05-13 06:10:58 +00003653 return true;
3654 }
3655
3656 return false;
3657}
3658
Alexis Huntb2f27802011-05-14 05:23:24 +00003659bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3660 CXXRecordDecl *RD = MD->getParent();
3661 assert(!RD->isDependentType() && "do deletion after instantiation");
3662 if (!LangOpts.CPlusPlus0x)
3663 return false;
3664
Alexis Hunte77a28f2011-05-18 03:41:58 +00003665 SourceLocation Loc = MD->getLocation();
3666
Alexis Huntb2f27802011-05-14 05:23:24 +00003667 // Do access control from the constructor
3668 ContextRAII MethodContext(*this, MD);
3669
3670 bool Union = RD->isUnion();
3671
Alexis Huntc9a55732011-05-14 05:23:28 +00003672 bool ConstArg =
3673 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Alexis Huntb2f27802011-05-14 05:23:24 +00003674
3675 // We do this because we should never actually use an anonymous
3676 // union's constructor.
3677 if (Union && RD->isAnonymousStructOrUnion())
3678 return false;
3679
3680 DeclarationName OperatorName =
3681 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunte77a28f2011-05-18 03:41:58 +00003682 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
Alexis Huntb2f27802011-05-14 05:23:24 +00003683 R.suppressDiagnostics();
3684
3685 // FIXME: We should put some diagnostic logic right into this function.
3686
3687 // C++0x [class.copy]/11
3688 // A defaulted [copy] assignment operator for class X is defined as deleted
3689 // if X has:
3690
3691 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3692 BE = RD->bases_end();
3693 BI != BE; ++BI) {
3694 // We'll handle this one later
3695 if (BI->isVirtual())
3696 continue;
3697
3698 QualType BaseType = BI->getType();
3699 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3700 assert(BaseDecl && "base isn't a CXXRecordDecl");
3701
3702 // -- a [direct base class] B that cannot be [copied] because overload
3703 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00003704 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00003705 // assignment operator
3706
3707 LookupQualifiedName(R, BaseDecl, false);
3708
3709 // Filter out any result that isn't a copy-assignment operator.
3710 LookupResult::Filter F = R.makeFilter();
3711 while (F.hasNext()) {
3712 NamedDecl *D = F.next();
3713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3714 if (Method->isCopyAssignmentOperator())
3715 continue;
3716
3717 F.erase();
3718 }
3719 F.done();
3720
3721 // Build a fake argument expression
3722 QualType ArgType = BaseType;
Alexis Huntc9a55732011-05-14 05:23:28 +00003723 QualType ThisType = BaseType;
Alexis Huntb2f27802011-05-14 05:23:24 +00003724 if (ConstArg)
3725 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003726 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3727 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Alexis Huntc9a55732011-05-14 05:23:28 +00003728 };
Alexis Huntb2f27802011-05-14 05:23:24 +00003729
Alexis Hunte77a28f2011-05-18 03:41:58 +00003730 OverloadCandidateSet OCS((Loc));
Alexis Huntb2f27802011-05-14 05:23:24 +00003731 OverloadCandidateSet::iterator Best;
3732
Alexis Huntc9a55732011-05-14 05:23:28 +00003733 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
Alexis Huntb2f27802011-05-14 05:23:24 +00003734
Alexis Hunte77a28f2011-05-18 03:41:58 +00003735 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Alexis Huntb2f27802011-05-14 05:23:24 +00003736 OR_Success)
3737 return true;
3738 }
3739
3740 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3741 BE = RD->vbases_end();
3742 BI != BE; ++BI) {
3743 QualType BaseType = BI->getType();
3744 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3745 assert(BaseDecl && "base isn't a CXXRecordDecl");
3746
Alexis Huntb2f27802011-05-14 05:23:24 +00003747 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00003748 // resolution, as applied to B's [copy] assignment operator, results in
3749 // an ambiguity or a function that is deleted or inaccessible from the
3750 // assignment operator
Alexis Huntb2f27802011-05-14 05:23:24 +00003751
Alexis Huntc9a55732011-05-14 05:23:28 +00003752 LookupQualifiedName(R, BaseDecl, false);
3753
3754 // Filter out any result that isn't a copy-assignment operator.
3755 LookupResult::Filter F = R.makeFilter();
3756 while (F.hasNext()) {
3757 NamedDecl *D = F.next();
3758 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3759 if (Method->isCopyAssignmentOperator())
3760 continue;
3761
3762 F.erase();
3763 }
3764 F.done();
3765
3766 // Build a fake argument expression
3767 QualType ArgType = BaseType;
3768 QualType ThisType = BaseType;
Alexis Huntb2f27802011-05-14 05:23:24 +00003769 if (ConstArg)
3770 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003771 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3772 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Alexis Huntc9a55732011-05-14 05:23:28 +00003773 };
Alexis Huntb2f27802011-05-14 05:23:24 +00003774
Alexis Hunte77a28f2011-05-18 03:41:58 +00003775 OverloadCandidateSet OCS((Loc));
Alexis Huntc9a55732011-05-14 05:23:28 +00003776 OverloadCandidateSet::iterator Best;
Alexis Huntb2f27802011-05-14 05:23:24 +00003777
Alexis Huntc9a55732011-05-14 05:23:28 +00003778 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3779
Alexis Hunte77a28f2011-05-18 03:41:58 +00003780 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Alexis Huntc9a55732011-05-14 05:23:28 +00003781 OR_Success)
Alexis Huntb2f27802011-05-14 05:23:24 +00003782 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00003783 }
3784
3785 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3786 FE = RD->field_end();
3787 FI != FE; ++FI) {
3788 QualType FieldType = Context.getBaseElementType(FI->getType());
3789
3790 // -- a non-static data member of reference type
3791 if (FieldType->isReferenceType())
3792 return true;
3793
3794 // -- a non-static data member of const non-class type (or array thereof)
3795 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3796 return true;
3797
3798 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3799
3800 if (FieldRecord) {
3801 // This is an anonymous union
3802 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3803 // Anonymous unions inside unions do not variant members create
3804 if (!Union) {
3805 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3806 UE = FieldRecord->field_end();
3807 UI != UE; ++UI) {
3808 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3809 CXXRecordDecl *UnionFieldRecord =
3810 UnionFieldType->getAsCXXRecordDecl();
3811
3812 // -- a variant member with a non-trivial [copy] assignment operator
3813 // and X is a union-like class
3814 if (UnionFieldRecord &&
3815 !UnionFieldRecord->hasTrivialCopyAssignment())
3816 return true;
3817 }
3818 }
3819
3820 // Don't try to initalize an anonymous union
3821 continue;
3822 // -- a variant member with a non-trivial [copy] assignment operator
3823 // and X is a union-like class
3824 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3825 return true;
3826 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003827
Alexis Huntc9a55732011-05-14 05:23:28 +00003828 LookupQualifiedName(R, FieldRecord, false);
Alexis Huntb2f27802011-05-14 05:23:24 +00003829
Alexis Huntc9a55732011-05-14 05:23:28 +00003830 // Filter out any result that isn't a copy-assignment operator.
3831 LookupResult::Filter F = R.makeFilter();
3832 while (F.hasNext()) {
3833 NamedDecl *D = F.next();
3834 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3835 if (Method->isCopyAssignmentOperator())
3836 continue;
3837
3838 F.erase();
3839 }
3840 F.done();
Alexis Huntb2f27802011-05-14 05:23:24 +00003841
Alexis Huntc9a55732011-05-14 05:23:28 +00003842 // Build a fake argument expression
3843 QualType ArgType = FieldType;
3844 QualType ThisType = FieldType;
3845 if (ConstArg)
3846 ArgType.addConst();
Alexis Hunte77a28f2011-05-18 03:41:58 +00003847 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3848 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
Alexis Huntc9a55732011-05-14 05:23:28 +00003849 };
Alexis Huntb2f27802011-05-14 05:23:24 +00003850
Alexis Hunte77a28f2011-05-18 03:41:58 +00003851 OverloadCandidateSet OCS((Loc));
Alexis Huntc9a55732011-05-14 05:23:28 +00003852 OverloadCandidateSet::iterator Best;
3853
3854 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3855
Alexis Hunte77a28f2011-05-18 03:41:58 +00003856 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
Alexis Huntc9a55732011-05-14 05:23:28 +00003857 OR_Success)
3858 return true;
3859 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003860 }
3861
3862 return false;
3863}
3864
Alexis Huntf91729462011-05-12 22:46:25 +00003865bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3866 CXXRecordDecl *RD = DD->getParent();
3867 assert(!RD->isDependentType() && "do deletion after instantiation");
3868 if (!LangOpts.CPlusPlus0x)
3869 return false;
3870
Alexis Hunte77a28f2011-05-18 03:41:58 +00003871 SourceLocation Loc = DD->getLocation();
3872
Alexis Huntf91729462011-05-12 22:46:25 +00003873 // Do access control from the destructor
3874 ContextRAII CtorContext(*this, DD);
3875
3876 bool Union = RD->isUnion();
3877
Alexis Hunt913820d2011-05-13 06:10:58 +00003878 // We do this because we should never actually use an anonymous
3879 // union's destructor.
3880 if (Union && RD->isAnonymousStructOrUnion())
3881 return false;
3882
Alexis Huntf91729462011-05-12 22:46:25 +00003883 // C++0x [class.dtor]p5
3884 // A defaulted destructor for a class X is defined as deleted if:
3885 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3886 BE = RD->bases_end();
3887 BI != BE; ++BI) {
3888 // We'll handle this one later
3889 if (BI->isVirtual())
3890 continue;
3891
3892 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3893 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3894 assert(BaseDtor && "base has no destructor");
3895
3896 // -- any direct or virtual base class has a deleted destructor or
3897 // a destructor that is inaccessible from the defaulted destructor
3898 if (BaseDtor->isDeleted())
3899 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003900 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003901 AR_accessible)
3902 return true;
3903 }
3904
3905 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3906 BE = RD->vbases_end();
3907 BI != BE; ++BI) {
3908 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3909 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3910 assert(BaseDtor && "base has no destructor");
3911
3912 // -- any direct or virtual base class has a deleted destructor or
3913 // a destructor that is inaccessible from the defaulted destructor
3914 if (BaseDtor->isDeleted())
3915 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003916 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003917 AR_accessible)
3918 return true;
3919 }
3920
3921 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3922 FE = RD->field_end();
3923 FI != FE; ++FI) {
3924 QualType FieldType = Context.getBaseElementType(FI->getType());
3925 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3926 if (FieldRecord) {
3927 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3928 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3929 UE = FieldRecord->field_end();
3930 UI != UE; ++UI) {
3931 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3932 CXXRecordDecl *UnionFieldRecord =
3933 UnionFieldType->getAsCXXRecordDecl();
3934
3935 // -- X is a union-like class that has a variant member with a non-
3936 // trivial destructor.
3937 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3938 return true;
3939 }
3940 // Technically we are supposed to do this next check unconditionally.
3941 // But that makes absolutely no sense.
3942 } else {
3943 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3944
3945 // -- any of the non-static data members has class type M (or array
3946 // thereof) and M has a deleted destructor or a destructor that is
3947 // inaccessible from the defaulted destructor
3948 if (FieldDtor->isDeleted())
3949 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003950 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003951 AR_accessible)
3952 return true;
3953
3954 // -- X is a union-like class that has a variant member with a non-
3955 // trivial destructor.
3956 if (Union && !FieldDtor->isTrivial())
3957 return true;
3958 }
3959 }
3960 }
3961
3962 if (DD->isVirtual()) {
3963 FunctionDecl *OperatorDelete = 0;
3964 DeclarationName Name =
3965 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00003966 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00003967 false))
3968 return true;
3969 }
3970
3971
3972 return false;
3973}
3974
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003975/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00003976namespace {
3977 struct FindHiddenVirtualMethodData {
3978 Sema *S;
3979 CXXMethodDecl *Method;
3980 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3981 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3982 };
3983}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003984
3985/// \brief Member lookup function that determines whether a given C++
3986/// method overloads virtual methods in a base class without overriding any,
3987/// to be used with CXXRecordDecl::lookupInBases().
3988static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3989 CXXBasePath &Path,
3990 void *UserData) {
3991 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3992
3993 FindHiddenVirtualMethodData &Data
3994 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3995
3996 DeclarationName Name = Data.Method->getDeclName();
3997 assert(Name.getNameKind() == DeclarationName::Identifier);
3998
3999 bool foundSameNameMethod = false;
4000 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4001 for (Path.Decls = BaseRecord->lookup(Name);
4002 Path.Decls.first != Path.Decls.second;
4003 ++Path.Decls.first) {
4004 NamedDecl *D = *Path.Decls.first;
4005 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004006 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004007 foundSameNameMethod = true;
4008 // Interested only in hidden virtual methods.
4009 if (!MD->isVirtual())
4010 continue;
4011 // If the method we are checking overrides a method from its base
4012 // don't warn about the other overloaded methods.
4013 if (!Data.S->IsOverload(Data.Method, MD, false))
4014 return true;
4015 // Collect the overload only if its hidden.
4016 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4017 overloadedMethods.push_back(MD);
4018 }
4019 }
4020
4021 if (foundSameNameMethod)
4022 Data.OverloadedMethods.append(overloadedMethods.begin(),
4023 overloadedMethods.end());
4024 return foundSameNameMethod;
4025}
4026
4027/// \brief See if a method overloads virtual methods in a base class without
4028/// overriding any.
4029void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4030 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4031 MD->getLocation()) == Diagnostic::Ignored)
4032 return;
4033 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4034 return;
4035
4036 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4037 /*bool RecordPaths=*/false,
4038 /*bool DetectVirtual=*/false);
4039 FindHiddenVirtualMethodData Data;
4040 Data.Method = MD;
4041 Data.S = this;
4042
4043 // Keep the base methods that were overriden or introduced in the subclass
4044 // by 'using' in a set. A base method not in this set is hidden.
4045 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4046 res.first != res.second; ++res.first) {
4047 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4048 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4049 E = MD->end_overridden_methods();
4050 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004051 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004052 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004054 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004055 }
4056
4057 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4058 !Data.OverloadedMethods.empty()) {
4059 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4060 << MD << (Data.OverloadedMethods.size() > 1);
4061
4062 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4063 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4064 Diag(overloadedMD->getLocation(),
4065 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4066 }
4067 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004068}
4069
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004070void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004071 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004072 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004073 SourceLocation RBrac,
4074 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004075 if (!TagDecl)
4076 return;
Mike Stump11289f42009-09-09 15:08:12 +00004077
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004078 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004079
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004080 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00004081 // strict aliasing violation!
4082 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004083 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004084
Douglas Gregor0be31a22010-07-02 17:43:08 +00004085 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004086 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004087}
4088
Douglas Gregor05379422008-11-03 17:51:48 +00004089/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4090/// special functions, such as the default constructor, copy
4091/// constructor, or destructor, to the given C++ class (C++
4092/// [special]p1). This routine can only be executed just before the
4093/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004094void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004095 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004096 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004097
Douglas Gregor54be3392010-07-01 17:57:27 +00004098 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004099 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004100
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004101 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4102 ++ASTContext::NumImplicitCopyAssignmentOperators;
4103
4104 // If we have a dynamic class, then the copy assignment operator may be
4105 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4106 // it shows up in the right place in the vtable and that we diagnose
4107 // problems with the implicit exception specification.
4108 if (ClassDecl->isDynamicClass())
4109 DeclareImplicitCopyAssignment(ClassDecl);
4110 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004111
Douglas Gregor7454c562010-07-02 20:37:36 +00004112 if (!ClassDecl->hasUserDeclaredDestructor()) {
4113 ++ASTContext::NumImplicitDestructors;
4114
4115 // If we have a dynamic class, then the destructor may be virtual, so we
4116 // have to declare the destructor immediately. This ensures that, e.g., it
4117 // shows up in the right place in the vtable and that we diagnose problems
4118 // with the implicit exception specification.
4119 if (ClassDecl->isDynamicClass())
4120 DeclareImplicitDestructor(ClassDecl);
4121 }
Douglas Gregor05379422008-11-03 17:51:48 +00004122}
4123
Francois Pichet1c229c02011-04-22 22:18:13 +00004124void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4125 if (!D)
4126 return;
4127
4128 int NumParamList = D->getNumTemplateParameterLists();
4129 for (int i = 0; i < NumParamList; i++) {
4130 TemplateParameterList* Params = D->getTemplateParameterList(i);
4131 for (TemplateParameterList::iterator Param = Params->begin(),
4132 ParamEnd = Params->end();
4133 Param != ParamEnd; ++Param) {
4134 NamedDecl *Named = cast<NamedDecl>(*Param);
4135 if (Named->getDeclName()) {
4136 S->AddDecl(Named);
4137 IdResolver.AddDecl(Named);
4138 }
4139 }
4140 }
4141}
4142
John McCall48871652010-08-21 09:40:31 +00004143void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004144 if (!D)
4145 return;
4146
4147 TemplateParameterList *Params = 0;
4148 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4149 Params = Template->getTemplateParameters();
4150 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4151 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4152 Params = PartialSpec->getTemplateParameters();
4153 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004154 return;
4155
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004156 for (TemplateParameterList::iterator Param = Params->begin(),
4157 ParamEnd = Params->end();
4158 Param != ParamEnd; ++Param) {
4159 NamedDecl *Named = cast<NamedDecl>(*Param);
4160 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004161 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004162 IdResolver.AddDecl(Named);
4163 }
4164 }
4165}
4166
John McCall48871652010-08-21 09:40:31 +00004167void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004168 if (!RecordD) return;
4169 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004170 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004171 PushDeclContext(S, Record);
4172}
4173
John McCall48871652010-08-21 09:40:31 +00004174void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004175 if (!RecordD) return;
4176 PopDeclContext();
4177}
4178
Douglas Gregor4d87df52008-12-16 21:30:33 +00004179/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4180/// parsing a top-level (non-nested) C++ class, and we are now
4181/// parsing those parts of the given Method declaration that could
4182/// not be parsed earlier (C++ [class.mem]p2), such as default
4183/// arguments. This action should enter the scope of the given
4184/// Method declaration as if we had just parsed the qualified method
4185/// name. However, it should not bring the parameters into scope;
4186/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004187void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004188}
4189
4190/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4191/// C++ method declaration. We're (re-)introducing the given
4192/// function parameter into scope for use in parsing later parts of
4193/// the method declaration. For example, we could see an
4194/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004195void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004196 if (!ParamD)
4197 return;
Mike Stump11289f42009-09-09 15:08:12 +00004198
John McCall48871652010-08-21 09:40:31 +00004199 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004200
4201 // If this parameter has an unparsed default argument, clear it out
4202 // to make way for the parsed default argument.
4203 if (Param->hasUnparsedDefaultArg())
4204 Param->setDefaultArg(0);
4205
John McCall48871652010-08-21 09:40:31 +00004206 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004207 if (Param->getDeclName())
4208 IdResolver.AddDecl(Param);
4209}
4210
4211/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4212/// processing the delayed method declaration for Method. The method
4213/// declaration is now considered finished. There may be a separate
4214/// ActOnStartOfFunctionDef action later (not necessarily
4215/// immediately!) for this method, if it was also defined inside the
4216/// class body.
John McCall48871652010-08-21 09:40:31 +00004217void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004218 if (!MethodD)
4219 return;
Mike Stump11289f42009-09-09 15:08:12 +00004220
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004221 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004222
John McCall48871652010-08-21 09:40:31 +00004223 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004224
4225 // Now that we have our default arguments, check the constructor
4226 // again. It could produce additional diagnostics or affect whether
4227 // the class has implicitly-declared destructors, among other
4228 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004229 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4230 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004231
4232 // Check the default arguments, which we may have added.
4233 if (!Method->isInvalidDecl())
4234 CheckCXXDefaultArguments(Method);
4235}
4236
Douglas Gregor831c93f2008-11-05 20:51:48 +00004237/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004238/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004239/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004240/// emit diagnostics and set the invalid bit to true. In any case, the type
4241/// will be updated to reflect a well-formed type for the constructor and
4242/// returned.
4243QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004244 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004245 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004246
4247 // C++ [class.ctor]p3:
4248 // A constructor shall not be virtual (10.3) or static (9.4). A
4249 // constructor can be invoked for a const, volatile or const
4250 // volatile object. A constructor shall not be declared const,
4251 // volatile, or const volatile (9.3.2).
4252 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004253 if (!D.isInvalidType())
4254 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4255 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4256 << SourceRange(D.getIdentifierLoc());
4257 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004258 }
John McCall8e7d6562010-08-26 03:08:43 +00004259 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004260 if (!D.isInvalidType())
4261 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4262 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4263 << SourceRange(D.getIdentifierLoc());
4264 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004265 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004266 }
Mike Stump11289f42009-09-09 15:08:12 +00004267
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004268 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004269 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004270 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004271 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4272 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004273 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004274 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4275 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004276 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004277 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4278 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004279 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004280 }
Mike Stump11289f42009-09-09 15:08:12 +00004281
Douglas Gregordb9d6642011-01-26 05:01:58 +00004282 // C++0x [class.ctor]p4:
4283 // A constructor shall not be declared with a ref-qualifier.
4284 if (FTI.hasRefQualifier()) {
4285 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4286 << FTI.RefQualifierIsLValueRef
4287 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4288 D.setInvalidType();
4289 }
4290
Douglas Gregor831c93f2008-11-05 20:51:48 +00004291 // Rebuild the function type "R" without any type qualifiers (in
4292 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004293 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004294 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004295 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4296 return R;
4297
4298 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4299 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004300 EPI.RefQualifier = RQ_None;
4301
Chris Lattner38378bf2009-04-25 08:28:21 +00004302 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004303 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004304}
4305
Douglas Gregor4d87df52008-12-16 21:30:33 +00004306/// CheckConstructor - Checks a fully-formed constructor for
4307/// well-formedness, issuing any diagnostics required. Returns true if
4308/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004309void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004310 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004311 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4312 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004313 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004314
4315 // C++ [class.copy]p3:
4316 // A declaration of a constructor for a class X is ill-formed if
4317 // its first parameter is of type (optionally cv-qualified) X and
4318 // either there are no other parameters or else all other
4319 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004320 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004321 ((Constructor->getNumParams() == 1) ||
4322 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004323 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4324 Constructor->getTemplateSpecializationKind()
4325 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004326 QualType ParamType = Constructor->getParamDecl(0)->getType();
4327 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4328 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004329 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004330 const char *ConstRef
4331 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4332 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004333 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004334 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004335
4336 // FIXME: Rather that making the constructor invalid, we should endeavor
4337 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004338 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004339 }
4340 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004341}
4342
John McCalldeb646e2010-08-04 01:04:25 +00004343/// CheckDestructor - Checks a fully-formed destructor definition for
4344/// well-formedness, issuing any diagnostics required. Returns true
4345/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004346bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004347 CXXRecordDecl *RD = Destructor->getParent();
4348
4349 if (Destructor->isVirtual()) {
4350 SourceLocation Loc;
4351
4352 if (!Destructor->isImplicit())
4353 Loc = Destructor->getLocation();
4354 else
4355 Loc = RD->getLocation();
4356
4357 // If we have a virtual destructor, look up the deallocation function
4358 FunctionDecl *OperatorDelete = 0;
4359 DeclarationName Name =
4360 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004361 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004362 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004363
4364 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004365
4366 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004367 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004368
4369 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004370}
4371
Mike Stump11289f42009-09-09 15:08:12 +00004372static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004373FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4374 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4375 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004376 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004377}
4378
Douglas Gregor831c93f2008-11-05 20:51:48 +00004379/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4380/// the well-formednes of the destructor declarator @p D with type @p
4381/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004382/// emit diagnostics and set the declarator to invalid. Even if this happens,
4383/// will be updated to reflect a well-formed type for the destructor and
4384/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004385QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004386 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004387 // C++ [class.dtor]p1:
4388 // [...] A typedef-name that names a class is a class-name
4389 // (7.1.3); however, a typedef-name that names a class shall not
4390 // be used as the identifier in the declarator for a destructor
4391 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004392 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004393 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004394 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004395 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004396 else if (const TemplateSpecializationType *TST =
4397 DeclaratorType->getAs<TemplateSpecializationType>())
4398 if (TST->isTypeAlias())
4399 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4400 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004401
4402 // C++ [class.dtor]p2:
4403 // A destructor is used to destroy objects of its class type. A
4404 // destructor takes no parameters, and no return type can be
4405 // specified for it (not even void). The address of a destructor
4406 // shall not be taken. A destructor shall not be static. A
4407 // destructor can be invoked for a const, volatile or const
4408 // volatile object. A destructor shall not be declared const,
4409 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004410 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004411 if (!D.isInvalidType())
4412 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4413 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004414 << SourceRange(D.getIdentifierLoc())
4415 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4416
John McCall8e7d6562010-08-26 03:08:43 +00004417 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004418 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004419 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004420 // Destructors don't have return types, but the parser will
4421 // happily parse something like:
4422 //
4423 // class X {
4424 // float ~X();
4425 // };
4426 //
4427 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004428 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4429 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4430 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004431 }
Mike Stump11289f42009-09-09 15:08:12 +00004432
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004433 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004434 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004435 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004436 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4437 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004438 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004439 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4440 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004441 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004442 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4443 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00004444 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004445 }
4446
Douglas Gregordb9d6642011-01-26 05:01:58 +00004447 // C++0x [class.dtor]p2:
4448 // A destructor shall not be declared with a ref-qualifier.
4449 if (FTI.hasRefQualifier()) {
4450 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4451 << FTI.RefQualifierIsLValueRef
4452 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4453 D.setInvalidType();
4454 }
4455
Douglas Gregor831c93f2008-11-05 20:51:48 +00004456 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00004457 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004458 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4459
4460 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00004461 FTI.freeArgs();
4462 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004463 }
4464
Mike Stump11289f42009-09-09 15:08:12 +00004465 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00004466 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004467 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00004468 D.setInvalidType();
4469 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00004470
4471 // Rebuild the function type "R" without any type qualifiers or
4472 // parameters (in case any of the errors above fired) and with
4473 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00004474 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00004475 if (!D.isInvalidType())
4476 return R;
4477
Douglas Gregor95755162010-07-01 05:10:53 +00004478 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004479 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4480 EPI.Variadic = false;
4481 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004482 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004483 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004484}
4485
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004486/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4487/// well-formednes of the conversion function declarator @p D with
4488/// type @p R. If there are any errors in the declarator, this routine
4489/// will emit diagnostics and return true. Otherwise, it will return
4490/// false. Either way, the type @p R will be updated to reflect a
4491/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004492void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00004493 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004494 // C++ [class.conv.fct]p1:
4495 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00004496 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00004497 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00004498 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004499 if (!D.isInvalidType())
4500 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4501 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4502 << SourceRange(D.getIdentifierLoc());
4503 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004504 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004505 }
John McCall212fa2e2010-04-13 00:04:31 +00004506
4507 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4508
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004509 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004510 // Conversion functions don't have return types, but the parser will
4511 // happily parse something like:
4512 //
4513 // class X {
4514 // float operator bool();
4515 // };
4516 //
4517 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00004518 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4519 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4520 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00004521 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004522 }
4523
John McCall212fa2e2010-04-13 00:04:31 +00004524 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4525
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004526 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00004527 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004528 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4529
4530 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004531 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004532 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00004533 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004534 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004535 D.setInvalidType();
4536 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004537
John McCall212fa2e2010-04-13 00:04:31 +00004538 // Diagnose "&operator bool()" and other such nonsense. This
4539 // is actually a gcc extension which we don't support.
4540 if (Proto->getResultType() != ConvType) {
4541 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4542 << Proto->getResultType();
4543 D.setInvalidType();
4544 ConvType = Proto->getResultType();
4545 }
4546
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004547 // C++ [class.conv.fct]p4:
4548 // The conversion-type-id shall not represent a function type nor
4549 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004550 if (ConvType->isArrayType()) {
4551 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4552 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004553 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004554 } else if (ConvType->isFunctionType()) {
4555 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4556 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004557 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004558 }
4559
4560 // Rebuild the function type "R" without any parameters (in case any
4561 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00004562 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00004563 if (D.isInvalidType())
4564 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004565
Douglas Gregor5fb53972009-01-14 15:45:31 +00004566 // C++0x explicit conversion operators.
4567 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00004568 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00004569 diag::warn_explicit_conversion_functions)
4570 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004571}
4572
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004573/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4574/// the declaration of the given C++ conversion function. This routine
4575/// is responsible for recording the conversion function in the C++
4576/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00004577Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004578 assert(Conversion && "Expected to receive a conversion function declaration");
4579
Douglas Gregor4287b372008-12-12 08:25:50 +00004580 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004581
4582 // Make sure we aren't redeclaring the conversion function.
4583 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004584
4585 // C++ [class.conv.fct]p1:
4586 // [...] A conversion function is never used to convert a
4587 // (possibly cv-qualified) object to the (possibly cv-qualified)
4588 // same object type (or a reference to it), to a (possibly
4589 // cv-qualified) base class of that type (or a reference to it),
4590 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00004591 // FIXME: Suppress this warning if the conversion function ends up being a
4592 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00004593 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004594 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004595 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004596 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004597 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4598 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00004599 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004600 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004601 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4602 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004603 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004604 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004605 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004606 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004607 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004608 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004609 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004610 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004611 }
4612
Douglas Gregor457104e2010-09-29 04:25:11 +00004613 if (FunctionTemplateDecl *ConversionTemplate
4614 = Conversion->getDescribedFunctionTemplate())
4615 return ConversionTemplate;
4616
John McCall48871652010-08-21 09:40:31 +00004617 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004618}
4619
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004620//===----------------------------------------------------------------------===//
4621// Namespace Handling
4622//===----------------------------------------------------------------------===//
4623
John McCallb1be5232010-08-26 09:15:37 +00004624
4625
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004626/// ActOnStartNamespaceDef - This is called at the start of a namespace
4627/// definition.
John McCall48871652010-08-21 09:40:31 +00004628Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00004629 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004630 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00004631 SourceLocation IdentLoc,
4632 IdentifierInfo *II,
4633 SourceLocation LBrace,
4634 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004635 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4636 // For anonymous namespace, take the location of the left brace.
4637 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00004638 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004639 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004640 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004641
4642 Scope *DeclRegionScope = NamespcScope->getParent();
4643
Anders Carlssona7bcade2010-02-07 01:09:23 +00004644 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4645
John McCall2faf32c2010-12-10 02:59:44 +00004646 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4647 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00004648
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004649 if (II) {
4650 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00004651 // The identifier in an original-namespace-definition shall not
4652 // have been previously defined in the declarative region in
4653 // which the original-namespace-definition appears. The
4654 // identifier in an original-namespace-definition is the name of
4655 // the namespace. Subsequently in that declarative region, it is
4656 // treated as an original-namespace-name.
4657 //
4658 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00004659 // look through using directives, just look for any ordinary names.
4660
4661 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4662 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4663 Decl::IDNS_Namespace;
4664 NamedDecl *PrevDecl = 0;
4665 for (DeclContext::lookup_result R
4666 = CurContext->getRedeclContext()->lookup(II);
4667 R.first != R.second; ++R.first) {
4668 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4669 PrevDecl = *R.first;
4670 break;
4671 }
4672 }
4673
Douglas Gregor91f84212008-12-11 16:49:14 +00004674 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4675 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004676 if (Namespc->isInline() != OrigNS->isInline()) {
4677 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00004678 if (OrigNS->isInline()) {
4679 // The user probably just forgot the 'inline', so suggest that it
4680 // be added back.
4681 Diag(Namespc->getLocation(),
4682 diag::warn_inline_namespace_reopened_noninline)
4683 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4684 } else {
4685 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4686 << Namespc->isInline();
4687 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004688 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00004689
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004690 // Recover by ignoring the new namespace's inline status.
4691 Namespc->setInline(OrigNS->isInline());
4692 }
4693
Douglas Gregor91f84212008-12-11 16:49:14 +00004694 // Attach this namespace decl to the chain of extended namespace
4695 // definitions.
4696 OrigNS->setNextNamespace(Namespc);
4697 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004698
Mike Stump11289f42009-09-09 15:08:12 +00004699 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00004700 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00004701 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00004702 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004703 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004704 } else if (PrevDecl) {
4705 // This is an invalid name redefinition.
4706 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4707 << Namespc->getDeclName();
4708 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4709 Namespc->setInvalidDecl();
4710 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00004711 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004712 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004713 // This is the first "real" definition of the namespace "std", so update
4714 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004715 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004716 // We had already defined a dummy namespace "std". Link this new
4717 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004718 StdNS->setNextNamespace(Namespc);
4719 StdNS->setLocation(IdentLoc);
4720 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00004721 }
4722
4723 // Make our StdNamespace cache point at the first real definition of the
4724 // "std" namespace.
4725 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00004726 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004727
4728 PushOnScopeChains(Namespc, DeclRegionScope);
4729 } else {
John McCall4fa53422009-10-01 00:25:31 +00004730 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00004731 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00004732
4733 // Link the anonymous namespace into its parent.
4734 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00004735 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00004736 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4737 PrevDecl = TU->getAnonymousNamespace();
4738 TU->setAnonymousNamespace(Namespc);
4739 } else {
4740 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4741 PrevDecl = ND->getAnonymousNamespace();
4742 ND->setAnonymousNamespace(Namespc);
4743 }
4744
4745 // Link the anonymous namespace with its previous declaration.
4746 if (PrevDecl) {
4747 assert(PrevDecl->isAnonymousNamespace());
4748 assert(!PrevDecl->getNextNamespace());
4749 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4750 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004751
4752 if (Namespc->isInline() != PrevDecl->isInline()) {
4753 // inline-ness must match
4754 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4755 << Namespc->isInline();
4756 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4757 Namespc->setInvalidDecl();
4758 // Recover by ignoring the new namespace's inline status.
4759 Namespc->setInline(PrevDecl->isInline());
4760 }
John McCall0db42252009-12-16 02:06:49 +00004761 }
John McCall4fa53422009-10-01 00:25:31 +00004762
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00004763 CurContext->addDecl(Namespc);
4764
John McCall4fa53422009-10-01 00:25:31 +00004765 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4766 // behaves as if it were replaced by
4767 // namespace unique { /* empty body */ }
4768 // using namespace unique;
4769 // namespace unique { namespace-body }
4770 // where all occurrences of 'unique' in a translation unit are
4771 // replaced by the same identifier and this identifier differs
4772 // from all other identifiers in the entire program.
4773
4774 // We just create the namespace with an empty name and then add an
4775 // implicit using declaration, just like the standard suggests.
4776 //
4777 // CodeGen enforces the "universally unique" aspect by giving all
4778 // declarations semantically contained within an anonymous
4779 // namespace internal linkage.
4780
John McCall0db42252009-12-16 02:06:49 +00004781 if (!PrevDecl) {
4782 UsingDirectiveDecl* UD
4783 = UsingDirectiveDecl::Create(Context, CurContext,
4784 /* 'using' */ LBrace,
4785 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00004786 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00004787 /* identifier */ SourceLocation(),
4788 Namespc,
4789 /* Ancestor */ CurContext);
4790 UD->setImplicit();
4791 CurContext->addDecl(UD);
4792 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004793 }
4794
4795 // Although we could have an invalid decl (i.e. the namespace name is a
4796 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00004797 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4798 // for the namespace has the declarations that showed up in that particular
4799 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00004800 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00004801 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004802}
4803
Sebastian Redla6602e92009-11-23 15:34:23 +00004804/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4805/// is a namespace alias, returns the namespace it points to.
4806static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4807 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4808 return AD->getNamespace();
4809 return dyn_cast_or_null<NamespaceDecl>(D);
4810}
4811
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004812/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4813/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00004814void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004815 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4816 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004817 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004818 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00004819 if (Namespc->hasAttr<VisibilityAttr>())
4820 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004821}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004822
John McCall28a0cf72010-08-25 07:42:41 +00004823CXXRecordDecl *Sema::getStdBadAlloc() const {
4824 return cast_or_null<CXXRecordDecl>(
4825 StdBadAlloc.get(Context.getExternalSource()));
4826}
4827
4828NamespaceDecl *Sema::getStdNamespace() const {
4829 return cast_or_null<NamespaceDecl>(
4830 StdNamespace.get(Context.getExternalSource()));
4831}
4832
Douglas Gregorcdf87022010-06-29 17:53:46 +00004833/// \brief Retrieve the special "std" namespace, which may require us to
4834/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004835NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00004836 if (!StdNamespace) {
4837 // The "std" namespace has not yet been defined, so build one implicitly.
4838 StdNamespace = NamespaceDecl::Create(Context,
4839 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004840 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00004841 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004842 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004843 }
4844
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004845 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004846}
4847
Douglas Gregora172e082011-03-26 22:25:30 +00004848/// \brief Determine whether a using statement is in a context where it will be
4849/// apply in all contexts.
4850static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4851 switch (CurContext->getDeclKind()) {
4852 case Decl::TranslationUnit:
4853 return true;
4854 case Decl::LinkageSpec:
4855 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4856 default:
4857 return false;
4858 }
4859}
4860
John McCall48871652010-08-21 09:40:31 +00004861Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00004862 SourceLocation UsingLoc,
4863 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004864 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004865 SourceLocation IdentLoc,
4866 IdentifierInfo *NamespcName,
4867 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00004868 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4869 assert(NamespcName && "Invalid NamespcName.");
4870 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00004871
4872 // This can only happen along a recovery path.
4873 while (S->getFlags() & Scope::TemplateParamScope)
4874 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00004875 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00004876
Douglas Gregor889ceb72009-02-03 19:21:40 +00004877 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00004878 NestedNameSpecifier *Qualifier = 0;
4879 if (SS.isSet())
4880 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4881
Douglas Gregor34074322009-01-14 22:20:51 +00004882 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004883 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4884 LookupParsedName(R, S, &SS);
4885 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004886 return 0;
John McCall27b18f82009-11-17 02:14:36 +00004887
Douglas Gregorcdf87022010-06-29 17:53:46 +00004888 if (R.empty()) {
4889 // Allow "using namespace std;" or "using namespace ::std;" even if
4890 // "std" hasn't been defined yet, for GCC compatibility.
4891 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4892 NamespcName->isStr("std")) {
4893 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004894 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00004895 R.resolveKind();
4896 }
4897 // Otherwise, attempt typo correction.
4898 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4899 CTC_NoKeywords, 0)) {
4900 if (R.getAsSingle<NamespaceDecl>() ||
4901 R.getAsSingle<NamespaceAliasDecl>()) {
4902 if (DeclContext *DC = computeDeclContext(SS, false))
4903 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4904 << NamespcName << DC << Corrected << SS.getRange()
4905 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4906 else
4907 Diag(IdentLoc, diag::err_using_directive_suggest)
4908 << NamespcName << Corrected
4909 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4910 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4911 << Corrected;
4912
4913 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004914 } else {
4915 R.clear();
4916 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004917 }
4918 }
4919 }
4920
John McCall9f3059a2009-10-09 21:13:30 +00004921 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00004922 NamedDecl *Named = R.getFoundDecl();
4923 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4924 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00004925 // C++ [namespace.udir]p1:
4926 // A using-directive specifies that the names in the nominated
4927 // namespace can be used in the scope in which the
4928 // using-directive appears after the using-directive. During
4929 // unqualified name lookup (3.4.1), the names appear as if they
4930 // were declared in the nearest enclosing namespace which
4931 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00004932 // namespace. [Note: in this context, "contains" means "contains
4933 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00004934
4935 // Find enclosing context containing both using-directive and
4936 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00004937 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004938 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4939 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4940 CommonAncestor = CommonAncestor->getParent();
4941
Sebastian Redla6602e92009-11-23 15:34:23 +00004942 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00004943 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00004944 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004945
Douglas Gregora172e082011-03-26 22:25:30 +00004946 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00004947 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004948 Diag(IdentLoc, diag::warn_using_directive_in_header);
4949 }
4950
Douglas Gregor889ceb72009-02-03 19:21:40 +00004951 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004952 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00004953 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00004954 }
4955
Douglas Gregor889ceb72009-02-03 19:21:40 +00004956 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00004957 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00004958}
4959
4960void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4961 // If scope has associated entity, then using directive is at namespace
4962 // or translation unit scope. We add UsingDirectiveDecls, into
4963 // it's lookup structure.
4964 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004965 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004966 else
4967 // Otherwise it is block-sope. using-directives will affect lookup
4968 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00004969 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004970}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004971
Douglas Gregorfec52632009-06-20 00:51:54 +00004972
John McCall48871652010-08-21 09:40:31 +00004973Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00004974 AccessSpecifier AS,
4975 bool HasUsingKeyword,
4976 SourceLocation UsingLoc,
4977 CXXScopeSpec &SS,
4978 UnqualifiedId &Name,
4979 AttributeList *AttrList,
4980 bool IsTypeName,
4981 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004982 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004983
Douglas Gregor220f4272009-11-04 16:30:06 +00004984 switch (Name.getKind()) {
4985 case UnqualifiedId::IK_Identifier:
4986 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004987 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004988 case UnqualifiedId::IK_ConversionFunctionId:
4989 break;
4990
4991 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004992 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004993 // C++0x inherited constructors.
4994 if (getLangOptions().CPlusPlus0x) break;
4995
Douglas Gregor220f4272009-11-04 16:30:06 +00004996 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4997 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004998 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004999
5000 case UnqualifiedId::IK_DestructorName:
5001 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5002 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005003 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005004
5005 case UnqualifiedId::IK_TemplateId:
5006 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5007 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00005008 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005009 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005010
5011 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5012 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005013 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005014 return 0;
John McCall3969e302009-12-08 07:46:18 +00005015
John McCalla0097262009-12-11 02:10:03 +00005016 // Warn about using declarations.
5017 // TODO: store that the declaration was written without 'using' and
5018 // talk about access decls instead of using decls in the
5019 // diagnostics.
5020 if (!HasUsingKeyword) {
5021 UsingLoc = Name.getSourceRange().getBegin();
5022
5023 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005024 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005025 }
5026
Douglas Gregorc4356532010-12-16 00:46:58 +00005027 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5028 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5029 return 0;
5030
John McCall3f746822009-11-17 05:59:44 +00005031 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005032 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005033 /* IsInstantiation */ false,
5034 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005035 if (UD)
5036 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005037
John McCall48871652010-08-21 09:40:31 +00005038 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005039}
5040
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005041/// \brief Determine whether a using declaration considers the given
5042/// declarations as "equivalent", e.g., if they are redeclarations of
5043/// the same entity or are both typedefs of the same type.
5044static bool
5045IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5046 bool &SuppressRedeclaration) {
5047 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5048 SuppressRedeclaration = false;
5049 return true;
5050 }
5051
Richard Smithdda56e42011-04-15 14:24:37 +00005052 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5053 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005054 SuppressRedeclaration = true;
5055 return Context.hasSameType(TD1->getUnderlyingType(),
5056 TD2->getUnderlyingType());
5057 }
5058
5059 return false;
5060}
5061
5062
John McCall84d87672009-12-10 09:41:52 +00005063/// Determines whether to create a using shadow decl for a particular
5064/// decl, given the set of decls existing prior to this using lookup.
5065bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5066 const LookupResult &Previous) {
5067 // Diagnose finding a decl which is not from a base class of the
5068 // current class. We do this now because there are cases where this
5069 // function will silently decide not to build a shadow decl, which
5070 // will pre-empt further diagnostics.
5071 //
5072 // We don't need to do this in C++0x because we do the check once on
5073 // the qualifier.
5074 //
5075 // FIXME: diagnose the following if we care enough:
5076 // struct A { int foo; };
5077 // struct B : A { using A::foo; };
5078 // template <class T> struct C : A {};
5079 // template <class T> struct D : C<T> { using B::foo; } // <---
5080 // This is invalid (during instantiation) in C++03 because B::foo
5081 // resolves to the using decl in B, which is not a base class of D<T>.
5082 // We can't diagnose it immediately because C<T> is an unknown
5083 // specialization. The UsingShadowDecl in D<T> then points directly
5084 // to A::foo, which will look well-formed when we instantiate.
5085 // The right solution is to not collapse the shadow-decl chain.
5086 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5087 DeclContext *OrigDC = Orig->getDeclContext();
5088
5089 // Handle enums and anonymous structs.
5090 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5091 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5092 while (OrigRec->isAnonymousStructOrUnion())
5093 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5094
5095 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5096 if (OrigDC == CurContext) {
5097 Diag(Using->getLocation(),
5098 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005099 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005100 Diag(Orig->getLocation(), diag::note_using_decl_target);
5101 return true;
5102 }
5103
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005104 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005105 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005106 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005107 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005108 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005109 Diag(Orig->getLocation(), diag::note_using_decl_target);
5110 return true;
5111 }
5112 }
5113
5114 if (Previous.empty()) return false;
5115
5116 NamedDecl *Target = Orig;
5117 if (isa<UsingShadowDecl>(Target))
5118 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5119
John McCalla17e83e2009-12-11 02:33:26 +00005120 // If the target happens to be one of the previous declarations, we
5121 // don't have a conflict.
5122 //
5123 // FIXME: but we might be increasing its access, in which case we
5124 // should redeclare it.
5125 NamedDecl *NonTag = 0, *Tag = 0;
5126 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5127 I != E; ++I) {
5128 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005129 bool Result;
5130 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5131 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005132
5133 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5134 }
5135
John McCall84d87672009-12-10 09:41:52 +00005136 if (Target->isFunctionOrFunctionTemplate()) {
5137 FunctionDecl *FD;
5138 if (isa<FunctionTemplateDecl>(Target))
5139 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5140 else
5141 FD = cast<FunctionDecl>(Target);
5142
5143 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005144 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005145 case Ovl_Overload:
5146 return false;
5147
5148 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005149 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005150 break;
5151
5152 // We found a decl with the exact signature.
5153 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005154 // If we're in a record, we want to hide the target, so we
5155 // return true (without a diagnostic) to tell the caller not to
5156 // build a shadow decl.
5157 if (CurContext->isRecord())
5158 return true;
5159
5160 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005161 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005162 break;
5163 }
5164
5165 Diag(Target->getLocation(), diag::note_using_decl_target);
5166 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5167 return true;
5168 }
5169
5170 // Target is not a function.
5171
John McCall84d87672009-12-10 09:41:52 +00005172 if (isa<TagDecl>(Target)) {
5173 // No conflict between a tag and a non-tag.
5174 if (!Tag) return false;
5175
John McCalle29c5cd2009-12-10 19:51:03 +00005176 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005177 Diag(Target->getLocation(), diag::note_using_decl_target);
5178 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5179 return true;
5180 }
5181
5182 // No conflict between a tag and a non-tag.
5183 if (!NonTag) return false;
5184
John McCalle29c5cd2009-12-10 19:51:03 +00005185 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005186 Diag(Target->getLocation(), diag::note_using_decl_target);
5187 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5188 return true;
5189}
5190
John McCall3f746822009-11-17 05:59:44 +00005191/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005192UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005193 UsingDecl *UD,
5194 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005195
5196 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005197 NamedDecl *Target = Orig;
5198 if (isa<UsingShadowDecl>(Target)) {
5199 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5200 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005201 }
5202
5203 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005204 = UsingShadowDecl::Create(Context, CurContext,
5205 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005206 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005207
5208 Shadow->setAccess(UD->getAccess());
5209 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5210 Shadow->setInvalidDecl();
5211
John McCall3f746822009-11-17 05:59:44 +00005212 if (S)
John McCall3969e302009-12-08 07:46:18 +00005213 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005214 else
John McCall3969e302009-12-08 07:46:18 +00005215 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005216
John McCall3969e302009-12-08 07:46:18 +00005217
John McCall84d87672009-12-10 09:41:52 +00005218 return Shadow;
5219}
John McCall3969e302009-12-08 07:46:18 +00005220
John McCall84d87672009-12-10 09:41:52 +00005221/// Hides a using shadow declaration. This is required by the current
5222/// using-decl implementation when a resolvable using declaration in a
5223/// class is followed by a declaration which would hide or override
5224/// one or more of the using decl's targets; for example:
5225///
5226/// struct Base { void foo(int); };
5227/// struct Derived : Base {
5228/// using Base::foo;
5229/// void foo(int);
5230/// };
5231///
5232/// The governing language is C++03 [namespace.udecl]p12:
5233///
5234/// When a using-declaration brings names from a base class into a
5235/// derived class scope, member functions in the derived class
5236/// override and/or hide member functions with the same name and
5237/// parameter types in a base class (rather than conflicting).
5238///
5239/// There are two ways to implement this:
5240/// (1) optimistically create shadow decls when they're not hidden
5241/// by existing declarations, or
5242/// (2) don't create any shadow decls (or at least don't make them
5243/// visible) until we've fully parsed/instantiated the class.
5244/// The problem with (1) is that we might have to retroactively remove
5245/// a shadow decl, which requires several O(n) operations because the
5246/// decl structures are (very reasonably) not designed for removal.
5247/// (2) avoids this but is very fiddly and phase-dependent.
5248void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005249 if (Shadow->getDeclName().getNameKind() ==
5250 DeclarationName::CXXConversionFunctionName)
5251 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5252
John McCall84d87672009-12-10 09:41:52 +00005253 // Remove it from the DeclContext...
5254 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005255
John McCall84d87672009-12-10 09:41:52 +00005256 // ...and the scope, if applicable...
5257 if (S) {
John McCall48871652010-08-21 09:40:31 +00005258 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005259 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005260 }
5261
John McCall84d87672009-12-10 09:41:52 +00005262 // ...and the using decl.
5263 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5264
5265 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005266 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005267}
5268
John McCalle61f2ba2009-11-18 02:36:19 +00005269/// Builds a using declaration.
5270///
5271/// \param IsInstantiation - Whether this call arises from an
5272/// instantiation of an unresolved using declaration. We treat
5273/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005274NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5275 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005276 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005277 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005278 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005279 bool IsInstantiation,
5280 bool IsTypeName,
5281 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005282 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005283 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005284 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005285
Anders Carlssonf038fc22009-08-28 05:49:21 +00005286 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005287
Anders Carlsson59140b32009-08-28 03:16:11 +00005288 if (SS.isEmpty()) {
5289 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005290 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
John McCall84d87672009-12-10 09:41:52 +00005293 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005294 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005295 ForRedeclaration);
5296 Previous.setHideTags(false);
5297 if (S) {
5298 LookupName(Previous, S);
5299
5300 // It is really dumb that we have to do this.
5301 LookupResult::Filter F = Previous.makeFilter();
5302 while (F.hasNext()) {
5303 NamedDecl *D = F.next();
5304 if (!isDeclInScope(D, CurContext, S))
5305 F.erase();
5306 }
5307 F.done();
5308 } else {
5309 assert(IsInstantiation && "no scope in non-instantiation");
5310 assert(CurContext->isRecord() && "scope not record in instantiation");
5311 LookupQualifiedName(Previous, CurContext);
5312 }
5313
John McCall84d87672009-12-10 09:41:52 +00005314 // Check for invalid redeclarations.
5315 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5316 return 0;
5317
5318 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005319 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5320 return 0;
5321
John McCall84c16cf2009-11-12 03:15:40 +00005322 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005323 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005324 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005325 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005326 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005327 // FIXME: not all declaration name kinds are legal here
5328 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5329 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005330 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005331 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005332 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005333 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5334 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005335 }
John McCallb96ec562009-12-04 22:46:56 +00005336 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005337 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5338 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005339 }
John McCallb96ec562009-12-04 22:46:56 +00005340 D->setAccess(AS);
5341 CurContext->addDecl(D);
5342
5343 if (!LookupContext) return D;
5344 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005345
John McCall0b66eb32010-05-01 00:40:08 +00005346 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005347 UD->setInvalidDecl();
5348 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005349 }
5350
Sebastian Redl08905022011-02-05 19:23:19 +00005351 // Constructor inheriting using decls get special treatment.
5352 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005353 if (CheckInheritedConstructorUsingDecl(UD))
5354 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005355 return UD;
5356 }
5357
5358 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005359
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005360 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetefb1af92011-05-23 03:43:44 +00005361 R.setUsingDeclaration(true);
John McCalle61f2ba2009-11-18 02:36:19 +00005362
John McCall3969e302009-12-08 07:46:18 +00005363 // Unlike most lookups, we don't always want to hide tag
5364 // declarations: tag names are visible through the using declaration
5365 // even if hidden by ordinary names, *except* in a dependent context
5366 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005367 if (!IsInstantiation)
5368 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005369
John McCall27b18f82009-11-17 02:14:36 +00005370 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005371
John McCall9f3059a2009-10-09 21:13:30 +00005372 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005373 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005374 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005375 UD->setInvalidDecl();
5376 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005377 }
5378
John McCallb96ec562009-12-04 22:46:56 +00005379 if (R.isAmbiguous()) {
5380 UD->setInvalidDecl();
5381 return UD;
5382 }
Mike Stump11289f42009-09-09 15:08:12 +00005383
John McCalle61f2ba2009-11-18 02:36:19 +00005384 if (IsTypeName) {
5385 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005386 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005387 Diag(IdentLoc, diag::err_using_typename_non_type);
5388 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5389 Diag((*I)->getUnderlyingDecl()->getLocation(),
5390 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005391 UD->setInvalidDecl();
5392 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005393 }
5394 } else {
5395 // If we asked for a non-typename and we got a type, error out,
5396 // but only if this is an instantiation of an unresolved using
5397 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005398 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005399 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5400 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005401 UD->setInvalidDecl();
5402 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005403 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005404 }
5405
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005406 // C++0x N2914 [namespace.udecl]p6:
5407 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005408 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005409 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5410 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005411 UD->setInvalidDecl();
5412 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005413 }
Mike Stump11289f42009-09-09 15:08:12 +00005414
John McCall84d87672009-12-10 09:41:52 +00005415 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5416 if (!CheckUsingShadowDecl(UD, *I, Previous))
5417 BuildUsingShadowDecl(S, UD, *I);
5418 }
John McCall3f746822009-11-17 05:59:44 +00005419
5420 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005421}
5422
Sebastian Redl08905022011-02-05 19:23:19 +00005423/// Additional checks for a using declaration referring to a constructor name.
5424bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5425 if (UD->isTypeName()) {
5426 // FIXME: Cannot specify typename when specifying constructor
5427 return true;
5428 }
5429
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005430 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00005431 assert(SourceType &&
5432 "Using decl naming constructor doesn't have type in scope spec.");
5433 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5434
5435 // Check whether the named type is a direct base class.
5436 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5437 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5438 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5439 BaseIt != BaseE; ++BaseIt) {
5440 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5441 if (CanonicalSourceType == BaseType)
5442 break;
5443 }
5444
5445 if (BaseIt == BaseE) {
5446 // Did not find SourceType in the bases.
5447 Diag(UD->getUsingLocation(),
5448 diag::err_using_decl_constructor_not_in_direct_base)
5449 << UD->getNameInfo().getSourceRange()
5450 << QualType(SourceType, 0) << TargetClass;
5451 return true;
5452 }
5453
5454 BaseIt->setInheritConstructors();
5455
5456 return false;
5457}
5458
John McCall84d87672009-12-10 09:41:52 +00005459/// Checks that the given using declaration is not an invalid
5460/// redeclaration. Note that this is checking only for the using decl
5461/// itself, not for any ill-formedness among the UsingShadowDecls.
5462bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5463 bool isTypeName,
5464 const CXXScopeSpec &SS,
5465 SourceLocation NameLoc,
5466 const LookupResult &Prev) {
5467 // C++03 [namespace.udecl]p8:
5468 // C++0x [namespace.udecl]p10:
5469 // A using-declaration is a declaration and can therefore be used
5470 // repeatedly where (and only where) multiple declarations are
5471 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00005472 //
John McCall032092f2010-11-29 18:01:58 +00005473 // That's in non-member contexts.
5474 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00005475 return false;
5476
5477 NestedNameSpecifier *Qual
5478 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5479
5480 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5481 NamedDecl *D = *I;
5482
5483 bool DTypename;
5484 NestedNameSpecifier *DQual;
5485 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5486 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005487 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005488 } else if (UnresolvedUsingValueDecl *UD
5489 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5490 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005491 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005492 } else if (UnresolvedUsingTypenameDecl *UD
5493 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5494 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005495 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005496 } else continue;
5497
5498 // using decls differ if one says 'typename' and the other doesn't.
5499 // FIXME: non-dependent using decls?
5500 if (isTypeName != DTypename) continue;
5501
5502 // using decls differ if they name different scopes (but note that
5503 // template instantiation can cause this check to trigger when it
5504 // didn't before instantiation).
5505 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5506 Context.getCanonicalNestedNameSpecifier(DQual))
5507 continue;
5508
5509 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00005510 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00005511 return true;
5512 }
5513
5514 return false;
5515}
5516
John McCall3969e302009-12-08 07:46:18 +00005517
John McCallb96ec562009-12-04 22:46:56 +00005518/// Checks that the given nested-name qualifier used in a using decl
5519/// in the current context is appropriately related to the current
5520/// scope. If an error is found, diagnoses it and returns true.
5521bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5522 const CXXScopeSpec &SS,
5523 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00005524 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005525
John McCall3969e302009-12-08 07:46:18 +00005526 if (!CurContext->isRecord()) {
5527 // C++03 [namespace.udecl]p3:
5528 // C++0x [namespace.udecl]p8:
5529 // A using-declaration for a class member shall be a member-declaration.
5530
5531 // If we weren't able to compute a valid scope, it must be a
5532 // dependent class scope.
5533 if (!NamedContext || NamedContext->isRecord()) {
5534 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5535 << SS.getRange();
5536 return true;
5537 }
5538
5539 // Otherwise, everything is known to be fine.
5540 return false;
5541 }
5542
5543 // The current scope is a record.
5544
5545 // If the named context is dependent, we can't decide much.
5546 if (!NamedContext) {
5547 // FIXME: in C++0x, we can diagnose if we can prove that the
5548 // nested-name-specifier does not refer to a base class, which is
5549 // still possible in some cases.
5550
5551 // Otherwise we have to conservatively report that things might be
5552 // okay.
5553 return false;
5554 }
5555
5556 if (!NamedContext->isRecord()) {
5557 // Ideally this would point at the last name in the specifier,
5558 // but we don't have that level of source info.
5559 Diag(SS.getRange().getBegin(),
5560 diag::err_using_decl_nested_name_specifier_is_not_class)
5561 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5562 return true;
5563 }
5564
Douglas Gregor7c842292010-12-21 07:41:49 +00005565 if (!NamedContext->isDependentContext() &&
5566 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5567 return true;
5568
John McCall3969e302009-12-08 07:46:18 +00005569 if (getLangOptions().CPlusPlus0x) {
5570 // C++0x [namespace.udecl]p3:
5571 // In a using-declaration used as a member-declaration, the
5572 // nested-name-specifier shall name a base class of the class
5573 // being defined.
5574
5575 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5576 cast<CXXRecordDecl>(NamedContext))) {
5577 if (CurContext == NamedContext) {
5578 Diag(NameLoc,
5579 diag::err_using_decl_nested_name_specifier_is_current_class)
5580 << SS.getRange();
5581 return true;
5582 }
5583
5584 Diag(SS.getRange().getBegin(),
5585 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5586 << (NestedNameSpecifier*) SS.getScopeRep()
5587 << cast<CXXRecordDecl>(CurContext)
5588 << SS.getRange();
5589 return true;
5590 }
5591
5592 return false;
5593 }
5594
5595 // C++03 [namespace.udecl]p4:
5596 // A using-declaration used as a member-declaration shall refer
5597 // to a member of a base class of the class being defined [etc.].
5598
5599 // Salient point: SS doesn't have to name a base class as long as
5600 // lookup only finds members from base classes. Therefore we can
5601 // diagnose here only if we can prove that that can't happen,
5602 // i.e. if the class hierarchies provably don't intersect.
5603
5604 // TODO: it would be nice if "definitely valid" results were cached
5605 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5606 // need to be repeated.
5607
5608 struct UserData {
5609 llvm::DenseSet<const CXXRecordDecl*> Bases;
5610
5611 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5612 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5613 Data->Bases.insert(Base);
5614 return true;
5615 }
5616
5617 bool hasDependentBases(const CXXRecordDecl *Class) {
5618 return !Class->forallBases(collect, this);
5619 }
5620
5621 /// Returns true if the base is dependent or is one of the
5622 /// accumulated base classes.
5623 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5624 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5625 return !Data->Bases.count(Base);
5626 }
5627
5628 bool mightShareBases(const CXXRecordDecl *Class) {
5629 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5630 }
5631 };
5632
5633 UserData Data;
5634
5635 // Returns false if we find a dependent base.
5636 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5637 return false;
5638
5639 // Returns false if the class has a dependent base or if it or one
5640 // of its bases is present in the base set of the current context.
5641 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5642 return false;
5643
5644 Diag(SS.getRange().getBegin(),
5645 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5646 << (NestedNameSpecifier*) SS.getScopeRep()
5647 << cast<CXXRecordDecl>(CurContext)
5648 << SS.getRange();
5649
5650 return true;
John McCallb96ec562009-12-04 22:46:56 +00005651}
5652
Richard Smithdda56e42011-04-15 14:24:37 +00005653Decl *Sema::ActOnAliasDeclaration(Scope *S,
5654 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005655 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00005656 SourceLocation UsingLoc,
5657 UnqualifiedId &Name,
5658 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00005659 // Skip up to the relevant declaration scope.
5660 while (S->getFlags() & Scope::TemplateParamScope)
5661 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00005662 assert((S->getFlags() & Scope::DeclScope) &&
5663 "got alias-declaration outside of declaration scope");
5664
5665 if (Type.isInvalid())
5666 return 0;
5667
5668 bool Invalid = false;
5669 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5670 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00005671 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00005672
5673 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5674 return 0;
5675
5676 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005677 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00005678 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005679 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5680 TInfo->getTypeLoc().getBeginLoc());
5681 }
Richard Smithdda56e42011-04-15 14:24:37 +00005682
5683 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5684 LookupName(Previous, S);
5685
5686 // Warn about shadowing the name of a template parameter.
5687 if (Previous.isSingleResult() &&
5688 Previous.getFoundDecl()->isTemplateParameter()) {
5689 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5690 Previous.getFoundDecl()))
5691 Invalid = true;
5692 Previous.clear();
5693 }
5694
5695 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5696 "name in alias declaration must be an identifier");
5697 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5698 Name.StartLocation,
5699 Name.Identifier, TInfo);
5700
5701 NewTD->setAccess(AS);
5702
5703 if (Invalid)
5704 NewTD->setInvalidDecl();
5705
Richard Smith3f1b5d02011-05-05 21:57:07 +00005706 CheckTypedefForVariablyModifiedType(S, NewTD);
5707 Invalid |= NewTD->isInvalidDecl();
5708
Richard Smithdda56e42011-04-15 14:24:37 +00005709 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005710
5711 NamedDecl *NewND;
5712 if (TemplateParamLists.size()) {
5713 TypeAliasTemplateDecl *OldDecl = 0;
5714 TemplateParameterList *OldTemplateParams = 0;
5715
5716 if (TemplateParamLists.size() != 1) {
5717 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5718 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5719 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5720 }
5721 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5722
5723 // Only consider previous declarations in the same scope.
5724 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5725 /*ExplicitInstantiationOrSpecialization*/false);
5726 if (!Previous.empty()) {
5727 Redeclaration = true;
5728
5729 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5730 if (!OldDecl && !Invalid) {
5731 Diag(UsingLoc, diag::err_redefinition_different_kind)
5732 << Name.Identifier;
5733
5734 NamedDecl *OldD = Previous.getRepresentativeDecl();
5735 if (OldD->getLocation().isValid())
5736 Diag(OldD->getLocation(), diag::note_previous_definition);
5737
5738 Invalid = true;
5739 }
5740
5741 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5742 if (TemplateParameterListsAreEqual(TemplateParams,
5743 OldDecl->getTemplateParameters(),
5744 /*Complain=*/true,
5745 TPL_TemplateMatch))
5746 OldTemplateParams = OldDecl->getTemplateParameters();
5747 else
5748 Invalid = true;
5749
5750 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5751 if (!Invalid &&
5752 !Context.hasSameType(OldTD->getUnderlyingType(),
5753 NewTD->getUnderlyingType())) {
5754 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5755 // but we can't reasonably accept it.
5756 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5757 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5758 if (OldTD->getLocation().isValid())
5759 Diag(OldTD->getLocation(), diag::note_previous_definition);
5760 Invalid = true;
5761 }
5762 }
5763 }
5764
5765 // Merge any previous default template arguments into our parameters,
5766 // and check the parameter list.
5767 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5768 TPC_TypeAliasTemplate))
5769 return 0;
5770
5771 TypeAliasTemplateDecl *NewDecl =
5772 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5773 Name.Identifier, TemplateParams,
5774 NewTD);
5775
5776 NewDecl->setAccess(AS);
5777
5778 if (Invalid)
5779 NewDecl->setInvalidDecl();
5780 else if (OldDecl)
5781 NewDecl->setPreviousDeclaration(OldDecl);
5782
5783 NewND = NewDecl;
5784 } else {
5785 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5786 NewND = NewTD;
5787 }
Richard Smithdda56e42011-04-15 14:24:37 +00005788
5789 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00005790 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00005791
Richard Smith3f1b5d02011-05-05 21:57:07 +00005792 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00005793}
5794
John McCall48871652010-08-21 09:40:31 +00005795Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005796 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005797 SourceLocation AliasLoc,
5798 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005799 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005800 SourceLocation IdentLoc,
5801 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00005802
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005803 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005804 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5805 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005806
Anders Carlssondca83c42009-03-28 06:23:46 +00005807 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00005808 NamedDecl *PrevDecl
5809 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5810 ForRedeclaration);
5811 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5812 PrevDecl = 0;
5813
5814 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005815 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00005816 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005817 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00005818 // FIXME: At some point, we'll want to create the (redundant)
5819 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00005820 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00005821 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00005822 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005823 }
Mike Stump11289f42009-09-09 15:08:12 +00005824
Anders Carlssondca83c42009-03-28 06:23:46 +00005825 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5826 diag::err_redefinition_different_kind;
5827 Diag(AliasLoc, DiagID) << Alias;
5828 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00005829 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00005830 }
5831
John McCall27b18f82009-11-17 02:14:36 +00005832 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005833 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005834
John McCall9f3059a2009-10-09 21:13:30 +00005835 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005836 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5837 CTC_NoKeywords, 0)) {
5838 if (R.getAsSingle<NamespaceDecl>() ||
5839 R.getAsSingle<NamespaceAliasDecl>()) {
5840 if (DeclContext *DC = computeDeclContext(SS, false))
5841 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5842 << Ident << DC << Corrected << SS.getRange()
5843 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5844 else
5845 Diag(IdentLoc, diag::err_using_directive_suggest)
5846 << Ident << Corrected
5847 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5848
5849 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5850 << Corrected;
5851
5852 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00005853 } else {
5854 R.clear();
5855 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005856 }
5857 }
5858
5859 if (R.empty()) {
5860 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005861 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005862 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00005863 }
Mike Stump11289f42009-09-09 15:08:12 +00005864
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005865 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00005866 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00005867 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00005868 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00005869
John McCalld8d0d432010-02-16 06:53:13 +00005870 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00005871 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00005872}
5873
Douglas Gregora57478e2010-05-01 15:04:51 +00005874namespace {
5875 /// \brief Scoped object used to handle the state changes required in Sema
5876 /// to implicitly define the body of a C++ member function;
5877 class ImplicitlyDefinedFunctionScope {
5878 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00005879 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00005880
5881 public:
5882 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00005883 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00005884 {
Douglas Gregora57478e2010-05-01 15:04:51 +00005885 S.PushFunctionScope();
5886 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5887 }
5888
5889 ~ImplicitlyDefinedFunctionScope() {
5890 S.PopExpressionEvaluationContext();
5891 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00005892 }
5893 };
5894}
5895
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005896Sema::ImplicitExceptionSpecification
5897Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00005898 // C++ [except.spec]p14:
5899 // An implicitly declared special member function (Clause 12) shall have an
5900 // exception-specification. [...]
5901 ImplicitExceptionSpecification ExceptSpec(Context);
5902
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005903 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005904 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5905 BEnd = ClassDecl->bases_end();
5906 B != BEnd; ++B) {
5907 if (B->isVirtual()) // Handled below.
5908 continue;
5909
Douglas Gregor9672f922010-07-03 00:47:00 +00005910 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5911 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005912 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5913 // If this is a deleted function, add it anyway. This might be conformant
5914 // with the standard. This might not. I'm not sure. It might not matter.
5915 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005916 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005917 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005918 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005919
5920 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005921 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5922 BEnd = ClassDecl->vbases_end();
5923 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00005924 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5925 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005926 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5927 // If this is a deleted function, add it anyway. This might be conformant
5928 // with the standard. This might not. I'm not sure. It might not matter.
5929 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005930 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005931 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005932 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005933
5934 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005935 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5936 FEnd = ClassDecl->field_end();
5937 F != FEnd; ++F) {
5938 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00005939 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00005940 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5941 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5942 // If this is a deleted function, add it anyway. This might be conformant
5943 // with the standard. This might not. I'm not sure. It might not matter.
5944 // In particular, the problem is that this function never gets called. It
5945 // might just be ill-formed because this function attempts to refer to
5946 // a deleted function here.
5947 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005948 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005949 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005950 }
John McCalldb40c7f2010-12-14 08:05:40 +00005951
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005952 return ExceptSpec;
5953}
5954
5955CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5956 CXXRecordDecl *ClassDecl) {
5957 // C++ [class.ctor]p5:
5958 // A default constructor for a class X is a constructor of class X
5959 // that can be called without an argument. If there is no
5960 // user-declared constructor for class X, a default constructor is
5961 // implicitly declared. An implicitly-declared default constructor
5962 // is an inline public member of its class.
5963 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5964 "Should not build implicit default constructor!");
5965
5966 ImplicitExceptionSpecification Spec =
5967 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5968 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005969
Douglas Gregor6d880b12010-07-01 22:31:05 +00005970 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005971 CanQualType ClassType
5972 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005973 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005974 DeclarationName Name
5975 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005976 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005977 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00005978 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005979 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005980 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005981 /*TInfo=*/0,
5982 /*isExplicit=*/false,
5983 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005984 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005985 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00005986 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005987 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00005988 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00005989
5990 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00005991 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5992
Douglas Gregor0be31a22010-07-02 17:43:08 +00005993 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00005994 PushOnScopeChains(DefaultCon, S, false);
5995 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00005996
5997 if (ShouldDeleteDefaultConstructor(DefaultCon))
5998 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00005999
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006000 return DefaultCon;
6001}
6002
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006003void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6004 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006005 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006006 !Constructor->doesThisDeclarationHaveABody() &&
6007 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006008 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006009
Anders Carlsson423f5d82010-04-23 16:04:08 +00006010 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006011 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006012
Douglas Gregora57478e2010-05-01 15:04:51 +00006013 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006014 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006015 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006016 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006017 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006018 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006019 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006020 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006021 }
Douglas Gregor73193272010-09-20 16:48:21 +00006022
6023 SourceLocation Loc = Constructor->getLocation();
6024 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6025
6026 Constructor->setUsed();
6027 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006028
6029 if (ASTMutationListener *L = getASTMutationListener()) {
6030 L->CompletedImplicitDefinition(Constructor);
6031 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006032}
6033
Sebastian Redl08905022011-02-05 19:23:19 +00006034void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6035 // We start with an initial pass over the base classes to collect those that
6036 // inherit constructors from. If there are none, we can forgo all further
6037 // processing.
6038 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6039 BasesVector BasesToInheritFrom;
6040 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6041 BaseE = ClassDecl->bases_end();
6042 BaseIt != BaseE; ++BaseIt) {
6043 if (BaseIt->getInheritConstructors()) {
6044 QualType Base = BaseIt->getType();
6045 if (Base->isDependentType()) {
6046 // If we inherit constructors from anything that is dependent, just
6047 // abort processing altogether. We'll get another chance for the
6048 // instantiations.
6049 return;
6050 }
6051 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6052 }
6053 }
6054 if (BasesToInheritFrom.empty())
6055 return;
6056
6057 // Now collect the constructors that we already have in the current class.
6058 // Those take precedence over inherited constructors.
6059 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6060 // unless there is a user-declared constructor with the same signature in
6061 // the class where the using-declaration appears.
6062 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6063 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6064 CtorE = ClassDecl->ctor_end();
6065 CtorIt != CtorE; ++CtorIt) {
6066 ExistingConstructors.insert(
6067 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6068 }
6069
6070 Scope *S = getScopeForContext(ClassDecl);
6071 DeclarationName CreatedCtorName =
6072 Context.DeclarationNames.getCXXConstructorName(
6073 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6074
6075 // Now comes the true work.
6076 // First, we keep a map from constructor types to the base that introduced
6077 // them. Needed for finding conflicting constructors. We also keep the
6078 // actually inserted declarations in there, for pretty diagnostics.
6079 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6080 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6081 ConstructorToSourceMap InheritedConstructors;
6082 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6083 BaseE = BasesToInheritFrom.end();
6084 BaseIt != BaseE; ++BaseIt) {
6085 const RecordType *Base = *BaseIt;
6086 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6087 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6088 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6089 CtorE = BaseDecl->ctor_end();
6090 CtorIt != CtorE; ++CtorIt) {
6091 // Find the using declaration for inheriting this base's constructors.
6092 DeclarationName Name =
6093 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6094 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6095 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6096 SourceLocation UsingLoc = UD ? UD->getLocation() :
6097 ClassDecl->getLocation();
6098
6099 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6100 // from the class X named in the using-declaration consists of actual
6101 // constructors and notional constructors that result from the
6102 // transformation of defaulted parameters as follows:
6103 // - all non-template default constructors of X, and
6104 // - for each non-template constructor of X that has at least one
6105 // parameter with a default argument, the set of constructors that
6106 // results from omitting any ellipsis parameter specification and
6107 // successively omitting parameters with a default argument from the
6108 // end of the parameter-type-list.
6109 CXXConstructorDecl *BaseCtor = *CtorIt;
6110 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6111 const FunctionProtoType *BaseCtorType =
6112 BaseCtor->getType()->getAs<FunctionProtoType>();
6113
6114 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6115 maxParams = BaseCtor->getNumParams();
6116 params <= maxParams; ++params) {
6117 // Skip default constructors. They're never inherited.
6118 if (params == 0)
6119 continue;
6120 // Skip copy and move constructors for the same reason.
6121 if (CanBeCopyOrMove && params == 1)
6122 continue;
6123
6124 // Build up a function type for this particular constructor.
6125 // FIXME: The working paper does not consider that the exception spec
6126 // for the inheriting constructor might be larger than that of the
6127 // source. This code doesn't yet, either.
6128 const Type *NewCtorType;
6129 if (params == maxParams)
6130 NewCtorType = BaseCtorType;
6131 else {
6132 llvm::SmallVector<QualType, 16> Args;
6133 for (unsigned i = 0; i < params; ++i) {
6134 Args.push_back(BaseCtorType->getArgType(i));
6135 }
6136 FunctionProtoType::ExtProtoInfo ExtInfo =
6137 BaseCtorType->getExtProtoInfo();
6138 ExtInfo.Variadic = false;
6139 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6140 Args.data(), params, ExtInfo)
6141 .getTypePtr();
6142 }
6143 const Type *CanonicalNewCtorType =
6144 Context.getCanonicalType(NewCtorType);
6145
6146 // Now that we have the type, first check if the class already has a
6147 // constructor with this signature.
6148 if (ExistingConstructors.count(CanonicalNewCtorType))
6149 continue;
6150
6151 // Then we check if we have already declared an inherited constructor
6152 // with this signature.
6153 std::pair<ConstructorToSourceMap::iterator, bool> result =
6154 InheritedConstructors.insert(std::make_pair(
6155 CanonicalNewCtorType,
6156 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6157 if (!result.second) {
6158 // Already in the map. If it came from a different class, that's an
6159 // error. Not if it's from the same.
6160 CanQualType PreviousBase = result.first->second.first;
6161 if (CanonicalBase != PreviousBase) {
6162 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6163 const CXXConstructorDecl *PrevBaseCtor =
6164 PrevCtor->getInheritedConstructor();
6165 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6166
6167 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6168 Diag(BaseCtor->getLocation(),
6169 diag::note_using_decl_constructor_conflict_current_ctor);
6170 Diag(PrevBaseCtor->getLocation(),
6171 diag::note_using_decl_constructor_conflict_previous_ctor);
6172 Diag(PrevCtor->getLocation(),
6173 diag::note_using_decl_constructor_conflict_previous_using);
6174 }
6175 continue;
6176 }
6177
6178 // OK, we're there, now add the constructor.
6179 // C++0x [class.inhctor]p8: [...] that would be performed by a
6180 // user-writtern inline constructor [...]
6181 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6182 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006183 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6184 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006185 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00006186 NewCtor->setAccess(BaseCtor->getAccess());
6187
6188 // Build up the parameter decls and add them.
6189 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6190 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006191 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6192 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006193 /*IdentifierInfo=*/0,
6194 BaseCtorType->getArgType(i),
6195 /*TInfo=*/0, SC_None,
6196 SC_None, /*DefaultArg=*/0));
6197 }
6198 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6199 NewCtor->setInheritedConstructor(BaseCtor);
6200
6201 PushOnScopeChains(NewCtor, S, false);
6202 ClassDecl->addDecl(NewCtor);
6203 result.first->second.second = NewCtor;
6204 }
6205 }
6206 }
6207}
6208
Alexis Huntf91729462011-05-12 22:46:25 +00006209Sema::ImplicitExceptionSpecification
6210Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006211 // C++ [except.spec]p14:
6212 // An implicitly declared special member function (Clause 12) shall have
6213 // an exception-specification.
6214 ImplicitExceptionSpecification ExceptSpec(Context);
6215
6216 // Direct base-class destructors.
6217 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6218 BEnd = ClassDecl->bases_end();
6219 B != BEnd; ++B) {
6220 if (B->isVirtual()) // Handled below.
6221 continue;
6222
6223 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6224 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006225 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006226 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006227
Douglas Gregorf1203042010-07-01 19:09:28 +00006228 // Virtual base-class destructors.
6229 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6230 BEnd = ClassDecl->vbases_end();
6231 B != BEnd; ++B) {
6232 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6233 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006234 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006235 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006236
Douglas Gregorf1203042010-07-01 19:09:28 +00006237 // Field destructors.
6238 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6239 FEnd = ClassDecl->field_end();
6240 F != FEnd; ++F) {
6241 if (const RecordType *RecordTy
6242 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6243 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006244 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006245 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006246
Alexis Huntf91729462011-05-12 22:46:25 +00006247 return ExceptSpec;
6248}
6249
6250CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6251 // C++ [class.dtor]p2:
6252 // If a class has no user-declared destructor, a destructor is
6253 // declared implicitly. An implicitly-declared destructor is an
6254 // inline public member of its class.
6255
6256 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006257 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006258 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6259
Douglas Gregor7454c562010-07-02 20:37:36 +00006260 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006261 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006262
Douglas Gregorf1203042010-07-01 19:09:28 +00006263 CanQualType ClassType
6264 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006265 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006266 DeclarationName Name
6267 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006268 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006269 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006270 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6271 /*isInline=*/true,
6272 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006273 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006274 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006275 Destructor->setImplicit();
6276 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006277
6278 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006279 ++ASTContext::NumImplicitDestructorsDeclared;
6280
6281 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006282 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006283 PushOnScopeChains(Destructor, S, false);
6284 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006285
6286 // This could be uniqued if it ever proves significant.
6287 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006288
6289 if (ShouldDeleteDestructor(Destructor))
6290 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006291
6292 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006293
Douglas Gregorf1203042010-07-01 19:09:28 +00006294 return Destructor;
6295}
6296
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006297void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006298 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006299 assert((Destructor->isDefaulted() &&
6300 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006301 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006302 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006303 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006304
Douglas Gregor54818f02010-05-12 16:39:35 +00006305 if (Destructor->isInvalidDecl())
6306 return;
6307
Douglas Gregora57478e2010-05-01 15:04:51 +00006308 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006309
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006310 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006311 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6312 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006313
Douglas Gregor54818f02010-05-12 16:39:35 +00006314 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006315 Diag(CurrentLocation, diag::note_member_synthesized_at)
6316 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6317
6318 Destructor->setInvalidDecl();
6319 return;
6320 }
6321
Douglas Gregor73193272010-09-20 16:48:21 +00006322 SourceLocation Loc = Destructor->getLocation();
6323 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6324
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006325 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006326 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006327
6328 if (ASTMutationListener *L = getASTMutationListener()) {
6329 L->CompletedImplicitDefinition(Destructor);
6330 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006331}
6332
Sebastian Redl623ea822011-05-19 05:13:44 +00006333void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6334 CXXDestructorDecl *destructor) {
6335 // C++11 [class.dtor]p3:
6336 // A declaration of a destructor that does not have an exception-
6337 // specification is implicitly considered to have the same exception-
6338 // specification as an implicit declaration.
6339 const FunctionProtoType *dtorType = destructor->getType()->
6340 getAs<FunctionProtoType>();
6341 if (dtorType->hasExceptionSpec())
6342 return;
6343
6344 ImplicitExceptionSpecification exceptSpec =
6345 ComputeDefaultedDtorExceptionSpec(classDecl);
6346
6347 // Replace the destructor's type.
6348 FunctionProtoType::ExtProtoInfo epi;
6349 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6350 epi.NumExceptions = exceptSpec.size();
6351 epi.Exceptions = exceptSpec.data();
6352 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6353
6354 destructor->setType(ty);
6355
6356 // FIXME: If the destructor has a body that could throw, and the newly created
6357 // spec doesn't allow exceptions, we should emit a warning, because this
6358 // change in behavior can break conforming C++03 programs at runtime.
6359 // However, we don't have a body yet, so it needs to be done somewhere else.
6360}
6361
Douglas Gregorb139cd52010-05-01 20:49:11 +00006362/// \brief Builds a statement that copies the given entity from \p From to
6363/// \c To.
6364///
6365/// This routine is used to copy the members of a class with an
6366/// implicitly-declared copy assignment operator. When the entities being
6367/// copied are arrays, this routine builds for loops to copy them.
6368///
6369/// \param S The Sema object used for type-checking.
6370///
6371/// \param Loc The location where the implicit copy is being generated.
6372///
6373/// \param T The type of the expressions being copied. Both expressions must
6374/// have this type.
6375///
6376/// \param To The expression we are copying to.
6377///
6378/// \param From The expression we are copying from.
6379///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006380/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6381/// Otherwise, it's a non-static member subobject.
6382///
Douglas Gregorb139cd52010-05-01 20:49:11 +00006383/// \param Depth Internal parameter recording the depth of the recursion.
6384///
6385/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00006386static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00006387BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00006388 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006389 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006390 // C++0x [class.copy]p30:
6391 // Each subobject is assigned in the manner appropriate to its type:
6392 //
6393 // - if the subobject is of class type, the copy assignment operator
6394 // for the class is used (as if by explicit qualification; that is,
6395 // ignoring any possible virtual overriding functions in more derived
6396 // classes);
6397 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6398 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6399
6400 // Look for operator=.
6401 DeclarationName Name
6402 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6403 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6404 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6405
6406 // Filter out any result that isn't a copy-assignment operator.
6407 LookupResult::Filter F = OpLookup.makeFilter();
6408 while (F.hasNext()) {
6409 NamedDecl *D = F.next();
6410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6411 if (Method->isCopyAssignmentOperator())
6412 continue;
6413
6414 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00006415 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006416 F.done();
6417
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006418 // Suppress the protected check (C++ [class.protected]) for each of the
6419 // assignment operators we found. This strange dance is required when
6420 // we're assigning via a base classes's copy-assignment operator. To
6421 // ensure that we're getting the right base class subobject (without
6422 // ambiguities), we need to cast "this" to that subobject type; to
6423 // ensure that we don't go through the virtual call mechanism, we need
6424 // to qualify the operator= name with the base class (see below). However,
6425 // this means that if the base class has a protected copy assignment
6426 // operator, the protected member access check will fail. So, we
6427 // rewrite "protected" access to "public" access in this case, since we
6428 // know by construction that we're calling from a derived class.
6429 if (CopyingBaseSubobject) {
6430 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6431 L != LEnd; ++L) {
6432 if (L.getAccess() == AS_protected)
6433 L.setAccess(AS_public);
6434 }
6435 }
6436
Douglas Gregorb139cd52010-05-01 20:49:11 +00006437 // Create the nested-name-specifier that will be used to qualify the
6438 // reference to operator=; this is required to suppress the virtual
6439 // call mechanism.
6440 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006441 SS.MakeTrivial(S.Context,
6442 NestedNameSpecifier::Create(S.Context, 0, false,
6443 T.getTypePtr()),
6444 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006445
6446 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00006447 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00006448 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006449 /*FirstQualifierInScope=*/0, OpLookup,
6450 /*TemplateArgs=*/0,
6451 /*SuppressQualifierCheck=*/true);
6452 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006453 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006454
6455 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00006456
John McCalldadc5752010-08-24 06:29:42 +00006457 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006458 OpEqualRef.takeAs<Expr>(),
6459 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006460 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006461 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006462
6463 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006464 }
John McCallab8c2732010-03-16 06:11:48 +00006465
Douglas Gregorb139cd52010-05-01 20:49:11 +00006466 // - if the subobject is of scalar type, the built-in assignment
6467 // operator is used.
6468 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6469 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00006470 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006471 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006472 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006473
6474 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006475 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006476
6477 // - if the subobject is an array, each element is assigned, in the
6478 // manner appropriate to the element type;
6479
6480 // Construct a loop over the array bounds, e.g.,
6481 //
6482 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6483 //
6484 // that will copy each of the array elements.
6485 QualType SizeType = S.Context.getSizeType();
6486
6487 // Create the iteration variable.
6488 IdentifierInfo *IterationVarName = 0;
6489 {
6490 llvm::SmallString<8> Str;
6491 llvm::raw_svector_ostream OS(Str);
6492 OS << "__i" << Depth;
6493 IterationVarName = &S.Context.Idents.get(OS.str());
6494 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00006495 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006496 IterationVarName, SizeType,
6497 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006498 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006499
6500 // Initialize the iteration variable to zero.
6501 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006502 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006503
6504 // Create a reference to the iteration variable; we'll use this several
6505 // times throughout.
6506 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00006507 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006508 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6509
6510 // Create the DeclStmt that holds the iteration variable.
6511 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6512
6513 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006514 llvm::APInt Upper
6515 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00006516 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00006517 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00006518 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6519 BO_NE, S.Context.BoolTy,
6520 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006521
6522 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006523 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00006524 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6525 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006526
6527 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006528 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6529 IterationVarRef, Loc));
6530 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6531 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006532
6533 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00006534 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6535 To, From, CopyingBaseSubobject,
6536 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00006537 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006538 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006539
6540 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00006541 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006542 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00006543 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00006544 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006545}
6546
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006547/// \brief Determine whether the given class has a copy assignment operator
6548/// that accepts a const-qualified argument.
6549static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6550 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6551
6552 if (!Class->hasDeclaredCopyAssignment())
6553 S.DeclareImplicitCopyAssignment(Class);
6554
6555 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6556 DeclarationName OpName
6557 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6558
6559 DeclContext::lookup_const_iterator Op, OpEnd;
6560 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6561 // C++ [class.copy]p9:
6562 // A user-declared copy assignment operator is a non-static non-template
6563 // member function of class X with exactly one parameter of type X, X&,
6564 // const X&, volatile X& or const volatile X&.
6565 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6566 if (!Method)
6567 continue;
6568
6569 if (Method->isStatic())
6570 continue;
6571 if (Method->getPrimaryTemplate())
6572 continue;
6573 const FunctionProtoType *FnType =
6574 Method->getType()->getAs<FunctionProtoType>();
6575 assert(FnType && "Overloaded operator has no prototype.");
6576 // Don't assert on this; an invalid decl might have been left in the AST.
6577 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6578 continue;
6579 bool AcceptsConst = true;
6580 QualType ArgType = FnType->getArgType(0);
6581 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6582 ArgType = Ref->getPointeeType();
6583 // Is it a non-const lvalue reference?
6584 if (!ArgType.isConstQualified())
6585 AcceptsConst = false;
6586 }
6587 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6588 continue;
6589
6590 // We have a single argument of type cv X or cv X&, i.e. we've found the
6591 // copy assignment operator. Return whether it accepts const arguments.
6592 return AcceptsConst;
6593 }
6594 assert(Class->isInvalidDecl() &&
6595 "No copy assignment operator declared in valid code.");
6596 return false;
6597}
6598
Alexis Hunt119f3652011-05-14 05:23:20 +00006599std::pair<Sema::ImplicitExceptionSpecification, bool>
6600Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6601 CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006602 // C++ [class.copy]p10:
6603 // If the class definition does not explicitly declare a copy
6604 // assignment operator, one is declared implicitly.
6605 // The implicitly-defined copy assignment operator for a class X
6606 // will have the form
6607 //
6608 // X& X::operator=(const X&)
6609 //
6610 // if
6611 bool HasConstCopyAssignment = true;
6612
6613 // -- each direct base class B of X has a copy assignment operator
6614 // whose parameter is of type const B&, const volatile B& or B,
6615 // and
6616 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6617 BaseEnd = ClassDecl->bases_end();
6618 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6619 assert(!Base->getType()->isDependentType() &&
6620 "Cannot generate implicit members for class with dependent bases.");
6621 const CXXRecordDecl *BaseClassDecl
6622 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006623 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006624 }
6625
6626 // -- for all the nonstatic data members of X that are of a class
6627 // type M (or array thereof), each such class type has a copy
6628 // assignment operator whose parameter is of type const M&,
6629 // const volatile M& or M.
6630 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6631 FieldEnd = ClassDecl->field_end();
6632 HasConstCopyAssignment && Field != FieldEnd;
6633 ++Field) {
6634 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6635 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6636 const CXXRecordDecl *FieldClassDecl
6637 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006638 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006639 }
6640 }
6641
6642 // Otherwise, the implicitly declared copy assignment operator will
6643 // have the form
6644 //
6645 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006646
Douglas Gregor68e11362010-07-01 17:48:08 +00006647 // C++ [except.spec]p14:
6648 // An implicitly declared special member function (Clause 12) shall have an
6649 // exception-specification. [...]
6650 ImplicitExceptionSpecification ExceptSpec(Context);
6651 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6652 BaseEnd = ClassDecl->bases_end();
6653 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006654 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006655 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006656
6657 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6658 DeclareImplicitCopyAssignment(BaseClassDecl);
6659
Douglas Gregor68e11362010-07-01 17:48:08 +00006660 if (CXXMethodDecl *CopyAssign
6661 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6662 ExceptSpec.CalledDecl(CopyAssign);
6663 }
6664 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6665 FieldEnd = ClassDecl->field_end();
6666 Field != FieldEnd;
6667 ++Field) {
6668 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6669 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006670 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006671 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006672
6673 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6674 DeclareImplicitCopyAssignment(FieldClassDecl);
6675
Douglas Gregor68e11362010-07-01 17:48:08 +00006676 if (CXXMethodDecl *CopyAssign
6677 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6678 ExceptSpec.CalledDecl(CopyAssign);
6679 }
6680 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006681
Alexis Hunt119f3652011-05-14 05:23:20 +00006682 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6683}
6684
6685CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6686 // Note: The following rules are largely analoguous to the copy
6687 // constructor rules. Note that virtual bases are not taken into account
6688 // for determining the argument type of the operator. Note also that
6689 // operators taking an object instead of a reference are allowed.
6690
6691 ImplicitExceptionSpecification Spec(Context);
6692 bool Const;
6693 llvm::tie(Spec, Const) =
6694 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6695
6696 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6697 QualType RetType = Context.getLValueReferenceType(ArgType);
6698 if (Const)
6699 ArgType = ArgType.withConst();
6700 ArgType = Context.getLValueReferenceType(ArgType);
6701
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006702 // An implicitly-declared copy assignment operator is an inline public
6703 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00006704 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006705 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006706 SourceLocation ClassLoc = ClassDecl->getLocation();
6707 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006708 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00006709 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00006710 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006711 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00006712 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00006713 /*isInline=*/true,
6714 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006715 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00006716 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006717 CopyAssignment->setImplicit();
6718 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006719
6720 // Add the parameter to the operator.
6721 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006722 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006723 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006724 SC_None,
6725 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006726 CopyAssignment->setParams(&FromParam, 1);
6727
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006728 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006729 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00006730
Douglas Gregor0be31a22010-07-02 17:43:08 +00006731 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006732 PushOnScopeChains(CopyAssignment, S, false);
6733 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006734
Alexis Hunte77a28f2011-05-18 03:41:58 +00006735 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6736 CopyAssignment->setDeletedAsWritten();
6737
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006738 AddOverriddenMethods(ClassDecl, CopyAssignment);
6739 return CopyAssignment;
6740}
6741
Douglas Gregorb139cd52010-05-01 20:49:11 +00006742void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6743 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00006744 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006745 CopyAssignOperator->isOverloadedOperator() &&
6746 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006747 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006748 "DefineImplicitCopyAssignment called for wrong function");
6749
6750 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6751
6752 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6753 CopyAssignOperator->setInvalidDecl();
6754 return;
6755 }
6756
6757 CopyAssignOperator->setUsed();
6758
6759 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006760 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006761
6762 // C++0x [class.copy]p30:
6763 // The implicitly-defined or explicitly-defaulted copy assignment operator
6764 // for a non-union class X performs memberwise copy assignment of its
6765 // subobjects. The direct base classes of X are assigned first, in the
6766 // order of their declaration in the base-specifier-list, and then the
6767 // immediate non-static data members of X are assigned, in the order in
6768 // which they were declared in the class definition.
6769
6770 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00006771 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006772
6773 // The parameter for the "other" object, which we are copying from.
6774 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6775 Qualifiers OtherQuals = Other->getType().getQualifiers();
6776 QualType OtherRefType = Other->getType();
6777 if (const LValueReferenceType *OtherRef
6778 = OtherRefType->getAs<LValueReferenceType>()) {
6779 OtherRefType = OtherRef->getPointeeType();
6780 OtherQuals = OtherRefType.getQualifiers();
6781 }
6782
6783 // Our location for everything implicitly-generated.
6784 SourceLocation Loc = CopyAssignOperator->getLocation();
6785
6786 // Construct a reference to the "other" object. We'll be using this
6787 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00006788 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006789 assert(OtherRef && "Reference to parameter cannot fail!");
6790
6791 // Construct the "this" pointer. We'll be using this throughout the generated
6792 // ASTs.
6793 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6794 assert(This && "Reference to this cannot fail!");
6795
6796 // Assign base classes.
6797 bool Invalid = false;
6798 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6799 E = ClassDecl->bases_end(); Base != E; ++Base) {
6800 // Form the assignment:
6801 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6802 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00006803 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006804 Invalid = true;
6805 continue;
6806 }
6807
John McCallcf142162010-08-07 06:22:56 +00006808 CXXCastPath BasePath;
6809 BasePath.push_back(Base);
6810
Douglas Gregorb139cd52010-05-01 20:49:11 +00006811 // Construct the "from" expression, which is an implicit cast to the
6812 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00006813 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00006814 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6815 CK_UncheckedDerivedToBase,
6816 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006817
6818 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00006819 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006820
6821 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00006822 To = ImpCastExprToType(To.take(),
6823 Context.getCVRQualifiedType(BaseType,
6824 CopyAssignOperator->getTypeQualifiers()),
6825 CK_UncheckedDerivedToBase,
6826 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006827
6828 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00006829 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00006830 To.get(), From,
6831 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006832 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006833 Diag(CurrentLocation, diag::note_member_synthesized_at)
6834 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6835 CopyAssignOperator->setInvalidDecl();
6836 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006837 }
6838
6839 // Success! Record the copy.
6840 Statements.push_back(Copy.takeAs<Expr>());
6841 }
6842
6843 // \brief Reference to the __builtin_memcpy function.
6844 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006845 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006846 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006847
6848 // Assign non-static members.
6849 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6850 FieldEnd = ClassDecl->field_end();
6851 Field != FieldEnd; ++Field) {
6852 // Check for members of reference type; we can't copy those.
6853 if (Field->getType()->isReferenceType()) {
6854 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6855 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6856 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006857 Diag(CurrentLocation, diag::note_member_synthesized_at)
6858 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006859 Invalid = true;
6860 continue;
6861 }
6862
6863 // Check for members of const-qualified, non-class type.
6864 QualType BaseType = Context.getBaseElementType(Field->getType());
6865 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6866 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6867 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6868 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006869 Diag(CurrentLocation, diag::note_member_synthesized_at)
6870 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006871 Invalid = true;
6872 continue;
6873 }
6874
6875 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00006876 if (FieldType->isIncompleteArrayType()) {
6877 assert(ClassDecl->hasFlexibleArrayMember() &&
6878 "Incomplete array type is not valid");
6879 continue;
6880 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006881
6882 // Build references to the field in the object we're copying from and to.
6883 CXXScopeSpec SS; // Intentionally empty
6884 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6885 LookupMemberName);
6886 MemberLookup.addDecl(*Field);
6887 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00006888 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00006889 Loc, /*IsArrow=*/false,
6890 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00006891 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00006892 Loc, /*IsArrow=*/true,
6893 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006894 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6895 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6896
6897 // If the field should be copied with __builtin_memcpy rather than via
6898 // explicit assignments, do so. This optimization only applies for arrays
6899 // of scalars and arrays of class type with trivial copy-assignment
6900 // operators.
6901 if (FieldType->isArrayType() &&
6902 (!BaseType->isRecordType() ||
6903 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
6904 ->hasTrivialCopyAssignment())) {
6905 // Compute the size of the memory buffer to be copied.
6906 QualType SizeType = Context.getSizeType();
6907 llvm::APInt Size(Context.getTypeSize(SizeType),
6908 Context.getTypeSizeInChars(BaseType).getQuantity());
6909 for (const ConstantArrayType *Array
6910 = Context.getAsConstantArrayType(FieldType);
6911 Array;
6912 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00006913 llvm::APInt ArraySize
6914 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006915 Size *= ArraySize;
6916 }
6917
6918 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00006919 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6920 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006921
6922 bool NeedsCollectableMemCpy =
6923 (BaseType->isRecordType() &&
6924 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6925
6926 if (NeedsCollectableMemCpy) {
6927 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006928 // Create a reference to the __builtin_objc_memmove_collectable function.
6929 LookupResult R(*this,
6930 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006931 Loc, LookupOrdinaryName);
6932 LookupName(R, TUScope, true);
6933
6934 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6935 if (!CollectableMemCpy) {
6936 // Something went horribly wrong earlier, and we will have
6937 // complained about it.
6938 Invalid = true;
6939 continue;
6940 }
6941
6942 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6943 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006944 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006945 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6946 }
6947 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006948 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006949 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006950 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6951 LookupOrdinaryName);
6952 LookupName(R, TUScope, true);
6953
6954 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6955 if (!BuiltinMemCpy) {
6956 // Something went horribly wrong earlier, and we will have complained
6957 // about it.
6958 Invalid = true;
6959 continue;
6960 }
6961
6962 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6963 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006964 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006965 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6966 }
6967
John McCall37ad5512010-08-23 06:44:23 +00006968 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006969 CallArgs.push_back(To.takeAs<Expr>());
6970 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006971 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00006972 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006973 if (NeedsCollectableMemCpy)
6974 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006975 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006976 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006977 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006978 else
6979 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006980 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006981 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006982 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006983
Douglas Gregorb139cd52010-05-01 20:49:11 +00006984 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
6985 Statements.push_back(Call.takeAs<Expr>());
6986 continue;
6987 }
6988
6989 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00006990 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00006991 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006992 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006993 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006994 Diag(CurrentLocation, diag::note_member_synthesized_at)
6995 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6996 CopyAssignOperator->setInvalidDecl();
6997 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006998 }
6999
7000 // Success! Record the copy.
7001 Statements.push_back(Copy.takeAs<Stmt>());
7002 }
7003
7004 if (!Invalid) {
7005 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007006 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007007
John McCalldadc5752010-08-24 06:29:42 +00007008 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007009 if (Return.isInvalid())
7010 Invalid = true;
7011 else {
7012 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007013
7014 if (Trap.hasErrorOccurred()) {
7015 Diag(CurrentLocation, diag::note_member_synthesized_at)
7016 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7017 Invalid = true;
7018 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007019 }
7020 }
7021
7022 if (Invalid) {
7023 CopyAssignOperator->setInvalidDecl();
7024 return;
7025 }
7026
John McCalldadc5752010-08-24 06:29:42 +00007027 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007028 /*isStmtExpr=*/false);
7029 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7030 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007031
7032 if (ASTMutationListener *L = getASTMutationListener()) {
7033 L->CompletedImplicitDefinition(CopyAssignOperator);
7034 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007035}
7036
Alexis Hunt913820d2011-05-13 06:10:58 +00007037std::pair<Sema::ImplicitExceptionSpecification, bool>
7038Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00007039 // C++ [class.copy]p5:
7040 // The implicitly-declared copy constructor for a class X will
7041 // have the form
7042 //
7043 // X::X(const X&)
7044 //
7045 // if
7046 bool HasConstCopyConstructor = true;
7047
7048 // -- each direct or virtual base class B of X has a copy
7049 // constructor whose first parameter is of type const B& or
7050 // const volatile B&, and
7051 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7052 BaseEnd = ClassDecl->bases_end();
7053 HasConstCopyConstructor && Base != BaseEnd;
7054 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007055 // Virtual bases are handled below.
7056 if (Base->isVirtual())
7057 continue;
7058
Douglas Gregora6d69502010-07-02 23:41:54 +00007059 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007060 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007061 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7062 DeclareImplicitCopyConstructor(BaseClassDecl);
7063
Alexis Huntfcaeae42011-05-25 20:50:04 +00007064 HasConstCopyConstructor = BaseClassDecl->hasConstCopyConstructor();
Douglas Gregorcfe68222010-07-01 18:27:03 +00007065 }
7066
7067 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7068 BaseEnd = ClassDecl->vbases_end();
7069 HasConstCopyConstructor && Base != BaseEnd;
7070 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007071 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00007072 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007073 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7074 DeclareImplicitCopyConstructor(BaseClassDecl);
7075
Alexis Huntfcaeae42011-05-25 20:50:04 +00007076 HasConstCopyConstructor= BaseClassDecl->hasConstCopyConstructor();
Douglas Gregor54be3392010-07-01 17:57:27 +00007077 }
7078
7079 // -- for all the nonstatic data members of X that are of a
7080 // class type M (or array thereof), each such class type
7081 // has a copy constructor whose first parameter is of type
7082 // const M& or const volatile M&.
7083 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7084 FieldEnd = ClassDecl->field_end();
7085 HasConstCopyConstructor && Field != FieldEnd;
7086 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007087 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00007088 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007089 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007090 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007091 if (!FieldClassDecl->hasDeclaredCopyConstructor())
7092 DeclareImplicitCopyConstructor(FieldClassDecl);
7093
Alexis Huntfcaeae42011-05-25 20:50:04 +00007094 HasConstCopyConstructor = FieldClassDecl->hasConstCopyConstructor();
Douglas Gregor54be3392010-07-01 17:57:27 +00007095 }
7096 }
Douglas Gregor54be3392010-07-01 17:57:27 +00007097 // Otherwise, the implicitly declared copy constructor will have
7098 // the form
7099 //
7100 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00007101
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007102 // C++ [except.spec]p14:
7103 // An implicitly declared special member function (Clause 12) shall have an
7104 // exception-specification. [...]
7105 ImplicitExceptionSpecification ExceptSpec(Context);
7106 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7107 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7108 BaseEnd = ClassDecl->bases_end();
7109 Base != BaseEnd;
7110 ++Base) {
7111 // Virtual bases are handled below.
7112 if (Base->isVirtual())
7113 continue;
7114
Douglas Gregora6d69502010-07-02 23:41:54 +00007115 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007116 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007117 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7118 DeclareImplicitCopyConstructor(BaseClassDecl);
7119
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007120 if (CXXConstructorDecl *CopyConstructor
Alexis Huntfcaeae42011-05-25 20:50:04 +00007121 = BaseClassDecl->getCopyConstructor(Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007122 ExceptSpec.CalledDecl(CopyConstructor);
7123 }
7124 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7125 BaseEnd = ClassDecl->vbases_end();
7126 Base != BaseEnd;
7127 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007128 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007129 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007130 if (!BaseClassDecl->hasDeclaredCopyConstructor())
7131 DeclareImplicitCopyConstructor(BaseClassDecl);
7132
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007133 if (CXXConstructorDecl *CopyConstructor
Alexis Huntfcaeae42011-05-25 20:50:04 +00007134 = BaseClassDecl->getCopyConstructor(Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007135 ExceptSpec.CalledDecl(CopyConstructor);
7136 }
7137 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7138 FieldEnd = ClassDecl->field_end();
7139 Field != FieldEnd;
7140 ++Field) {
7141 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7142 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007143 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007144 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00007145 if (!FieldClassDecl->hasDeclaredCopyConstructor())
7146 DeclareImplicitCopyConstructor(FieldClassDecl);
7147
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007148 if (CXXConstructorDecl *CopyConstructor
Alexis Huntfcaeae42011-05-25 20:50:04 +00007149 = FieldClassDecl->getCopyConstructor(Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007150 ExceptSpec.CalledDecl(CopyConstructor);
7151 }
7152 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007153
Alexis Hunt913820d2011-05-13 06:10:58 +00007154 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7155}
7156
7157CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7158 CXXRecordDecl *ClassDecl) {
7159 // C++ [class.copy]p4:
7160 // If the class definition does not explicitly declare a copy
7161 // constructor, one is declared implicitly.
7162
7163 ImplicitExceptionSpecification Spec(Context);
7164 bool Const;
7165 llvm::tie(Spec, Const) =
7166 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7167
7168 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7169 QualType ArgType = ClassType;
7170 if (Const)
7171 ArgType = ArgType.withConst();
7172 ArgType = Context.getLValueReferenceType(ArgType);
7173
7174 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7175
Douglas Gregor54be3392010-07-01 17:57:27 +00007176 DeclarationName Name
7177 = Context.DeclarationNames.getCXXConstructorName(
7178 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007179 SourceLocation ClassLoc = ClassDecl->getLocation();
7180 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00007181
7182 // An implicitly-declared copy constructor is an inline public
7183 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00007184 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00007185 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00007186 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00007187 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00007188 /*TInfo=*/0,
7189 /*isExplicit=*/false,
7190 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00007191 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00007192 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00007193 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00007194 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7195
Douglas Gregora6d69502010-07-02 23:41:54 +00007196 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00007197 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7198
Douglas Gregor54be3392010-07-01 17:57:27 +00007199 // Add the parameter to the constructor.
7200 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007201 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00007202 /*IdentifierInfo=*/0,
7203 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007204 SC_None,
7205 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00007206 CopyConstructor->setParams(&FromParam, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00007207
Douglas Gregor0be31a22010-07-02 17:43:08 +00007208 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00007209 PushOnScopeChains(CopyConstructor, S, false);
7210 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007211
7212 if (ShouldDeleteCopyConstructor(CopyConstructor))
7213 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00007214
7215 return CopyConstructor;
7216}
7217
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007218void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00007219 CXXConstructorDecl *CopyConstructor) {
7220 assert((CopyConstructor->isDefaulted() &&
7221 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007222 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007223 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007224
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00007225 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007226 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007227
Douglas Gregora57478e2010-05-01 15:04:51 +00007228 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007229 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007230
Alexis Hunt1d792652011-01-08 20:30:50 +00007231 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007232 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00007233 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00007234 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00007235 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00007236 } else {
7237 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7238 CopyConstructor->getLocation(),
7239 MultiStmtArg(*this, 0, 0),
7240 /*isStmtExpr=*/false)
7241 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00007242 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00007243
7244 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00007245
7246 if (ASTMutationListener *L = getASTMutationListener()) {
7247 L->CompletedImplicitDefinition(CopyConstructor);
7248 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007249}
7250
John McCalldadc5752010-08-24 06:29:42 +00007251ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007252Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00007253 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007254 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007255 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007256 unsigned ConstructKind,
7257 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00007258 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00007259
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007260 // C++0x [class.copy]p34:
7261 // When certain criteria are met, an implementation is allowed to
7262 // omit the copy/move construction of a class object, even if the
7263 // copy/move constructor and/or destructor for the object have
7264 // side effects. [...]
7265 // - when a temporary class object that has not been bound to a
7266 // reference (12.2) would be copied/moved to a class object
7267 // with the same cv-unqualified type, the copy/move operation
7268 // can be omitted by constructing the temporary object
7269 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00007270 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00007271 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007272 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00007273 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00007274 }
Mike Stump11289f42009-09-09 15:08:12 +00007275
7276 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007277 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007278 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00007279}
7280
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007281/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7282/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00007283ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007284Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7285 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007286 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007287 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007288 unsigned ConstructKind,
7289 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007290 unsigned NumExprs = ExprArgs.size();
7291 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00007292
Nick Lewyckyd4693212011-03-25 01:44:32 +00007293 for (specific_attr_iterator<NonNullAttr>
7294 i = Constructor->specific_attr_begin<NonNullAttr>(),
7295 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7296 const NonNullAttr *NonNull = *i;
7297 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7298 }
7299
Douglas Gregor27381f32009-11-23 12:27:39 +00007300 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00007301 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007302 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00007303 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007304 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7305 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007306}
7307
Mike Stump11289f42009-09-09 15:08:12 +00007308bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007309 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007310 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00007311 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00007312 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00007313 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00007314 move(Exprs), false, CXXConstructExpr::CK_Complete,
7315 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007316 if (TempResult.isInvalid())
7317 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007318
Anders Carlsson6eb55572009-08-25 05:12:04 +00007319 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00007320 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00007321 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00007322 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00007323 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00007324
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007325 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00007326}
7327
John McCall03c48482010-02-02 09:10:11 +00007328void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00007329 if (VD->isInvalidDecl()) return;
7330
John McCall03c48482010-02-02 09:10:11 +00007331 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00007332 if (ClassDecl->isInvalidDecl()) return;
7333 if (ClassDecl->hasTrivialDestructor()) return;
7334 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00007335
Chandler Carruth86d17d32011-03-27 21:26:48 +00007336 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7337 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7338 CheckDestructorAccess(VD->getLocation(), Destructor,
7339 PDiag(diag::err_access_dtor_var)
7340 << VD->getDeclName()
7341 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00007342
Chandler Carruth86d17d32011-03-27 21:26:48 +00007343 if (!VD->hasGlobalStorage()) return;
7344
7345 // Emit warning for non-trivial dtor in global scope (a real global,
7346 // class-static, function-static).
7347 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7348
7349 // TODO: this should be re-enabled for static locals by !CXAAtExit
7350 if (!VD->isStaticLocal())
7351 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007352}
7353
Mike Stump11289f42009-09-09 15:08:12 +00007354/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007355/// ActOnDeclarator, when a C++ direct initializer is present.
7356/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00007357void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007358 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007359 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00007360 SourceLocation RParenLoc,
7361 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00007362 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007363
7364 // If there is no declaration, there was an error parsing it. Just ignore
7365 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00007366 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007367 return;
Mike Stump11289f42009-09-09 15:08:12 +00007368
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007369 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7370 if (!VDecl) {
7371 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7372 RealDecl->setInvalidDecl();
7373 return;
7374 }
7375
Richard Smith30482bc2011-02-20 03:19:35 +00007376 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7377 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00007378 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7379 if (Exprs.size() > 1) {
7380 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7381 diag::err_auto_var_init_multiple_expressions)
7382 << VDecl->getDeclName() << VDecl->getType()
7383 << VDecl->getSourceRange();
7384 RealDecl->setInvalidDecl();
7385 return;
7386 }
7387
7388 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00007389 TypeSourceInfo *DeducedType = 0;
7390 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00007391 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7392 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7393 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00007394 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00007395 RealDecl->setInvalidDecl();
7396 return;
7397 }
Richard Smith9647d3c2011-03-17 16:11:59 +00007398 VDecl->setTypeSourceInfo(DeducedType);
7399 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00007400
7401 // If this is a redeclaration, check that the type we just deduced matches
7402 // the previously declared type.
7403 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7404 MergeVarDeclTypes(VDecl, Old);
7405 }
7406
Douglas Gregor402250f2009-08-26 21:14:46 +00007407 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007408 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007409 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7410 //
7411 // Clients that want to distinguish between the two forms, can check for
7412 // direct initializer using VarDecl::hasCXXDirectInitializer().
7413 // A major benefit is that clients that don't particularly care about which
7414 // exactly form was it (like the CodeGen) can handle both cases without
7415 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007416
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007417 // C++ 8.5p11:
7418 // The form of initialization (using parentheses or '=') is generally
7419 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007420 // class type.
7421
Douglas Gregor50dc2192010-02-11 22:55:30 +00007422 if (!VDecl->getType()->isDependentType() &&
7423 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00007424 diag::err_typecheck_decl_incomplete_type)) {
7425 VDecl->setInvalidDecl();
7426 return;
7427 }
7428
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007429 // The variable can not have an abstract class type.
7430 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7431 diag::err_abstract_type_in_decl,
7432 AbstractVariableType))
7433 VDecl->setInvalidDecl();
7434
Sebastian Redl5ca79842010-02-01 20:16:42 +00007435 const VarDecl *Def;
7436 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007437 Diag(VDecl->getLocation(), diag::err_redefinition)
7438 << VDecl->getDeclName();
7439 Diag(Def->getLocation(), diag::note_previous_definition);
7440 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007441 return;
7442 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00007443
Douglas Gregorf0f83692010-08-24 05:27:49 +00007444 // C++ [class.static.data]p4
7445 // If a static data member is of const integral or const
7446 // enumeration type, its declaration in the class definition can
7447 // specify a constant-initializer which shall be an integral
7448 // constant expression (5.19). In that case, the member can appear
7449 // in integral constant expressions. The member shall still be
7450 // defined in a namespace scope if it is used in the program and the
7451 // namespace scope definition shall not contain an initializer.
7452 //
7453 // We already performed a redefinition check above, but for static
7454 // data members we also need to check whether there was an in-class
7455 // declaration with an initializer.
7456 const VarDecl* PrevInit = 0;
7457 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7458 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7459 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7460 return;
7461 }
7462
Douglas Gregor71f39c92010-12-16 01:31:22 +00007463 bool IsDependent = false;
7464 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7465 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7466 VDecl->setInvalidDecl();
7467 return;
7468 }
7469
7470 if (Exprs.get()[I]->isTypeDependent())
7471 IsDependent = true;
7472 }
7473
Douglas Gregor50dc2192010-02-11 22:55:30 +00007474 // If either the declaration has a dependent type or if any of the
7475 // expressions is type-dependent, we represent the initialization
7476 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00007477 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00007478 // Let clients know that initialization was done with a direct initializer.
7479 VDecl->setCXXDirectInitializer(true);
7480
7481 // Store the initialization expressions as a ParenListExpr.
7482 unsigned NumExprs = Exprs.size();
7483 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7484 (Expr **)Exprs.release(),
7485 NumExprs, RParenLoc));
7486 return;
7487 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007488
7489 // Capture the variable that is being initialized and the style of
7490 // initialization.
7491 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7492
7493 // FIXME: Poor source location information.
7494 InitializationKind Kind
7495 = InitializationKind::CreateDirect(VDecl->getLocation(),
7496 LParenLoc, RParenLoc);
7497
7498 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00007499 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00007500 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007501 if (Result.isInvalid()) {
7502 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007503 return;
7504 }
John McCallacf0ee52010-10-08 02:01:28 +00007505
7506 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007507
Douglas Gregora40433a2010-12-07 00:41:46 +00007508 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00007509 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007510 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007511
John McCall8b7fd8f12011-01-19 11:48:09 +00007512 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007513}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007514
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007515/// \brief Given a constructor and the set of arguments provided for the
7516/// constructor, convert the arguments and add any required default arguments
7517/// to form a proper call to this constructor.
7518///
7519/// \returns true if an error occurred, false otherwise.
7520bool
7521Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7522 MultiExprArg ArgsPtr,
7523 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00007524 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007525 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7526 unsigned NumArgs = ArgsPtr.size();
7527 Expr **Args = (Expr **)ArgsPtr.get();
7528
7529 const FunctionProtoType *Proto
7530 = Constructor->getType()->getAs<FunctionProtoType>();
7531 assert(Proto && "Constructor without a prototype?");
7532 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007533
7534 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007535 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007536 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007537 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007538 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007539
7540 VariadicCallType CallType =
7541 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7542 llvm::SmallVector<Expr *, 8> AllArgs;
7543 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7544 Proto, 0, Args, NumArgs, AllArgs,
7545 CallType);
7546 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7547 ConvertedArgs.push_back(AllArgs[i]);
7548 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00007549}
7550
Anders Carlssone363c8e2009-12-12 00:32:00 +00007551static inline bool
7552CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7553 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007554 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00007555 if (isa<NamespaceDecl>(DC)) {
7556 return SemaRef.Diag(FnDecl->getLocation(),
7557 diag::err_operator_new_delete_declared_in_namespace)
7558 << FnDecl->getDeclName();
7559 }
7560
7561 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00007562 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007563 return SemaRef.Diag(FnDecl->getLocation(),
7564 diag::err_operator_new_delete_declared_static)
7565 << FnDecl->getDeclName();
7566 }
7567
Anders Carlsson60659a82009-12-12 02:43:16 +00007568 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00007569}
7570
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007571static inline bool
7572CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7573 CanQualType ExpectedResultType,
7574 CanQualType ExpectedFirstParamType,
7575 unsigned DependentParamTypeDiag,
7576 unsigned InvalidParamTypeDiag) {
7577 QualType ResultType =
7578 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7579
7580 // Check that the result type is not dependent.
7581 if (ResultType->isDependentType())
7582 return SemaRef.Diag(FnDecl->getLocation(),
7583 diag::err_operator_new_delete_dependent_result_type)
7584 << FnDecl->getDeclName() << ExpectedResultType;
7585
7586 // Check that the result type is what we expect.
7587 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7588 return SemaRef.Diag(FnDecl->getLocation(),
7589 diag::err_operator_new_delete_invalid_result_type)
7590 << FnDecl->getDeclName() << ExpectedResultType;
7591
7592 // A function template must have at least 2 parameters.
7593 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7594 return SemaRef.Diag(FnDecl->getLocation(),
7595 diag::err_operator_new_delete_template_too_few_parameters)
7596 << FnDecl->getDeclName();
7597
7598 // The function decl must have at least 1 parameter.
7599 if (FnDecl->getNumParams() == 0)
7600 return SemaRef.Diag(FnDecl->getLocation(),
7601 diag::err_operator_new_delete_too_few_parameters)
7602 << FnDecl->getDeclName();
7603
7604 // Check the the first parameter type is not dependent.
7605 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7606 if (FirstParamType->isDependentType())
7607 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7608 << FnDecl->getDeclName() << ExpectedFirstParamType;
7609
7610 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00007611 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007612 ExpectedFirstParamType)
7613 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7614 << FnDecl->getDeclName() << ExpectedFirstParamType;
7615
7616 return false;
7617}
7618
Anders Carlsson12308f42009-12-11 23:23:22 +00007619static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007620CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007621 // C++ [basic.stc.dynamic.allocation]p1:
7622 // A program is ill-formed if an allocation function is declared in a
7623 // namespace scope other than global scope or declared static in global
7624 // scope.
7625 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7626 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007627
7628 CanQualType SizeTy =
7629 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7630
7631 // C++ [basic.stc.dynamic.allocation]p1:
7632 // The return type shall be void*. The first parameter shall have type
7633 // std::size_t.
7634 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7635 SizeTy,
7636 diag::err_operator_new_dependent_param_type,
7637 diag::err_operator_new_param_type))
7638 return true;
7639
7640 // C++ [basic.stc.dynamic.allocation]p1:
7641 // The first parameter shall not have an associated default argument.
7642 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00007643 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007644 diag::err_operator_new_default_arg)
7645 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7646
7647 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00007648}
7649
7650static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00007651CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7652 // C++ [basic.stc.dynamic.deallocation]p1:
7653 // A program is ill-formed if deallocation functions are declared in a
7654 // namespace scope other than global scope or declared static in global
7655 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00007656 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7657 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007658
7659 // C++ [basic.stc.dynamic.deallocation]p2:
7660 // Each deallocation function shall return void and its first parameter
7661 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007662 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7663 SemaRef.Context.VoidPtrTy,
7664 diag::err_operator_delete_dependent_param_type,
7665 diag::err_operator_delete_param_type))
7666 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007667
Anders Carlsson12308f42009-12-11 23:23:22 +00007668 return false;
7669}
7670
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007671/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7672/// of this overloaded operator is well-formed. If so, returns false;
7673/// otherwise, emits appropriate diagnostics and returns true.
7674bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00007675 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007676 "Expected an overloaded operator declaration");
7677
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007678 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7679
Mike Stump11289f42009-09-09 15:08:12 +00007680 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007681 // The allocation and deallocation functions, operator new,
7682 // operator new[], operator delete and operator delete[], are
7683 // described completely in 3.7.3. The attributes and restrictions
7684 // found in the rest of this subclause do not apply to them unless
7685 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00007686 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00007687 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00007688
Anders Carlsson22f443f2009-12-12 00:26:23 +00007689 if (Op == OO_New || Op == OO_Array_New)
7690 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007691
7692 // C++ [over.oper]p6:
7693 // An operator function shall either be a non-static member
7694 // function or be a non-member function and have at least one
7695 // parameter whose type is a class, a reference to a class, an
7696 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00007697 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7698 if (MethodDecl->isStatic())
7699 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007700 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007701 } else {
7702 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00007703 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7704 ParamEnd = FnDecl->param_end();
7705 Param != ParamEnd; ++Param) {
7706 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00007707 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7708 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007709 ClassOrEnumParam = true;
7710 break;
7711 }
7712 }
7713
Douglas Gregord69246b2008-11-17 16:14:12 +00007714 if (!ClassOrEnumParam)
7715 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007716 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007717 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007718 }
7719
7720 // C++ [over.oper]p8:
7721 // An operator function cannot have default arguments (8.3.6),
7722 // except where explicitly stated below.
7723 //
Mike Stump11289f42009-09-09 15:08:12 +00007724 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007725 // (C++ [over.call]p1).
7726 if (Op != OO_Call) {
7727 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7728 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007729 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00007730 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00007731 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007732 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007733 }
7734 }
7735
Douglas Gregor6cf08062008-11-10 13:38:07 +00007736 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7737 { false, false, false }
7738#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7739 , { Unary, Binary, MemberOnly }
7740#include "clang/Basic/OperatorKinds.def"
7741 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007742
Douglas Gregor6cf08062008-11-10 13:38:07 +00007743 bool CanBeUnaryOperator = OperatorUses[Op][0];
7744 bool CanBeBinaryOperator = OperatorUses[Op][1];
7745 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007746
7747 // C++ [over.oper]p8:
7748 // [...] Operator functions cannot have more or fewer parameters
7749 // than the number required for the corresponding operator, as
7750 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00007751 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00007752 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007753 if (Op != OO_Call &&
7754 ((NumParams == 1 && !CanBeUnaryOperator) ||
7755 (NumParams == 2 && !CanBeBinaryOperator) ||
7756 (NumParams < 1) || (NumParams > 2))) {
7757 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007758 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00007759 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007760 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00007761 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007762 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007763 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00007764 assert(CanBeBinaryOperator &&
7765 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007766 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007767 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007768
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007769 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007770 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007771 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007772
Douglas Gregord69246b2008-11-17 16:14:12 +00007773 // Overloaded operators other than operator() cannot be variadic.
7774 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00007775 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007776 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007777 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007778 }
7779
7780 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00007781 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7782 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007783 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007784 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007785 }
7786
7787 // C++ [over.inc]p1:
7788 // The user-defined function called operator++ implements the
7789 // prefix and postfix ++ operator. If this function is a member
7790 // function with no parameters, or a non-member function with one
7791 // parameter of class or enumeration type, it defines the prefix
7792 // increment operator ++ for objects of that type. If the function
7793 // is a member function with one parameter (which shall be of type
7794 // int) or a non-member function with two parameters (the second
7795 // of which shall be of type int), it defines the postfix
7796 // increment operator ++ for objects of that type.
7797 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7798 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7799 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00007800 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007801 ParamIsInt = BT->getKind() == BuiltinType::Int;
7802
Chris Lattner2b786902008-11-21 07:50:02 +00007803 if (!ParamIsInt)
7804 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00007805 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007806 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007807 }
7808
Douglas Gregord69246b2008-11-17 16:14:12 +00007809 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007810}
Chris Lattner3b024a32008-12-17 07:09:26 +00007811
Alexis Huntc88db062010-01-13 09:01:02 +00007812/// CheckLiteralOperatorDeclaration - Check whether the declaration
7813/// of this literal operator function is well-formed. If so, returns
7814/// false; otherwise, emits appropriate diagnostics and returns true.
7815bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7816 DeclContext *DC = FnDecl->getDeclContext();
7817 Decl::Kind Kind = DC->getDeclKind();
7818 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7819 Kind != Decl::LinkageSpec) {
7820 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7821 << FnDecl->getDeclName();
7822 return true;
7823 }
7824
7825 bool Valid = false;
7826
Alexis Hunt7dd26172010-04-07 23:11:06 +00007827 // template <char...> type operator "" name() is the only valid template
7828 // signature, and the only valid signature with no parameters.
7829 if (FnDecl->param_size() == 0) {
7830 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7831 // Must have only one template parameter
7832 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7833 if (Params->size() == 1) {
7834 NonTypeTemplateParmDecl *PmDecl =
7835 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00007836
Alexis Hunt7dd26172010-04-07 23:11:06 +00007837 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00007838 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7839 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7840 Valid = true;
7841 }
7842 }
7843 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00007844 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00007845 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7846
Alexis Huntc88db062010-01-13 09:01:02 +00007847 QualType T = (*Param)->getType();
7848
Alexis Hunt079a6f72010-04-07 22:57:35 +00007849 // unsigned long long int, long double, and any character type are allowed
7850 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00007851 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7852 Context.hasSameType(T, Context.LongDoubleTy) ||
7853 Context.hasSameType(T, Context.CharTy) ||
7854 Context.hasSameType(T, Context.WCharTy) ||
7855 Context.hasSameType(T, Context.Char16Ty) ||
7856 Context.hasSameType(T, Context.Char32Ty)) {
7857 if (++Param == FnDecl->param_end())
7858 Valid = true;
7859 goto FinishedParams;
7860 }
7861
Alexis Hunt079a6f72010-04-07 22:57:35 +00007862 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00007863 const PointerType *PT = T->getAs<PointerType>();
7864 if (!PT)
7865 goto FinishedParams;
7866 T = PT->getPointeeType();
7867 if (!T.isConstQualified())
7868 goto FinishedParams;
7869 T = T.getUnqualifiedType();
7870
7871 // Move on to the second parameter;
7872 ++Param;
7873
7874 // If there is no second parameter, the first must be a const char *
7875 if (Param == FnDecl->param_end()) {
7876 if (Context.hasSameType(T, Context.CharTy))
7877 Valid = true;
7878 goto FinishedParams;
7879 }
7880
7881 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7882 // are allowed as the first parameter to a two-parameter function
7883 if (!(Context.hasSameType(T, Context.CharTy) ||
7884 Context.hasSameType(T, Context.WCharTy) ||
7885 Context.hasSameType(T, Context.Char16Ty) ||
7886 Context.hasSameType(T, Context.Char32Ty)))
7887 goto FinishedParams;
7888
7889 // The second and final parameter must be an std::size_t
7890 T = (*Param)->getType().getUnqualifiedType();
7891 if (Context.hasSameType(T, Context.getSizeType()) &&
7892 ++Param == FnDecl->param_end())
7893 Valid = true;
7894 }
7895
7896 // FIXME: This diagnostic is absolutely terrible.
7897FinishedParams:
7898 if (!Valid) {
7899 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7900 << FnDecl->getDeclName();
7901 return true;
7902 }
7903
7904 return false;
7905}
7906
Douglas Gregor07665a62009-01-05 19:45:36 +00007907/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7908/// linkage specification, including the language and (if present)
7909/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7910/// the location of the language string literal, which is provided
7911/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7912/// the '{' brace. Otherwise, this linkage specification does not
7913/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00007914Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7915 SourceLocation LangLoc,
7916 llvm::StringRef Lang,
7917 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00007918 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007919 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007920 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007921 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007922 Language = LinkageSpecDecl::lang_cxx;
7923 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00007924 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00007925 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00007926 }
Mike Stump11289f42009-09-09 15:08:12 +00007927
Chris Lattner438e5012008-12-17 07:13:27 +00007928 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00007929
Douglas Gregor07665a62009-01-05 19:45:36 +00007930 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007931 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007932 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00007933 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00007934 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00007935}
7936
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00007937/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00007938/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7939/// valid, it's the position of the closing '}' brace in a linkage
7940/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00007941Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007942 Decl *LinkageSpec,
7943 SourceLocation RBraceLoc) {
7944 if (LinkageSpec) {
7945 if (RBraceLoc.isValid()) {
7946 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7947 LSDecl->setRBraceLoc(RBraceLoc);
7948 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007949 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007950 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007951 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00007952}
7953
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007954/// \brief Perform semantic analysis for the variable declaration that
7955/// occurs within a C++ catch clause, returning the newly-created
7956/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007957VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00007958 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007959 SourceLocation StartLoc,
7960 SourceLocation Loc,
7961 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007962 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007963 QualType ExDeclType = TInfo->getType();
7964
Sebastian Redl54c04d42008-12-22 19:15:10 +00007965 // Arrays and functions decay.
7966 if (ExDeclType->isArrayType())
7967 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7968 else if (ExDeclType->isFunctionType())
7969 ExDeclType = Context.getPointerType(ExDeclType);
7970
7971 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7972 // The exception-declaration shall not denote a pointer or reference to an
7973 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00007974 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00007975 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007976 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00007977 Invalid = true;
7978 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007979
Douglas Gregor104ee002010-03-08 01:47:36 +00007980 // GCC allows catching pointers and references to incomplete types
7981 // as an extension; so do we, but we warn by default.
7982
Sebastian Redl54c04d42008-12-22 19:15:10 +00007983 QualType BaseType = ExDeclType;
7984 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00007985 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00007986 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007987 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007988 BaseType = Ptr->getPointeeType();
7989 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00007990 DK = diag::ext_catch_incomplete_ptr;
7991 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00007992 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00007993 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00007994 BaseType = Ref->getPointeeType();
7995 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00007996 DK = diag::ext_catch_incomplete_ref;
7997 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007998 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00007999 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00008000 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8001 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00008002 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008003
Mike Stump11289f42009-09-09 15:08:12 +00008004 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008005 RequireNonAbstractType(Loc, ExDeclType,
8006 diag::err_abstract_type_in_decl,
8007 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00008008 Invalid = true;
8009
John McCall2ca705e2010-07-24 00:37:23 +00008010 // Only the non-fragile NeXT runtime currently supports C++ catches
8011 // of ObjC types, and no runtime supports catching ObjC types by value.
8012 if (!Invalid && getLangOptions().ObjC1) {
8013 QualType T = ExDeclType;
8014 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8015 T = RT->getPointeeType();
8016
8017 if (T->isObjCObjectType()) {
8018 Diag(Loc, diag::err_objc_object_catch);
8019 Invalid = true;
8020 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00008021 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00008022 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8023 Invalid = true;
8024 }
8025 }
8026 }
8027
Abramo Bagnaradff19302011-03-08 08:55:46 +00008028 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8029 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00008030 ExDecl->setExceptionVariable(true);
8031
Douglas Gregor6de584c2010-03-05 23:38:39 +00008032 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00008033 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00008034 // C++ [except.handle]p16:
8035 // The object declared in an exception-declaration or, if the
8036 // exception-declaration does not specify a name, a temporary (12.2) is
8037 // copy-initialized (8.5) from the exception object. [...]
8038 // The object is destroyed when the handler exits, after the destruction
8039 // of any automatic objects initialized within the handler.
8040 //
8041 // We just pretend to initialize the object with itself, then make sure
8042 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00008043 QualType initType = ExDeclType;
8044
8045 InitializedEntity entity =
8046 InitializedEntity::InitializeVariable(ExDecl);
8047 InitializationKind initKind =
8048 InitializationKind::CreateCopy(Loc, SourceLocation());
8049
8050 Expr *opaqueValue =
8051 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8052 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8053 ExprResult result = sequence.Perform(*this, entity, initKind,
8054 MultiExprArg(&opaqueValue, 1));
8055 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00008056 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00008057 else {
8058 // If the constructor used was non-trivial, set this as the
8059 // "initializer".
8060 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8061 if (!construct->getConstructor()->isTrivial()) {
8062 Expr *init = MaybeCreateExprWithCleanups(construct);
8063 ExDecl->setInit(init);
8064 }
8065
8066 // And make sure it's destructable.
8067 FinalizeVarWithDestructor(ExDecl, recordType);
8068 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00008069 }
8070 }
8071
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008072 if (Invalid)
8073 ExDecl->setInvalidDecl();
8074
8075 return ExDecl;
8076}
8077
8078/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8079/// handler.
John McCall48871652010-08-21 09:40:31 +00008080Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00008081 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00008082 bool Invalid = D.isInvalidType();
8083
8084 // Check for unexpanded parameter packs.
8085 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8086 UPPC_ExceptionType)) {
8087 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8088 D.getIdentifierLoc());
8089 Invalid = true;
8090 }
8091
Sebastian Redl54c04d42008-12-22 19:15:10 +00008092 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008093 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00008094 LookupOrdinaryName,
8095 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008096 // The scope should be freshly made just for us. There is just no way
8097 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00008098 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00008099 if (PrevDecl->isTemplateParameter()) {
8100 // Maybe we will complain about the shadowed template parameter.
8101 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008102 }
8103 }
8104
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008105 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008106 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8107 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008108 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008109 }
8110
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008111 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008112 D.getSourceRange().getBegin(),
8113 D.getIdentifierLoc(),
8114 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008115 if (Invalid)
8116 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00008117
Sebastian Redl54c04d42008-12-22 19:15:10 +00008118 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008119 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008120 PushOnScopeChains(ExDecl, S);
8121 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008122 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008123
Douglas Gregor758a8692009-06-17 21:51:59 +00008124 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00008125 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008126}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008127
Abramo Bagnaraea947882011-03-08 16:41:52 +00008128Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00008129 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00008130 Expr *AssertMessageExpr_,
8131 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00008132 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008133
Anders Carlsson54b26982009-03-14 00:33:21 +00008134 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8135 llvm::APSInt Value(32);
8136 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008137 Diag(StaticAssertLoc,
8138 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00008139 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008140 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00008141 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008142
Anders Carlsson54b26982009-03-14 00:33:21 +00008143 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008144 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00008145 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00008146 }
8147 }
Mike Stump11289f42009-09-09 15:08:12 +00008148
Douglas Gregoref68fee2010-12-15 23:55:21 +00008149 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8150 return 0;
8151
Abramo Bagnaraea947882011-03-08 16:41:52 +00008152 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8153 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00008154
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008155 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00008156 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008157}
Sebastian Redlf769df52009-03-24 22:27:57 +00008158
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008159/// \brief Perform semantic analysis of the given friend type declaration.
8160///
8161/// \returns A friend declaration that.
8162FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8163 TypeSourceInfo *TSInfo) {
8164 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8165
8166 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008167 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008168
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008169 if (!getLangOptions().CPlusPlus0x) {
8170 // C++03 [class.friend]p2:
8171 // An elaborated-type-specifier shall be used in a friend declaration
8172 // for a class.*
8173 //
8174 // * The class-key of the elaborated-type-specifier is required.
8175 if (!ActiveTemplateInstantiations.empty()) {
8176 // Do not complain about the form of friend template types during
8177 // template instantiation; we will already have complained when the
8178 // template was declared.
8179 } else if (!T->isElaboratedTypeSpecifier()) {
8180 // If we evaluated the type to a record type, suggest putting
8181 // a tag in front.
8182 if (const RecordType *RT = T->getAs<RecordType>()) {
8183 RecordDecl *RD = RT->getDecl();
8184
8185 std::string InsertionText = std::string(" ") + RD->getKindName();
8186
8187 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8188 << (unsigned) RD->getTagKind()
8189 << T
8190 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8191 InsertionText);
8192 } else {
8193 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8194 << T
8195 << SourceRange(FriendLoc, TypeRange.getEnd());
8196 }
8197 } else if (T->getAs<EnumType>()) {
8198 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008199 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008200 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008201 }
8202 }
8203
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008204 // C++0x [class.friend]p3:
8205 // If the type specifier in a friend declaration designates a (possibly
8206 // cv-qualified) class type, that class is declared as a friend; otherwise,
8207 // the friend declaration is ignored.
8208
8209 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8210 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008211
8212 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8213}
8214
John McCallace48cd2010-10-19 01:40:49 +00008215/// Handle a friend tag declaration where the scope specifier was
8216/// templated.
8217Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8218 unsigned TagSpec, SourceLocation TagLoc,
8219 CXXScopeSpec &SS,
8220 IdentifierInfo *Name, SourceLocation NameLoc,
8221 AttributeList *Attr,
8222 MultiTemplateParamsArg TempParamLists) {
8223 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8224
8225 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00008226 bool Invalid = false;
8227
8228 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008229 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00008230 TempParamLists.get(),
8231 TempParamLists.size(),
8232 /*friend*/ true,
8233 isExplicitSpecialization,
8234 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00008235 if (TemplateParams->size() > 0) {
8236 // This is a declaration of a class template.
8237 if (Invalid)
8238 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008239
John McCallace48cd2010-10-19 01:40:49 +00008240 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8241 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008242 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008243 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008244 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00008245 } else {
8246 // The "template<>" header is extraneous.
8247 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8248 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8249 isExplicitSpecialization = true;
8250 }
8251 }
8252
8253 if (Invalid) return 0;
8254
8255 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8256
8257 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00008258 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00008259 if (TempParamLists.get()[I]->size()) {
8260 isAllExplicitSpecializations = false;
8261 break;
8262 }
8263 }
8264
8265 // FIXME: don't ignore attributes.
8266
8267 // If it's explicit specializations all the way down, just forget
8268 // about the template header and build an appropriate non-templated
8269 // friend. TODO: for source fidelity, remember the headers.
8270 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008271 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00008272 ElaboratedTypeKeyword Keyword
8273 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008274 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008275 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00008276 if (T.isNull())
8277 return 0;
8278
8279 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8280 if (isa<DependentNameType>(T)) {
8281 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8282 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008283 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008284 TL.setNameLoc(NameLoc);
8285 } else {
8286 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8287 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008288 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008289 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8290 }
8291
8292 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8293 TSI, FriendLoc);
8294 Friend->setAccess(AS_public);
8295 CurContext->addDecl(Friend);
8296 return Friend;
8297 }
8298
8299 // Handle the case of a templated-scope friend class. e.g.
8300 // template <class T> class A<T>::B;
8301 // FIXME: we don't support these right now.
8302 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8303 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8304 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8305 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8306 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008307 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00008308 TL.setNameLoc(NameLoc);
8309
8310 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8311 TSI, FriendLoc);
8312 Friend->setAccess(AS_public);
8313 Friend->setUnsupportedFriend(true);
8314 CurContext->addDecl(Friend);
8315 return Friend;
8316}
8317
8318
John McCall11083da2009-09-16 22:47:08 +00008319/// Handle a friend type declaration. This works in tandem with
8320/// ActOnTag.
8321///
8322/// Notes on friend class templates:
8323///
8324/// We generally treat friend class declarations as if they were
8325/// declaring a class. So, for example, the elaborated type specifier
8326/// in a friend declaration is required to obey the restrictions of a
8327/// class-head (i.e. no typedefs in the scope chain), template
8328/// parameters are required to match up with simple template-ids, &c.
8329/// However, unlike when declaring a template specialization, it's
8330/// okay to refer to a template specialization without an empty
8331/// template parameter declaration, e.g.
8332/// friend class A<T>::B<unsigned>;
8333/// We permit this as a special case; if there are any template
8334/// parameters present at all, require proper matching, i.e.
8335/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00008336Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00008337 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008338 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00008339
8340 assert(DS.isFriendSpecified());
8341 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8342
John McCall11083da2009-09-16 22:47:08 +00008343 // Try to convert the decl specifier to a type. This works for
8344 // friend templates because ActOnTag never produces a ClassTemplateDecl
8345 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00008346 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00008347 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8348 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00008349 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00008350 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008351
Douglas Gregor6c110f32010-12-16 01:14:37 +00008352 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8353 return 0;
8354
John McCall11083da2009-09-16 22:47:08 +00008355 // This is definitely an error in C++98. It's probably meant to
8356 // be forbidden in C++0x, too, but the specification is just
8357 // poorly written.
8358 //
8359 // The problem is with declarations like the following:
8360 // template <T> friend A<T>::foo;
8361 // where deciding whether a class C is a friend or not now hinges
8362 // on whether there exists an instantiation of A that causes
8363 // 'foo' to equal C. There are restrictions on class-heads
8364 // (which we declare (by fiat) elaborated friend declarations to
8365 // be) that makes this tractable.
8366 //
8367 // FIXME: handle "template <> friend class A<T>;", which
8368 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00008369 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00008370 Diag(Loc, diag::err_tagless_friend_type_template)
8371 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008372 return 0;
John McCall11083da2009-09-16 22:47:08 +00008373 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008374
John McCallaa74a0c2009-08-28 07:59:38 +00008375 // C++98 [class.friend]p1: A friend of a class is a function
8376 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00008377 // This is fixed in DR77, which just barely didn't make the C++03
8378 // deadline. It's also a very silly restriction that seriously
8379 // affects inner classes and which nobody else seems to implement;
8380 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00008381 //
8382 // But note that we could warn about it: it's always useless to
8383 // friend one of your own members (it's not, however, worthless to
8384 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00008385
John McCall11083da2009-09-16 22:47:08 +00008386 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008387 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00008388 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008389 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00008390 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00008391 TSI,
John McCall11083da2009-09-16 22:47:08 +00008392 DS.getFriendSpecLoc());
8393 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008394 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8395
8396 if (!D)
John McCall48871652010-08-21 09:40:31 +00008397 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008398
John McCall11083da2009-09-16 22:47:08 +00008399 D->setAccess(AS_public);
8400 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00008401
John McCall48871652010-08-21 09:40:31 +00008402 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00008403}
8404
John McCallde3fd222010-10-12 23:13:28 +00008405Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8406 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008407 const DeclSpec &DS = D.getDeclSpec();
8408
8409 assert(DS.isFriendSpecified());
8410 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8411
8412 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00008413 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8414 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00008415
8416 // C++ [class.friend]p1
8417 // A friend of a class is a function or class....
8418 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00008419 // It *doesn't* see through dependent types, which is correct
8420 // according to [temp.arg.type]p3:
8421 // If a declaration acquires a function type through a
8422 // type dependent on a template-parameter and this causes
8423 // a declaration that does not use the syntactic form of a
8424 // function declarator to have a function type, the program
8425 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00008426 if (!T->isFunctionType()) {
8427 Diag(Loc, diag::err_unexpected_friend);
8428
8429 // It might be worthwhile to try to recover by creating an
8430 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00008431 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008432 }
8433
8434 // C++ [namespace.memdef]p3
8435 // - If a friend declaration in a non-local class first declares a
8436 // class or function, the friend class or function is a member
8437 // of the innermost enclosing namespace.
8438 // - The name of the friend is not found by simple name lookup
8439 // until a matching declaration is provided in that namespace
8440 // scope (either before or after the class declaration granting
8441 // friendship).
8442 // - If a friend function is called, its name may be found by the
8443 // name lookup that considers functions from namespaces and
8444 // classes associated with the types of the function arguments.
8445 // - When looking for a prior declaration of a class or a function
8446 // declared as a friend, scopes outside the innermost enclosing
8447 // namespace scope are not considered.
8448
John McCallde3fd222010-10-12 23:13:28 +00008449 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008450 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8451 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00008452 assert(Name);
8453
Douglas Gregor6c110f32010-12-16 01:14:37 +00008454 // Check for unexpanded parameter packs.
8455 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8456 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8457 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8458 return 0;
8459
John McCall07e91c02009-08-06 02:15:43 +00008460 // The context we found the declaration in, or in which we should
8461 // create the declaration.
8462 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00008463 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008464 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00008465 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00008466
John McCallde3fd222010-10-12 23:13:28 +00008467 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00008468
John McCallde3fd222010-10-12 23:13:28 +00008469 // There are four cases here.
8470 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00008471 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00008472 // there as appropriate.
8473 // Recover from invalid scope qualifiers as if they just weren't there.
8474 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00008475 // C++0x [namespace.memdef]p3:
8476 // If the name in a friend declaration is neither qualified nor
8477 // a template-id and the declaration is a function or an
8478 // elaborated-type-specifier, the lookup to determine whether
8479 // the entity has been previously declared shall not consider
8480 // any scopes outside the innermost enclosing namespace.
8481 // C++0x [class.friend]p11:
8482 // If a friend declaration appears in a local class and the name
8483 // specified is an unqualified name, a prior declaration is
8484 // looked up without considering scopes that are outside the
8485 // innermost enclosing non-class scope. For a friend function
8486 // declaration, if there is no prior declaration, the program is
8487 // ill-formed.
8488 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00008489 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00008490
John McCallf7cfb222010-10-13 05:45:15 +00008491 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00008492 DC = CurContext;
8493 while (true) {
8494 // Skip class contexts. If someone can cite chapter and verse
8495 // for this behavior, that would be nice --- it's what GCC and
8496 // EDG do, and it seems like a reasonable intent, but the spec
8497 // really only says that checks for unqualified existing
8498 // declarations should stop at the nearest enclosing namespace,
8499 // not that they should only consider the nearest enclosing
8500 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008501 while (DC->isRecord())
8502 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00008503
John McCall1f82f242009-11-18 22:49:29 +00008504 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00008505
8506 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00008507 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00008508 break;
John McCallf7cfb222010-10-13 05:45:15 +00008509
John McCallf4776592010-10-14 22:22:28 +00008510 if (isTemplateId) {
8511 if (isa<TranslationUnitDecl>(DC)) break;
8512 } else {
8513 if (DC->isFileContext()) break;
8514 }
John McCall07e91c02009-08-06 02:15:43 +00008515 DC = DC->getParent();
8516 }
8517
8518 // C++ [class.friend]p1: A friend of a class is a function or
8519 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00008520 // C++0x changes this for both friend types and functions.
8521 // Most C++ 98 compilers do seem to give an error here, so
8522 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00008523 if (!Previous.empty() && DC->Equals(CurContext)
8524 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00008525 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00008526
John McCallccbc0322010-10-13 06:22:15 +00008527 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00008528
John McCallde3fd222010-10-12 23:13:28 +00008529 // - There's a non-dependent scope specifier, in which case we
8530 // compute it and do a previous lookup there for a function
8531 // or function template.
8532 } else if (!SS.getScopeRep()->isDependent()) {
8533 DC = computeDeclContext(SS);
8534 if (!DC) return 0;
8535
8536 if (RequireCompleteDeclContext(SS, DC)) return 0;
8537
8538 LookupQualifiedName(Previous, DC);
8539
8540 // Ignore things found implicitly in the wrong scope.
8541 // TODO: better diagnostics for this case. Suggesting the right
8542 // qualified scope would be nice...
8543 LookupResult::Filter F = Previous.makeFilter();
8544 while (F.hasNext()) {
8545 NamedDecl *D = F.next();
8546 if (!DC->InEnclosingNamespaceSetOf(
8547 D->getDeclContext()->getRedeclContext()))
8548 F.erase();
8549 }
8550 F.done();
8551
8552 if (Previous.empty()) {
8553 D.setInvalidType();
8554 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8555 return 0;
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 . . .
8560 if (DC->Equals(CurContext))
8561 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8562
8563 // - There's a scope specifier that does not match any template
8564 // parameter lists, in which case we use some arbitrary context,
8565 // create a method or method template, and wait for instantiation.
8566 // - There's a scope specifier that does match some template
8567 // parameter lists, which we don't handle right now.
8568 } else {
8569 DC = CurContext;
8570 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00008571 }
8572
John McCallf7cfb222010-10-13 05:45:15 +00008573 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00008574 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00008575 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8576 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8577 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00008578 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00008579 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8580 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00008581 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008582 }
John McCall07e91c02009-08-06 02:15:43 +00008583 }
8584
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008585 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00008586 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00008587 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00008588 IsDefinition,
8589 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00008590 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00008591
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008592 assert(ND->getDeclContext() == DC);
8593 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00008594
John McCall759e32b2009-08-31 22:39:49 +00008595 // Add the function declaration to the appropriate lookup tables,
8596 // adjusting the redeclarations list as necessary. We don't
8597 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00008598 //
John McCall759e32b2009-08-31 22:39:49 +00008599 // Also update the scope-based lookup if the target context's
8600 // lookup context is in lexical scope.
8601 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008602 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008603 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008604 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008605 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008606 }
John McCallaa74a0c2009-08-28 07:59:38 +00008607
8608 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008609 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00008610 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00008611 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00008612 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00008613
John McCallde3fd222010-10-12 23:13:28 +00008614 if (ND->isInvalidDecl())
8615 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00008616 else {
8617 FunctionDecl *FD;
8618 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8619 FD = FTD->getTemplatedDecl();
8620 else
8621 FD = cast<FunctionDecl>(ND);
8622
8623 // Mark templated-scope function declarations as unsupported.
8624 if (FD->getNumTemplateParameterLists())
8625 FrD->setUnsupportedFriend(true);
8626 }
John McCallde3fd222010-10-12 23:13:28 +00008627
John McCall48871652010-08-21 09:40:31 +00008628 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00008629}
8630
John McCall48871652010-08-21 09:40:31 +00008631void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8632 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00008633
Sebastian Redlf769df52009-03-24 22:27:57 +00008634 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8635 if (!Fn) {
8636 Diag(DelLoc, diag::err_deleted_non_function);
8637 return;
8638 }
8639 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8640 Diag(DelLoc, diag::err_deleted_decl_not_first);
8641 Diag(Prev->getLocation(), diag::note_previous_declaration);
8642 // If the declaration wasn't the first, we delete the function anyway for
8643 // recovery.
8644 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008645 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00008646}
Sebastian Redl4c018662009-04-27 21:33:24 +00008647
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008648void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8649 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8650
8651 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +00008652 if (MD->getParent()->isDependentType()) {
8653 MD->setDefaulted();
8654 MD->setExplicitlyDefaulted();
8655 return;
8656 }
8657
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008658 CXXSpecialMember Member = getSpecialMember(MD);
8659 if (Member == CXXInvalid) {
8660 Diag(DefaultLoc, diag::err_default_special_members);
8661 return;
8662 }
8663
8664 MD->setDefaulted();
8665 MD->setExplicitlyDefaulted();
8666
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008667 // If this definition appears within the record, do the checking when
8668 // the record is complete.
8669 const FunctionDecl *Primary = MD;
8670 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8671 // Find the uninstantiated declaration that actually had the '= default'
8672 // on it.
8673 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8674
8675 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008676 return;
8677
8678 switch (Member) {
8679 case CXXDefaultConstructor: {
8680 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8681 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008682 if (!CD->isInvalidDecl())
8683 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8684 break;
8685 }
8686
8687 case CXXCopyConstructor: {
8688 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8689 CheckExplicitlyDefaultedCopyConstructor(CD);
8690 if (!CD->isInvalidDecl())
8691 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008692 break;
8693 }
Alexis Huntf91729462011-05-12 22:46:25 +00008694
Alexis Huntc9a55732011-05-14 05:23:28 +00008695 case CXXCopyAssignment: {
8696 CheckExplicitlyDefaultedCopyAssignment(MD);
8697 if (!MD->isInvalidDecl())
8698 DefineImplicitCopyAssignment(DefaultLoc, MD);
8699 break;
8700 }
8701
Alexis Huntf91729462011-05-12 22:46:25 +00008702 case CXXDestructor: {
8703 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8704 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008705 if (!DD->isInvalidDecl())
8706 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00008707 break;
8708 }
8709
Alexis Hunt119c10e2011-05-25 23:16:36 +00008710 case CXXMoveConstructor:
8711 case CXXMoveAssignment:
8712 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8713 break;
8714
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008715 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00008716 // FIXME: Do the rest once we have move functions
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008717 break;
8718 }
8719 } else {
8720 Diag(DefaultLoc, diag::err_default_special_members);
8721 }
8722}
8723
Sebastian Redl4c018662009-04-27 21:33:24 +00008724static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00008725 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00008726 Stmt *SubStmt = *CI;
8727 if (!SubStmt)
8728 continue;
8729 if (isa<ReturnStmt>(SubStmt))
8730 Self.Diag(SubStmt->getSourceRange().getBegin(),
8731 diag::err_return_in_constructor_handler);
8732 if (!isa<Expr>(SubStmt))
8733 SearchForReturnInStmt(Self, SubStmt);
8734 }
8735}
8736
8737void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8738 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8739 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8740 SearchForReturnInStmt(*this, Handler);
8741 }
8742}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008743
Mike Stump11289f42009-09-09 15:08:12 +00008744bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008745 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00008746 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8747 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008748
Chandler Carruth284bb2e2010-02-15 11:53:20 +00008749 if (Context.hasSameType(NewTy, OldTy) ||
8750 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008751 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008752
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008753 // Check if the return types are covariant
8754 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00008755
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008756 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008757 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8758 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008759 NewClassTy = NewPT->getPointeeType();
8760 OldClassTy = OldPT->getPointeeType();
8761 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008762 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8763 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8764 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8765 NewClassTy = NewRT->getPointeeType();
8766 OldClassTy = OldRT->getPointeeType();
8767 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008768 }
8769 }
Mike Stump11289f42009-09-09 15:08:12 +00008770
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008771 // The return types aren't either both pointers or references to a class type.
8772 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00008773 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008774 diag::err_different_return_type_for_overriding_virtual_function)
8775 << New->getDeclName() << NewTy << OldTy;
8776 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00008777
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008778 return true;
8779 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008780
Anders Carlssone60365b2009-12-31 18:34:24 +00008781 // C++ [class.virtual]p6:
8782 // If the return type of D::f differs from the return type of B::f, the
8783 // class type in the return type of D::f shall be complete at the point of
8784 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008785 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8786 if (!RT->isBeingDefined() &&
8787 RequireCompleteType(New->getLocation(), NewClassTy,
8788 PDiag(diag::err_covariant_return_incomplete)
8789 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00008790 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008791 }
Anders Carlssone60365b2009-12-31 18:34:24 +00008792
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008793 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008794 // Check if the new class derives from the old class.
8795 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8796 Diag(New->getLocation(),
8797 diag::err_covariant_return_not_derived)
8798 << New->getDeclName() << NewTy << OldTy;
8799 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8800 return true;
8801 }
Mike Stump11289f42009-09-09 15:08:12 +00008802
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008803 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00008804 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00008805 diag::err_covariant_return_inaccessible_base,
8806 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8807 // FIXME: Should this point to the return type?
8808 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00008809 // FIXME: this note won't trigger for delayed access control
8810 // diagnostics, and it's impossible to get an undelayed error
8811 // here from access control during the original parse because
8812 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008813 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8814 return true;
8815 }
8816 }
Mike Stump11289f42009-09-09 15:08:12 +00008817
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008818 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008819 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008820 Diag(New->getLocation(),
8821 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008822 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008823 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8824 return true;
8825 };
Mike Stump11289f42009-09-09 15:08:12 +00008826
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008827
8828 // The new class type must have the same or less qualifiers as the old type.
8829 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8830 Diag(New->getLocation(),
8831 diag::err_covariant_return_type_class_type_more_qualified)
8832 << New->getDeclName() << NewTy << OldTy;
8833 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8834 return true;
8835 };
Mike Stump11289f42009-09-09 15:08:12 +00008836
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008837 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008838}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008839
Douglas Gregor21920e372009-12-01 17:24:26 +00008840/// \brief Mark the given method pure.
8841///
8842/// \param Method the method to be marked pure.
8843///
8844/// \param InitRange the source range that covers the "0" initializer.
8845bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008846 SourceLocation EndLoc = InitRange.getEnd();
8847 if (EndLoc.isValid())
8848 Method->setRangeEnd(EndLoc);
8849
Douglas Gregor21920e372009-12-01 17:24:26 +00008850 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8851 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00008852 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008853 }
Douglas Gregor21920e372009-12-01 17:24:26 +00008854
8855 if (!Method->isInvalidDecl())
8856 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8857 << Method->getDeclName() << InitRange;
8858 return true;
8859}
8860
John McCall1f4ee7b2009-12-19 09:28:58 +00008861/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8862/// an initializer for the out-of-line declaration 'Dcl'. The scope
8863/// is a fresh scope pushed for just this purpose.
8864///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008865/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8866/// static data member of class X, names should be looked up in the scope of
8867/// class X.
John McCall48871652010-08-21 09:40:31 +00008868void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008869 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008870 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008871
John McCall1f4ee7b2009-12-19 09:28:58 +00008872 // We should only get called for declarations with scope specifiers, like:
8873 // int foo::bar;
8874 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008875 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008876}
8877
8878/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00008879/// initializer for the out-of-line declaration 'D'.
8880void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008881 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008882 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008883
John McCall1f4ee7b2009-12-19 09:28:58 +00008884 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008885 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008886}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008887
8888/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8889/// C++ if/switch/while/for statement.
8890/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00008891DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008892 // C++ 6.4p2:
8893 // The declarator shall not specify a function or an array.
8894 // The type-specifier-seq shall not contain typedef and shall not declare a
8895 // new class or enumeration.
8896 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8897 "Parser allowed 'typedef' as storage class of condition decl.");
8898
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008899 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00008900 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
8901 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008902
8903 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
8904 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
8905 // would be created and CXXConditionDeclExpr wants a VarDecl.
8906 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
8907 << D.getSourceRange();
8908 return DeclResult();
8909 } else if (OwnedTag && OwnedTag->isDefinition()) {
8910 // The type-specifier-seq shall not declare a new class or enumeration.
8911 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
8912 }
8913
John McCall48871652010-08-21 09:40:31 +00008914 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008915 if (!Dcl)
8916 return DeclResult();
8917
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008918 return Dcl;
8919}
Anders Carlssonf98849e2009-12-02 17:15:43 +00008920
Douglas Gregor88d292c2010-05-13 16:44:06 +00008921void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8922 bool DefinitionRequired) {
8923 // Ignore any vtable uses in unevaluated operands or for classes that do
8924 // not have a vtable.
8925 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8926 CurContext->isDependentContext() ||
8927 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00008928 return;
8929
Douglas Gregor88d292c2010-05-13 16:44:06 +00008930 // Try to insert this class into the map.
8931 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8932 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8933 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8934 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00008935 // If we already had an entry, check to see if we are promoting this vtable
8936 // to required a definition. If so, we need to reappend to the VTableUses
8937 // list, since we may have already processed the first entry.
8938 if (DefinitionRequired && !Pos.first->second) {
8939 Pos.first->second = true;
8940 } else {
8941 // Otherwise, we can early exit.
8942 return;
8943 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008944 }
8945
8946 // Local classes need to have their virtual members marked
8947 // immediately. For all other classes, we mark their virtual members
8948 // at the end of the translation unit.
8949 if (Class->isLocalClass())
8950 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00008951 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00008952 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00008953}
8954
Douglas Gregor88d292c2010-05-13 16:44:06 +00008955bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008956 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00008957 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00008958
Douglas Gregor88d292c2010-05-13 16:44:06 +00008959 // Note: The VTableUses vector could grow as a result of marking
8960 // the members of a class as "used", so we check the size each
8961 // time through the loop and prefer indices (with are stable) to
8962 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00008963 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00008964 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00008965 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00008966 if (!Class)
8967 continue;
8968
8969 SourceLocation Loc = VTableUses[I].second;
8970
8971 // If this class has a key function, but that key function is
8972 // defined in another translation unit, we don't need to emit the
8973 // vtable even though we're using it.
8974 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00008975 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008976 switch (KeyFunction->getTemplateSpecializationKind()) {
8977 case TSK_Undeclared:
8978 case TSK_ExplicitSpecialization:
8979 case TSK_ExplicitInstantiationDeclaration:
8980 // The key function is in another translation unit.
8981 continue;
8982
8983 case TSK_ExplicitInstantiationDefinition:
8984 case TSK_ImplicitInstantiation:
8985 // We will be instantiating the key function.
8986 break;
8987 }
8988 } else if (!KeyFunction) {
8989 // If we have a class with no key function that is the subject
8990 // of an explicit instantiation declaration, suppress the
8991 // vtable; it will live with the explicit instantiation
8992 // definition.
8993 bool IsExplicitInstantiationDeclaration
8994 = Class->getTemplateSpecializationKind()
8995 == TSK_ExplicitInstantiationDeclaration;
8996 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
8997 REnd = Class->redecls_end();
8998 R != REnd; ++R) {
8999 TemplateSpecializationKind TSK
9000 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9001 if (TSK == TSK_ExplicitInstantiationDeclaration)
9002 IsExplicitInstantiationDeclaration = true;
9003 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9004 IsExplicitInstantiationDeclaration = false;
9005 break;
9006 }
9007 }
9008
9009 if (IsExplicitInstantiationDeclaration)
9010 continue;
9011 }
9012
9013 // Mark all of the virtual members of this class as referenced, so
9014 // that we can build a vtable. Then, tell the AST consumer that a
9015 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00009016 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009017 MarkVirtualMembersReferenced(Loc, Class);
9018 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9019 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9020
9021 // Optionally warn if we're emitting a weak vtable.
9022 if (Class->getLinkage() == ExternalLinkage &&
9023 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009024 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00009025 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9026 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00009027 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009028 VTableUses.clear();
9029
Douglas Gregor97509692011-04-22 22:25:37 +00009030 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00009031}
Anders Carlsson82fccd02009-12-07 08:24:59 +00009032
Rafael Espindola5b334082010-03-26 00:36:59 +00009033void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9034 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00009035 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9036 e = RD->method_end(); i != e; ++i) {
9037 CXXMethodDecl *MD = *i;
9038
9039 // C++ [basic.def.odr]p2:
9040 // [...] A virtual member function is used if it is not pure. [...]
9041 if (MD->isVirtual() && !MD->isPure())
9042 MarkDeclarationReferenced(Loc, MD);
9043 }
Rafael Espindola5b334082010-03-26 00:36:59 +00009044
9045 // Only classes that have virtual bases need a VTT.
9046 if (RD->getNumVBases() == 0)
9047 return;
9048
9049 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9050 e = RD->bases_end(); i != e; ++i) {
9051 const CXXRecordDecl *Base =
9052 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00009053 if (Base->getNumVBases() == 0)
9054 continue;
9055 MarkVirtualMembersReferenced(Loc, Base);
9056 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00009057}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009058
9059/// SetIvarInitializers - This routine builds initialization ASTs for the
9060/// Objective-C implementation whose ivars need be initialized.
9061void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9062 if (!getLangOptions().CPlusPlus)
9063 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00009064 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009065 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9066 CollectIvarsToConstructOrDestruct(OID, ivars);
9067 if (ivars.empty())
9068 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00009069 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009070 for (unsigned i = 0; i < ivars.size(); i++) {
9071 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00009072 if (Field->isInvalidDecl())
9073 continue;
9074
Alexis Hunt1d792652011-01-08 20:30:50 +00009075 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009076 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9077 InitializationKind InitKind =
9078 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9079
9080 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00009081 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00009082 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00009083 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009084 // Note, MemberInit could actually come back empty if no initialization
9085 // is required (e.g., because it would call a trivial default constructor)
9086 if (!MemberInit.get() || MemberInit.isInvalid())
9087 continue;
John McCallacf0ee52010-10-08 02:01:28 +00009088
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009089 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00009090 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9091 SourceLocation(),
9092 MemberInit.takeAs<Expr>(),
9093 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009094 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00009095
9096 // Be sure that the destructor is accessible and is marked as referenced.
9097 if (const RecordType *RecordTy
9098 = Context.getBaseElementType(Field->getType())
9099 ->getAs<RecordType>()) {
9100 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00009101 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00009102 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9103 CheckDestructorAccess(Field->getLocation(), Destructor,
9104 PDiag(diag::err_access_dtor_ivar)
9105 << Context.getBaseElementType(Field->getType()));
9106 }
9107 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009108 }
9109 ObjCImplementation->setIvarInitializers(Context,
9110 AllToInit.data(), AllToInit.size());
9111 }
9112}
Alexis Hunt6118d662011-05-04 05:57:24 +00009113
Alexis Hunt27a761d2011-05-04 23:29:54 +00009114static
9115void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9116 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9117 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9118 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9119 Sema &S) {
9120 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9121 CE = Current.end();
9122 if (Ctor->isInvalidDecl())
9123 return;
9124
9125 const FunctionDecl *FNTarget = 0;
9126 CXXConstructorDecl *Target;
9127
9128 // We ignore the result here since if we don't have a body, Target will be
9129 // null below.
9130 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9131 Target
9132= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9133
9134 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9135 // Avoid dereferencing a null pointer here.
9136 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9137
9138 if (!Current.insert(Canonical))
9139 return;
9140
9141 // We know that beyond here, we aren't chaining into a cycle.
9142 if (!Target || !Target->isDelegatingConstructor() ||
9143 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9144 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9145 Valid.insert(*CI);
9146 Current.clear();
9147 // We've hit a cycle.
9148 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9149 Current.count(TCanonical)) {
9150 // If we haven't diagnosed this cycle yet, do so now.
9151 if (!Invalid.count(TCanonical)) {
9152 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00009153 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00009154 << Ctor;
9155
9156 // Don't add a note for a function delegating directo to itself.
9157 if (TCanonical != Canonical)
9158 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9159
9160 CXXConstructorDecl *C = Target;
9161 while (C->getCanonicalDecl() != Canonical) {
9162 (void)C->getTargetConstructor()->hasBody(FNTarget);
9163 assert(FNTarget && "Ctor cycle through bodiless function");
9164
9165 C
9166 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9167 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9168 }
9169 }
9170
9171 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9172 Invalid.insert(*CI);
9173 Current.clear();
9174 } else {
9175 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9176 }
9177}
9178
9179
Alexis Hunt6118d662011-05-04 05:57:24 +00009180void Sema::CheckDelegatingCtorCycles() {
9181 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9182
Alexis Hunt27a761d2011-05-04 23:29:54 +00009183 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9184 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00009185
9186 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00009187 I = DelegatingCtorDecls.begin(),
9188 E = DelegatingCtorDecls.end();
9189 I != E; ++I) {
9190 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00009191 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00009192
9193 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9194 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00009195}