blob: d80bfb9b7e5afb98df4ff392745e68e1ad28e141 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115 // If we have an MSAny spec already, don't bother.
116 if (!Method || ComputedEST == EST_MSAny)
117 return;
118
119 const FunctionProtoType *Proto
120 = Method->getType()->getAs<FunctionProtoType>();
121
122 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
123
124 // If this function can throw any exceptions, make a note of that.
125 if (EST == EST_MSAny || EST == EST_None) {
126 ClearExceptions();
127 ComputedEST = EST;
128 return;
129 }
130
131 // If this function has a basic noexcept, it doesn't affect the outcome.
132 if (EST == EST_BasicNoexcept)
133 return;
134
135 // If we have a throw-all spec at this point, ignore the function.
136 if (ComputedEST == EST_None)
137 return;
138
139 // If we're still at noexcept(true) and there's a nothrow() callee,
140 // change to that specification.
141 if (EST == EST_DynamicNone) {
142 if (ComputedEST == EST_BasicNoexcept)
143 ComputedEST = EST_DynamicNone;
144 return;
145 }
146
147 // Check out noexcept specs.
148 if (EST == EST_ComputedNoexcept) {
149 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
150 assert(NR != FunctionProtoType::NR_NoNoexcept &&
151 "Must have noexcept result for EST_ComputedNoexcept.");
152 assert(NR != FunctionProtoType::NR_Dependent &&
153 "Should not generate implicit declarations for dependent cases, "
154 "and don't know how to handle them anyway.");
155
156 // noexcept(false) -> no spec on the new function
157 if (NR == FunctionProtoType::NR_Throw) {
158 ClearExceptions();
159 ComputedEST = EST_None;
160 }
161 // noexcept(true) won't change anything either.
162 return;
163 }
164
165 assert(EST == EST_Dynamic && "EST case not considered earlier.");
166 assert(ComputedEST != EST_None &&
167 "Shouldn't collect exceptions when throw-all is guaranteed.");
168 ComputedEST = EST_Dynamic;
169 // Record the exceptions in this function's exception specification.
170 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
171 EEnd = Proto->exception_end();
172 E != EEnd; ++E)
173 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
174 Exceptions.push_back(*E);
175}
176
Anders Carlssoned961f92009-08-25 02:29:20 +0000177bool
John McCall9ae2f072010-08-23 23:25:46 +0000178Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000179 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000180 if (RequireCompleteType(Param->getLocation(), Param->getType(),
181 diag::err_typecheck_decl_incomplete_type)) {
182 Param->setInvalidDecl();
183 return true;
184 }
185
Anders Carlssoned961f92009-08-25 02:29:20 +0000186 // C++ [dcl.fct.default]p5
187 // A default argument expression is implicitly converted (clause
188 // 4) to the parameter type. The default argument expression has
189 // the same semantic constraints as the initializer expression in
190 // a declaration of a variable of the parameter type, using the
191 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000192 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
193 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000194 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
195 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000196 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000197 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000198 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000199 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000200 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000201 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000202
John McCallb4eb64d2010-10-08 02:01:28 +0000203 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000204 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Anders Carlssoned961f92009-08-25 02:29:20 +0000206 // Okay: add the default argument to the parameter
207 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000209 // We have already instantiated this parameter; provide each of the
210 // instantiations with the uninstantiated default argument.
211 UnparsedDefaultArgInstantiationsMap::iterator InstPos
212 = UnparsedDefaultArgInstantiations.find(Param);
213 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
214 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
215 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
216
217 // We're done tracking this parameter's instantiations.
218 UnparsedDefaultArgInstantiations.erase(InstPos);
219 }
220
Anders Carlsson9351c172009-08-25 03:18:48 +0000221 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000222}
223
Chris Lattner8123a952008-04-10 02:22:51 +0000224/// ActOnParamDefaultArgument - Check whether the default argument
225/// provided for a function parameter is well-formed. If so, attach it
226/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000227void
John McCalld226f652010-08-21 09:40:31 +0000228Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000229 Expr *DefaultArg) {
230 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000231 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000232
John McCalld226f652010-08-21 09:40:31 +0000233 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000234 UnparsedDefaultArgLocs.erase(Param);
235
Chris Lattner3d1cee32008-04-08 05:04:30 +0000236 // Default arguments are only permitted in C++
237 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000238 Diag(EqualLoc, diag::err_param_default_argument)
239 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000240 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000241 return;
242 }
243
Douglas Gregor6f526752010-12-16 08:48:57 +0000244 // Check for unexpanded parameter packs.
245 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
246 Param->setInvalidDecl();
247 return;
248 }
249
Anders Carlsson66e30672009-08-25 01:02:06 +0000250 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000251 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
252 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000253 Param->setInvalidDecl();
254 return;
255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
John McCall9ae2f072010-08-23 23:25:46 +0000257 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000258}
259
Douglas Gregor61366e92008-12-24 00:01:03 +0000260/// ActOnParamUnparsedDefaultArgument - We've seen a default
261/// argument for a function parameter, but we can't parse it yet
262/// because we're inside a class definition. Note that this default
263/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000264void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000265 SourceLocation EqualLoc,
266 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000267 if (!param)
268 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000269
John McCalld226f652010-08-21 09:40:31 +0000270 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000271 if (Param)
272 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Anders Carlsson5e300d12009-06-12 16:51:40 +0000274 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000275}
276
Douglas Gregor72b505b2008-12-16 21:30:33 +0000277/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
278/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000279void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000280 if (!param)
281 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000282
John McCalld226f652010-08-21 09:40:31 +0000283 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Anders Carlsson5e300d12009-06-12 16:51:40 +0000285 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Anders Carlsson5e300d12009-06-12 16:51:40 +0000287 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000288}
289
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000290/// CheckExtraCXXDefaultArguments - Check for any extra default
291/// arguments in the declarator, which is not a function declaration
292/// or definition and therefore is not permitted to have default
293/// arguments. This routine should be invoked for every declarator
294/// that is not a function declaration or definition.
295void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
296 // C++ [dcl.fct.default]p3
297 // A default argument expression shall be specified only in the
298 // parameter-declaration-clause of a function declaration or in a
299 // template-parameter (14.1). It shall not be specified for a
300 // parameter pack. If it is specified in a
301 // parameter-declaration-clause, it shall not occur within a
302 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000303 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000304 DeclaratorChunk &chunk = D.getTypeObject(i);
305 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000306 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
307 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000308 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000309 if (Param->hasUnparsedDefaultArg()) {
310 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
312 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
313 delete Toks;
314 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000315 } else if (Param->getDefaultArg()) {
316 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
317 << Param->getDefaultArg()->getSourceRange();
318 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000319 }
320 }
321 }
322 }
323}
324
Chris Lattner3d1cee32008-04-08 05:04:30 +0000325// MergeCXXFunctionDecl - Merge two declarations of the same C++
326// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000327// type. Subroutine of MergeFunctionDecl. Returns true if there was an
328// error, false otherwise.
329bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
330 bool Invalid = false;
331
Chris Lattner3d1cee32008-04-08 05:04:30 +0000332 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000333 // For non-template functions, default arguments can be added in
334 // later declarations of a function in the same
335 // scope. Declarations in different scopes have completely
336 // distinct sets of default arguments. That is, declarations in
337 // inner scopes do not acquire default arguments from
338 // declarations in outer scopes, and vice versa. In a given
339 // function declaration, all parameters subsequent to a
340 // parameter with a default argument shall have default
341 // arguments supplied in this or previous declarations. A
342 // default argument shall not be redefined by a later
343 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000344 //
345 // C++ [dcl.fct.default]p6:
346 // Except for member functions of class templates, the default arguments
347 // in a member function definition that appears outside of the class
348 // definition are added to the set of default arguments provided by the
349 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000350 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
351 ParmVarDecl *OldParam = Old->getParamDecl(p);
352 ParmVarDecl *NewParam = New->getParamDecl(p);
353
Douglas Gregor6cc15182009-09-11 18:44:32 +0000354 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000355
Francois Pichet8d051e02011-04-10 03:03:52 +0000356 unsigned DiagDefaultParamID =
357 diag::err_param_default_argument_redefinition;
358
359 // MSVC accepts that default parameters be redefined for member functions
360 // of template class. The new default parameter's value is ignored.
361 Invalid = true;
362 if (getLangOptions().Microsoft) {
363 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
364 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000365 // Merge the old default argument into the new parameter.
366 NewParam->setHasInheritedDefaultArg();
367 if (OldParam->hasUninstantiatedDefaultArg())
368 NewParam->setUninstantiatedDefaultArg(
369 OldParam->getUninstantiatedDefaultArg());
370 else
371 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000372 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000373 Invalid = false;
374 }
375 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000376
Francois Pichet8cf90492011-04-10 04:58:30 +0000377 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
378 // hint here. Alternatively, we could walk the type-source information
379 // for NewParam to find the last source location in the type... but it
380 // isn't worth the effort right now. This is the kind of test case that
381 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000382 // int f(int);
383 // void g(int (*fp)(int) = f);
384 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000385 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000386 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387
388 // Look for the function declaration where the default argument was
389 // actually written, which may be a declaration prior to Old.
390 for (FunctionDecl *Older = Old->getPreviousDeclaration();
391 Older; Older = Older->getPreviousDeclaration()) {
392 if (!Older->getParamDecl(p)->hasDefaultArg())
393 break;
394
395 OldParam = Older->getParamDecl(p);
396 }
397
398 Diag(OldParam->getLocation(), diag::note_previous_definition)
399 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000400 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000401 // Merge the old default argument into the new parameter.
402 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000403 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000404 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000405 if (OldParam->hasUninstantiatedDefaultArg())
406 NewParam->setUninstantiatedDefaultArg(
407 OldParam->getUninstantiatedDefaultArg());
408 else
John McCall3d6c1782010-05-04 01:53:42 +0000409 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000410 } else if (NewParam->hasDefaultArg()) {
411 if (New->getDescribedFunctionTemplate()) {
412 // Paragraph 4, quoted above, only applies to non-template functions.
413 Diag(NewParam->getLocation(),
414 diag::err_param_default_argument_template_redecl)
415 << NewParam->getDefaultArgRange();
416 Diag(Old->getLocation(), diag::note_template_prev_declaration)
417 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000418 } else if (New->getTemplateSpecializationKind()
419 != TSK_ImplicitInstantiation &&
420 New->getTemplateSpecializationKind() != TSK_Undeclared) {
421 // C++ [temp.expr.spec]p21:
422 // Default function arguments shall not be specified in a declaration
423 // or a definition for one of the following explicit specializations:
424 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000425 // - the explicit specialization of a member function template;
426 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000427 // template where the class template specialization to which the
428 // member function specialization belongs is implicitly
429 // instantiated.
430 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
431 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
432 << New->getDeclName()
433 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000434 } else if (New->getDeclContext()->isDependentContext()) {
435 // C++ [dcl.fct.default]p6 (DR217):
436 // Default arguments for a member function of a class template shall
437 // be specified on the initial declaration of the member function
438 // within the class template.
439 //
440 // Reading the tea leaves a bit in DR217 and its reference to DR205
441 // leads me to the conclusion that one cannot add default function
442 // arguments for an out-of-line definition of a member function of a
443 // dependent type.
444 int WhichKind = 2;
445 if (CXXRecordDecl *Record
446 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
447 if (Record->getDescribedClassTemplate())
448 WhichKind = 0;
449 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
450 WhichKind = 1;
451 else
452 WhichKind = 2;
453 }
454
455 Diag(NewParam->getLocation(),
456 diag::err_param_default_argument_member_template_redecl)
457 << WhichKind
458 << NewParam->getDefaultArgRange();
459 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000460 }
461 }
462
Douglas Gregore13ad832010-02-12 07:32:17 +0000463 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000464 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000465
Douglas Gregorcda9c672009-02-16 17:45:42 +0000466 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000467}
468
Sebastian Redl60618fa2011-03-12 11:50:43 +0000469/// \brief Merge the exception specifications of two variable declarations.
470///
471/// This is called when there's a redeclaration of a VarDecl. The function
472/// checks if the redeclaration might have an exception specification and
473/// validates compatibility and merges the specs if necessary.
474void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
475 // Shortcut if exceptions are disabled.
476 if (!getLangOptions().CXXExceptions)
477 return;
478
479 assert(Context.hasSameType(New->getType(), Old->getType()) &&
480 "Should only be called if types are otherwise the same.");
481
482 QualType NewType = New->getType();
483 QualType OldType = Old->getType();
484
485 // We're only interested in pointers and references to functions, as well
486 // as pointers to member functions.
487 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
488 NewType = R->getPointeeType();
489 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
490 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
491 NewType = P->getPointeeType();
492 OldType = OldType->getAs<PointerType>()->getPointeeType();
493 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
494 NewType = M->getPointeeType();
495 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
496 }
497
498 if (!NewType->isFunctionProtoType())
499 return;
500
501 // There's lots of special cases for functions. For function pointers, system
502 // libraries are hopefully not as broken so that we don't need these
503 // workarounds.
504 if (CheckEquivalentExceptionSpec(
505 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
506 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
507 New->setInvalidDecl();
508 }
509}
510
Chris Lattner3d1cee32008-04-08 05:04:30 +0000511/// CheckCXXDefaultArguments - Verify that the default arguments for a
512/// function declaration are well-formed according to C++
513/// [dcl.fct.default].
514void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
515 unsigned NumParams = FD->getNumParams();
516 unsigned p;
517
518 // Find first parameter with a default argument
519 for (p = 0; p < NumParams; ++p) {
520 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000521 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000522 break;
523 }
524
525 // C++ [dcl.fct.default]p4:
526 // In a given function declaration, all parameters
527 // subsequent to a parameter with a default argument shall
528 // have default arguments supplied in this or previous
529 // declarations. A default argument shall not be redefined
530 // by a later declaration (not even to the same value).
531 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000532 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000533 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000534 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000535 if (Param->isInvalidDecl())
536 /* We already complained about this parameter. */;
537 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000538 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000539 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000540 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000541 else
Mike Stump1eb44332009-09-09 15:08:12 +0000542 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000543 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner3d1cee32008-04-08 05:04:30 +0000545 LastMissingDefaultArg = p;
546 }
547 }
548
549 if (LastMissingDefaultArg > 0) {
550 // Some default arguments were missing. Clear out all of the
551 // default arguments up to (and including) the last missing
552 // default argument, so that we leave the function parameters
553 // in a semantically valid state.
554 for (p = 0; p <= LastMissingDefaultArg; ++p) {
555 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000556 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000557 Param->setDefaultArg(0);
558 }
559 }
560 }
561}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000562
Douglas Gregorb48fe382008-10-31 09:07:45 +0000563/// isCurrentClassName - Determine whether the identifier II is the
564/// name of the class type currently being defined. In the case of
565/// nested classes, this will only return true if II is the name of
566/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000567bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
568 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000569 assert(getLangOptions().CPlusPlus && "No class names in C!");
570
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000571 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000572 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000573 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000574 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
575 } else
576 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
577
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000578 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000579 return &II == CurDecl->getIdentifier();
580 else
581 return false;
582}
583
Mike Stump1eb44332009-09-09 15:08:12 +0000584/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000585///
586/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
587/// and returns NULL otherwise.
588CXXBaseSpecifier *
589Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
590 SourceRange SpecifierRange,
591 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000592 TypeSourceInfo *TInfo,
593 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000594 QualType BaseType = TInfo->getType();
595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 // C++ [class.union]p1:
597 // A union shall not have base classes.
598 if (Class->isUnion()) {
599 Diag(Class->getLocation(), diag::err_base_clause_on_union)
600 << SpecifierRange;
601 return 0;
602 }
603
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000604 if (EllipsisLoc.isValid() &&
605 !TInfo->getType()->containsUnexpandedParameterPack()) {
606 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
607 << TInfo->getTypeLoc().getSourceRange();
608 EllipsisLoc = SourceLocation();
609 }
610
Douglas Gregor2943aed2009-03-03 04:44:36 +0000611 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000612 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000613 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000614 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000615
616 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617
618 // Base specifiers must be record types.
619 if (!BaseType->isRecordType()) {
620 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
621 return 0;
622 }
623
624 // C++ [class.union]p1:
625 // A union shall not be used as a base class.
626 if (BaseType->isUnionType()) {
627 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
628 return 0;
629 }
630
631 // C++ [class.derived]p2:
632 // The class-name in a base-specifier shall not be an incompletely
633 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000634 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000635 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000636 << SpecifierRange)) {
637 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 return 0;
John McCall572fc622010-08-17 07:23:57 +0000639 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000640
Eli Friedman1d954f62009-08-15 21:55:26 +0000641 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000642 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000643 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000644 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000645 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000646 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
647 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000648
Anders Carlsson1d209272011-03-25 14:55:14 +0000649 // C++ [class]p3:
650 // If a class is marked final and it appears as a base-type-specifier in
651 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000652 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000653 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
654 << CXXBaseDecl->getDeclName();
655 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
656 << CXXBaseDecl->getDeclName();
657 return 0;
658 }
659
John McCall572fc622010-08-17 07:23:57 +0000660 if (BaseDecl->isInvalidDecl())
661 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000662
663 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000664 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000665 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000666 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000667}
668
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000669/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
670/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000671/// example:
672/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000673/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000674BaseResult
John McCalld226f652010-08-21 09:40:31 +0000675Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000676 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000677 ParsedType basetype, SourceLocation BaseLoc,
678 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000679 if (!classdecl)
680 return true;
681
Douglas Gregor40808ce2009-03-09 23:48:35 +0000682 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000683 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000684 if (!Class)
685 return true;
686
Nick Lewycky56062202010-07-26 16:56:01 +0000687 TypeSourceInfo *TInfo = 0;
688 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000689
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000690 if (EllipsisLoc.isInvalid() &&
691 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000692 UPPC_BaseType))
693 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000694
Douglas Gregor2943aed2009-03-03 04:44:36 +0000695 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000696 Virtual, Access, TInfo,
697 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000698 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Douglas Gregor2943aed2009-03-03 04:44:36 +0000700 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000701}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000702
Douglas Gregor2943aed2009-03-03 04:44:36 +0000703/// \brief Performs the actual work of attaching the given base class
704/// specifiers to a C++ class.
705bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
706 unsigned NumBases) {
707 if (NumBases == 0)
708 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000709
710 // Used to keep track of which base types we have already seen, so
711 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000712 // that the key is always the unqualified canonical type of the base
713 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000714 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
715
716 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000717 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000718 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000719 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000720 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000721 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000722 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000723 if (!Class->hasObjectMember()) {
724 if (const RecordType *FDTTy =
725 NewBaseType.getTypePtr()->getAs<RecordType>())
726 if (FDTTy->getDecl()->hasObjectMember())
727 Class->setHasObjectMember(true);
728 }
729
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000730 if (KnownBaseTypes[NewBaseType]) {
731 // C++ [class.mi]p3:
732 // A class shall not be specified as a direct base class of a
733 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000734 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000735 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000736 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000737 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000738
739 // Delete the duplicate base class specifier; we're going to
740 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000741 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000742
743 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000744 } else {
745 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000746 KnownBaseTypes[NewBaseType] = Bases[idx];
747 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000748 }
749 }
750
751 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000752 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000753
754 // Delete the remaining (good) base class specifiers, since their
755 // data has been copied into the CXXRecordDecl.
756 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000757 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000758
759 return Invalid;
760}
761
762/// ActOnBaseSpecifiers - Attach the given base specifiers to the
763/// class, after checking whether there are any duplicate base
764/// classes.
John McCalld226f652010-08-21 09:40:31 +0000765void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000766 unsigned NumBases) {
767 if (!ClassDecl || !Bases || !NumBases)
768 return;
769
770 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000771 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000772 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000773}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000774
John McCall3cb0ebd2010-03-10 03:28:59 +0000775static CXXRecordDecl *GetClassForType(QualType T) {
776 if (const RecordType *RT = T->getAs<RecordType>())
777 return cast<CXXRecordDecl>(RT->getDecl());
778 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
779 return ICT->getDecl();
780 else
781 return 0;
782}
783
Douglas Gregora8f32e02009-10-06 17:59:45 +0000784/// \brief Determine whether the type \p Derived is a C++ class that is
785/// derived from the type \p Base.
786bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
787 if (!getLangOptions().CPlusPlus)
788 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000789
790 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
791 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000792 return false;
793
John McCall3cb0ebd2010-03-10 03:28:59 +0000794 CXXRecordDecl *BaseRD = GetClassForType(Base);
795 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000796 return false;
797
John McCall86ff3082010-02-04 22:26:26 +0000798 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
799 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000800}
801
802/// \brief Determine whether the type \p Derived is a C++ class that is
803/// derived from the type \p Base.
804bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
805 if (!getLangOptions().CPlusPlus)
806 return false;
807
John McCall3cb0ebd2010-03-10 03:28:59 +0000808 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
809 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000810 return false;
811
John McCall3cb0ebd2010-03-10 03:28:59 +0000812 CXXRecordDecl *BaseRD = GetClassForType(Base);
813 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000814 return false;
815
Douglas Gregora8f32e02009-10-06 17:59:45 +0000816 return DerivedRD->isDerivedFrom(BaseRD, Paths);
817}
818
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000819void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000820 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000821 assert(BasePathArray.empty() && "Base path array must be empty!");
822 assert(Paths.isRecordingPaths() && "Must record paths!");
823
824 const CXXBasePath &Path = Paths.front();
825
826 // We first go backward and check if we have a virtual base.
827 // FIXME: It would be better if CXXBasePath had the base specifier for
828 // the nearest virtual base.
829 unsigned Start = 0;
830 for (unsigned I = Path.size(); I != 0; --I) {
831 if (Path[I - 1].Base->isVirtual()) {
832 Start = I - 1;
833 break;
834 }
835 }
836
837 // Now add all bases.
838 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000839 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000840}
841
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000842/// \brief Determine whether the given base path includes a virtual
843/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000844bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
845 for (CXXCastPath::const_iterator B = BasePath.begin(),
846 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000847 B != BEnd; ++B)
848 if ((*B)->isVirtual())
849 return true;
850
851 return false;
852}
853
Douglas Gregora8f32e02009-10-06 17:59:45 +0000854/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
855/// conversion (where Derived and Base are class types) is
856/// well-formed, meaning that the conversion is unambiguous (and
857/// that all of the base classes are accessible). Returns true
858/// and emits a diagnostic if the code is ill-formed, returns false
859/// otherwise. Loc is the location where this routine should point to
860/// if there is an error, and Range is the source range to highlight
861/// if there is an error.
862bool
863Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000864 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000865 unsigned AmbigiousBaseConvID,
866 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000867 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000868 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000869 // First, determine whether the path from Derived to Base is
870 // ambiguous. This is slightly more expensive than checking whether
871 // the Derived to Base conversion exists, because here we need to
872 // explore multiple paths to determine if there is an ambiguity.
873 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
874 /*DetectVirtual=*/false);
875 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
876 assert(DerivationOkay &&
877 "Can only be used with a derived-to-base conversion");
878 (void)DerivationOkay;
879
880 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000881 if (InaccessibleBaseID) {
882 // Check that the base class can be accessed.
883 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
884 InaccessibleBaseID)) {
885 case AR_inaccessible:
886 return true;
887 case AR_accessible:
888 case AR_dependent:
889 case AR_delayed:
890 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000891 }
John McCall6b2accb2010-02-10 09:31:12 +0000892 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000893
894 // Build a base path if necessary.
895 if (BasePath)
896 BuildBasePathArray(Paths, *BasePath);
897 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000898 }
899
900 // We know that the derived-to-base conversion is ambiguous, and
901 // we're going to produce a diagnostic. Perform the derived-to-base
902 // search just one more time to compute all of the possible paths so
903 // that we can print them out. This is more expensive than any of
904 // the previous derived-to-base checks we've done, but at this point
905 // performance isn't as much of an issue.
906 Paths.clear();
907 Paths.setRecordingPaths(true);
908 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
909 assert(StillOkay && "Can only be used with a derived-to-base conversion");
910 (void)StillOkay;
911
912 // Build up a textual representation of the ambiguous paths, e.g.,
913 // D -> B -> A, that will be used to illustrate the ambiguous
914 // conversions in the diagnostic. We only print one of the paths
915 // to each base class subobject.
916 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
917
918 Diag(Loc, AmbigiousBaseConvID)
919 << Derived << Base << PathDisplayStr << Range << Name;
920 return true;
921}
922
923bool
924Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000925 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000926 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000927 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000928 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000929 IgnoreAccess ? 0
930 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000931 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000932 Loc, Range, DeclarationName(),
933 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000934}
935
936
937/// @brief Builds a string representing ambiguous paths from a
938/// specific derived class to different subobjects of the same base
939/// class.
940///
941/// This function builds a string that can be used in error messages
942/// to show the different paths that one can take through the
943/// inheritance hierarchy to go from the derived class to different
944/// subobjects of a base class. The result looks something like this:
945/// @code
946/// struct D -> struct B -> struct A
947/// struct D -> struct C -> struct A
948/// @endcode
949std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
950 std::string PathDisplayStr;
951 std::set<unsigned> DisplayedPaths;
952 for (CXXBasePaths::paths_iterator Path = Paths.begin();
953 Path != Paths.end(); ++Path) {
954 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
955 // We haven't displayed a path to this particular base
956 // class subobject yet.
957 PathDisplayStr += "\n ";
958 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
959 for (CXXBasePath::const_iterator Element = Path->begin();
960 Element != Path->end(); ++Element)
961 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
962 }
963 }
964
965 return PathDisplayStr;
966}
967
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000968//===----------------------------------------------------------------------===//
969// C++ class member Handling
970//===----------------------------------------------------------------------===//
971
Abramo Bagnara6206d532010-06-05 05:09:32 +0000972/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000973Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
974 SourceLocation ASLoc,
975 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000976 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000977 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000978 ASLoc, ColonLoc);
979 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000980 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000981}
982
Anders Carlsson9e682d92011-01-20 05:57:14 +0000983/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000984void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000985 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
986 if (!MD || !MD->isVirtual())
987 return;
988
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000989 if (MD->isDependentContext())
990 return;
991
Anders Carlsson9e682d92011-01-20 05:57:14 +0000992 // C++0x [class.virtual]p3:
993 // If a virtual function is marked with the virt-specifier override and does
994 // not override a member function of a base class,
995 // the program is ill-formed.
996 bool HasOverriddenMethods =
997 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000998 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000999 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001000 diag::err_function_marked_override_not_overriding)
1001 << MD->getDeclName();
1002 return;
1003 }
1004}
1005
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001006/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1007/// function overrides a virtual member function marked 'final', according to
1008/// C++0x [class.virtual]p3.
1009bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1010 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001011 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001012 return false;
1013
1014 Diag(New->getLocation(), diag::err_final_function_overridden)
1015 << New->getDeclName();
1016 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1017 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001018}
1019
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001020/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1021/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1022/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +00001023/// any.
John McCalld226f652010-08-21 09:40:31 +00001024Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001025Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001026 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +00001027 ExprTy *BW, const VirtSpecifiers &VS,
Sean Hunte4246a62011-05-12 06:15:49 +00001028 ExprTy *InitExpr, bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001029 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001030 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1031 DeclarationName Name = NameInfo.getName();
1032 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001033
1034 // For anonymous bitfields, the location should point to the type.
1035 if (Loc.isInvalid())
1036 Loc = D.getSourceRange().getBegin();
1037
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001038 Expr *BitWidth = static_cast<Expr*>(BW);
1039 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001040
John McCall4bde1e12010-06-04 08:34:12 +00001041 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001042 assert(!DS.isFriendSpecified());
1043
John McCall4bde1e12010-06-04 08:34:12 +00001044 bool isFunc = false;
1045 if (D.isFunctionDeclarator())
1046 isFunc = true;
1047 else if (D.getNumTypeObjects() == 0 &&
1048 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +00001049 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +00001050 isFunc = TDType->isFunctionType();
1051 }
1052
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001053 // C++ 9.2p6: A member shall not be declared to have automatic storage
1054 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001055 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1056 // data members and cannot be applied to names declared const or static,
1057 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001058 switch (DS.getStorageClassSpec()) {
1059 case DeclSpec::SCS_unspecified:
1060 case DeclSpec::SCS_typedef:
1061 case DeclSpec::SCS_static:
1062 // FALL THROUGH.
1063 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001064 case DeclSpec::SCS_mutable:
1065 if (isFunc) {
1066 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001067 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001068 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001069 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Sebastian Redla11f42f2008-11-17 23:24:37 +00001071 // FIXME: It would be nicer if the keyword was ignored only for this
1072 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001073 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001074 }
1075 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001076 default:
1077 if (DS.getStorageClassSpecLoc().isValid())
1078 Diag(DS.getStorageClassSpecLoc(),
1079 diag::err_storageclass_invalid_for_member);
1080 else
1081 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1082 D.getMutableDeclSpec().ClearStorageClassSpecs();
1083 }
1084
Sebastian Redl669d5d72008-11-14 23:42:31 +00001085 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1086 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001087 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001088
1089 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001090 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001091 CXXScopeSpec &SS = D.getCXXScopeSpec();
1092
Douglas Gregor922fff22010-10-13 22:19:53 +00001093 if (SS.isSet() && !SS.isInvalid()) {
1094 // The user provided a superfluous scope specifier inside a class
1095 // definition:
1096 //
1097 // class X {
1098 // int X::member;
1099 // };
1100 DeclContext *DC = 0;
1101 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1102 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1103 << Name << FixItHint::CreateRemoval(SS.getRange());
1104 else
1105 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1106 << Name << SS.getRange();
1107
1108 SS.clear();
1109 }
1110
Douglas Gregor37b372b2009-08-20 22:52:58 +00001111 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001112 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001113 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1114 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001115 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001116 } else {
Sean Hunte4246a62011-05-12 06:15:49 +00001117 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001118 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001119 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001120 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001121
1122 // Non-instance-fields can't have a bitfield.
1123 if (BitWidth) {
1124 if (Member->isInvalidDecl()) {
1125 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001126 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001127 // C++ 9.6p3: A bit-field shall not be a static member.
1128 // "static member 'A' cannot be a bit-field"
1129 Diag(Loc, diag::err_static_not_bitfield)
1130 << Name << BitWidth->getSourceRange();
1131 } else if (isa<TypedefDecl>(Member)) {
1132 // "typedef member 'x' cannot be a bit-field"
1133 Diag(Loc, diag::err_typedef_not_bitfield)
1134 << Name << BitWidth->getSourceRange();
1135 } else {
1136 // A function typedef ("typedef int f(); f a;").
1137 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1138 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001139 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001140 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001141 }
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Chris Lattner8b963ef2009-03-05 23:01:03 +00001143 BitWidth = 0;
1144 Member->setInvalidDecl();
1145 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001146
1147 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Douglas Gregor37b372b2009-08-20 22:52:58 +00001149 // If we have declared a member function template, set the access of the
1150 // templated declaration as well.
1151 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1152 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001153 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001154
Anders Carlssonaae5af22011-01-20 04:34:22 +00001155 if (VS.isOverrideSpecified()) {
1156 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1157 if (!MD || !MD->isVirtual()) {
1158 Diag(Member->getLocStart(),
1159 diag::override_keyword_only_allowed_on_virtual_member_functions)
1160 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001161 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001162 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001163 }
1164 if (VS.isFinalSpecified()) {
1165 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1166 if (!MD || !MD->isVirtual()) {
1167 Diag(Member->getLocStart(),
1168 diag::override_keyword_only_allowed_on_virtual_member_functions)
1169 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001170 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001171 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001172 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001173
Douglas Gregorf5251602011-03-08 17:10:18 +00001174 if (VS.getLastLocation().isValid()) {
1175 // Update the end location of a method that has a virt-specifiers.
1176 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1177 MD->setRangeEnd(VS.getLastLocation());
1178 }
1179
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001180 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001181
Douglas Gregor10bd3682008-11-17 22:58:34 +00001182 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001183
Douglas Gregor021c3b32009-03-11 23:00:04 +00001184 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001185 AddInitializerToDecl(Member, Init, false,
1186 DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001187
Richard Smith483b9f32011-02-21 20:05:19 +00001188 FinalizeDeclaration(Member);
1189
John McCallb25b2952011-02-15 07:12:36 +00001190 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001191 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001192 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001193}
1194
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001195/// \brief Find the direct and/or virtual base specifiers that
1196/// correspond to the given base type, for use in base initialization
1197/// within a constructor.
1198static bool FindBaseInitializer(Sema &SemaRef,
1199 CXXRecordDecl *ClassDecl,
1200 QualType BaseType,
1201 const CXXBaseSpecifier *&DirectBaseSpec,
1202 const CXXBaseSpecifier *&VirtualBaseSpec) {
1203 // First, check for a direct base class.
1204 DirectBaseSpec = 0;
1205 for (CXXRecordDecl::base_class_const_iterator Base
1206 = ClassDecl->bases_begin();
1207 Base != ClassDecl->bases_end(); ++Base) {
1208 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1209 // We found a direct base of this type. That's what we're
1210 // initializing.
1211 DirectBaseSpec = &*Base;
1212 break;
1213 }
1214 }
1215
1216 // Check for a virtual base class.
1217 // FIXME: We might be able to short-circuit this if we know in advance that
1218 // there are no virtual bases.
1219 VirtualBaseSpec = 0;
1220 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1221 // We haven't found a base yet; search the class hierarchy for a
1222 // virtual base class.
1223 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1224 /*DetectVirtual=*/false);
1225 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1226 BaseType, Paths)) {
1227 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1228 Path != Paths.end(); ++Path) {
1229 if (Path->back().Base->isVirtual()) {
1230 VirtualBaseSpec = Path->back().Base;
1231 break;
1232 }
1233 }
1234 }
1235 }
1236
1237 return DirectBaseSpec || VirtualBaseSpec;
1238}
1239
Douglas Gregor7ad83902008-11-05 04:29:56 +00001240/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001241MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001242Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001243 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001244 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001245 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001246 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001247 SourceLocation IdLoc,
1248 SourceLocation LParenLoc,
1249 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001250 SourceLocation RParenLoc,
1251 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001252 if (!ConstructorD)
1253 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001255 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001256
1257 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001258 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001259 if (!Constructor) {
1260 // The user wrote a constructor initializer on a function that is
1261 // not a C++ constructor. Ignore the error for now, because we may
1262 // have more member initializers coming; we'll diagnose it just
1263 // once in ActOnMemInitializers.
1264 return true;
1265 }
1266
1267 CXXRecordDecl *ClassDecl = Constructor->getParent();
1268
1269 // C++ [class.base.init]p2:
1270 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001271 // constructor's class and, if not found in that scope, are looked
1272 // up in the scope containing the constructor's definition.
1273 // [Note: if the constructor's class contains a member with the
1274 // same name as a direct or virtual base class of the class, a
1275 // mem-initializer-id naming the member or base class and composed
1276 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001277 // mem-initializer-id for the hidden base class may be specified
1278 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001279 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001280 // Look for a member, first.
1281 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001282 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001283 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001284 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001285 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001286
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001287 if (Member) {
1288 if (EllipsisLoc.isValid())
1289 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1290 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1291
Francois Pichet00eb3f92010-12-04 09:14:42 +00001292 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001293 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001294 }
1295
Francois Pichet00eb3f92010-12-04 09:14:42 +00001296 // Handle anonymous union case.
1297 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001298 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1299 if (EllipsisLoc.isValid())
1300 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1301 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1302
Francois Pichet00eb3f92010-12-04 09:14:42 +00001303 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1304 NumArgs, IdLoc,
1305 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001306 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001307 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001308 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001309 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001310 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001311 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001312
1313 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001314 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001315 } else {
1316 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1317 LookupParsedName(R, S, &SS);
1318
1319 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1320 if (!TyD) {
1321 if (R.isAmbiguous()) return true;
1322
John McCallfd225442010-04-09 19:01:14 +00001323 // We don't want access-control diagnostics here.
1324 R.suppressDiagnostics();
1325
Douglas Gregor7a886e12010-01-19 06:46:48 +00001326 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1327 bool NotUnknownSpecialization = false;
1328 DeclContext *DC = computeDeclContext(SS, false);
1329 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1330 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1331
1332 if (!NotUnknownSpecialization) {
1333 // When the scope specifier can refer to a member of an unknown
1334 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001335 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1336 SS.getWithLocInContext(Context),
1337 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001338 if (BaseType.isNull())
1339 return true;
1340
Douglas Gregor7a886e12010-01-19 06:46:48 +00001341 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001342 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001343 }
1344 }
1345
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001346 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001347 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001348 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1349 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001350 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001351 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001352 // We have found a non-static data member with a similar
1353 // name to what was typed; complain and initialize that
1354 // member.
1355 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1356 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001357 << FixItHint::CreateReplacement(R.getNameLoc(),
1358 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001359 Diag(Member->getLocation(), diag::note_previous_decl)
1360 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001361
1362 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1363 LParenLoc, RParenLoc);
1364 }
1365 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1366 const CXXBaseSpecifier *DirectBaseSpec;
1367 const CXXBaseSpecifier *VirtualBaseSpec;
1368 if (FindBaseInitializer(*this, ClassDecl,
1369 Context.getTypeDeclType(Type),
1370 DirectBaseSpec, VirtualBaseSpec)) {
1371 // We have found a direct or virtual base class with a
1372 // similar name to what was typed; complain and initialize
1373 // that base class.
1374 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1375 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001376 << FixItHint::CreateReplacement(R.getNameLoc(),
1377 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001378
1379 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1380 : VirtualBaseSpec;
1381 Diag(BaseSpec->getSourceRange().getBegin(),
1382 diag::note_base_class_specified_here)
1383 << BaseSpec->getType()
1384 << BaseSpec->getSourceRange();
1385
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001386 TyD = Type;
1387 }
1388 }
1389 }
1390
Douglas Gregor7a886e12010-01-19 06:46:48 +00001391 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001392 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1393 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1394 return true;
1395 }
John McCall2b194412009-12-21 10:41:20 +00001396 }
1397
Douglas Gregor7a886e12010-01-19 06:46:48 +00001398 if (BaseType.isNull()) {
1399 BaseType = Context.getTypeDeclType(TyD);
1400 if (SS.isSet()) {
1401 NestedNameSpecifier *Qualifier =
1402 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001403
Douglas Gregor7a886e12010-01-19 06:46:48 +00001404 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001405 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001406 }
John McCall2b194412009-12-21 10:41:20 +00001407 }
1408 }
Mike Stump1eb44332009-09-09 15:08:12 +00001409
John McCalla93c9342009-12-07 02:54:59 +00001410 if (!TInfo)
1411 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001412
John McCalla93c9342009-12-07 02:54:59 +00001413 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001414 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001415}
1416
John McCallb4190042009-11-04 23:02:40 +00001417/// Checks an initializer expression for use of uninitialized fields, such as
1418/// containing the field that is being initialized. Returns true if there is an
1419/// uninitialized field was used an updates the SourceLocation parameter; false
1420/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001421static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001422 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001423 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001424 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1425
Nick Lewycky43ad1822010-06-15 07:32:55 +00001426 if (isa<CallExpr>(S)) {
1427 // Do not descend into function calls or constructors, as the use
1428 // of an uninitialized field may be valid. One would have to inspect
1429 // the contents of the function/ctor to determine if it is safe or not.
1430 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1431 // may be safe, depending on what the function/ctor does.
1432 return false;
1433 }
1434 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1435 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001436
1437 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1438 // The member expression points to a static data member.
1439 assert(VD->isStaticDataMember() &&
1440 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001441 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001442 return false;
1443 }
1444
1445 if (isa<EnumConstantDecl>(RhsField)) {
1446 // The member expression points to an enum.
1447 return false;
1448 }
1449
John McCallb4190042009-11-04 23:02:40 +00001450 if (RhsField == LhsField) {
1451 // Initializing a field with itself. Throw a warning.
1452 // But wait; there are exceptions!
1453 // Exception #1: The field may not belong to this record.
1454 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001455 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001456 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1457 // Even though the field matches, it does not belong to this record.
1458 return false;
1459 }
1460 // None of the exceptions triggered; return true to indicate an
1461 // uninitialized field was used.
1462 *L = ME->getMemberLoc();
1463 return true;
1464 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001465 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001466 // sizeof/alignof doesn't reference contents, do not warn.
1467 return false;
1468 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1469 // address-of doesn't reference contents (the pointer may be dereferenced
1470 // in the same expression but it would be rare; and weird).
1471 if (UOE->getOpcode() == UO_AddrOf)
1472 return false;
John McCallb4190042009-11-04 23:02:40 +00001473 }
John McCall7502c1d2011-02-13 04:07:26 +00001474 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001475 if (!*it) {
1476 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001477 continue;
1478 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001479 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1480 return true;
John McCallb4190042009-11-04 23:02:40 +00001481 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001482 return false;
John McCallb4190042009-11-04 23:02:40 +00001483}
1484
John McCallf312b1e2010-08-26 23:41:50 +00001485MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001486Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001487 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001488 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001489 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001490 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1491 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1492 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001493 "Member must be a FieldDecl or IndirectFieldDecl");
1494
Douglas Gregor464b2f02010-11-05 22:21:31 +00001495 if (Member->isInvalidDecl())
1496 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001497
John McCallb4190042009-11-04 23:02:40 +00001498 // Diagnose value-uses of fields to initialize themselves, e.g.
1499 // foo(foo)
1500 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001501 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001502 for (unsigned i = 0; i < NumArgs; ++i) {
1503 SourceLocation L;
1504 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1505 // FIXME: Return true in the case when other fields are used before being
1506 // uninitialized. For example, let this field be the i'th field. When
1507 // initializing the i'th field, throw a warning if any of the >= i'th
1508 // fields are used, as they are not yet initialized.
1509 // Right now we are only handling the case where the i'th field uses
1510 // itself in its initializer.
1511 Diag(L, diag::warn_field_is_uninit);
1512 }
1513 }
1514
Eli Friedman59c04372009-07-29 19:44:27 +00001515 bool HasDependentArg = false;
1516 for (unsigned i = 0; i < NumArgs; i++)
1517 HasDependentArg |= Args[i]->isTypeDependent();
1518
Chandler Carruth894aed92010-12-06 09:23:57 +00001519 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001520 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001521 // Can't check initialization for a member of dependent type or when
1522 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001523 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1524 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001525
1526 // Erase any temporaries within this evaluation context; we're not
1527 // going to track them in the AST, since we'll be rebuilding the
1528 // ASTs during template instantiation.
1529 ExprTemporaries.erase(
1530 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1531 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001532 } else {
1533 // Initialize the member.
1534 InitializedEntity MemberEntity =
1535 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1536 : InitializedEntity::InitializeMember(IndirectMember, 0);
1537 InitializationKind Kind =
1538 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001539
Chandler Carruth894aed92010-12-06 09:23:57 +00001540 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1541
1542 ExprResult MemberInit =
1543 InitSeq.Perform(*this, MemberEntity, Kind,
1544 MultiExprArg(*this, Args, NumArgs), 0);
1545 if (MemberInit.isInvalid())
1546 return true;
1547
1548 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1549
1550 // C++0x [class.base.init]p7:
1551 // The initialization of each base and member constitutes a
1552 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001553 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001554 if (MemberInit.isInvalid())
1555 return true;
1556
1557 // If we are in a dependent context, template instantiation will
1558 // perform this type-checking again. Just save the arguments that we
1559 // received in a ParenListExpr.
1560 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1561 // of the information that we have about the member
1562 // initializer. However, deconstructing the ASTs is a dicey process,
1563 // and this approach is far more likely to get the corner cases right.
1564 if (CurContext->isDependentContext())
1565 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1566 RParenLoc);
1567 else
1568 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001569 }
1570
Chandler Carruth894aed92010-12-06 09:23:57 +00001571 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001572 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001573 IdLoc, LParenLoc, Init,
1574 RParenLoc);
1575 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001576 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001577 IdLoc, LParenLoc, Init,
1578 RParenLoc);
1579 }
Eli Friedman59c04372009-07-29 19:44:27 +00001580}
1581
John McCallf312b1e2010-08-26 23:41:50 +00001582MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001583Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1584 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001585 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001586 SourceLocation LParenLoc,
1587 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001588 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001589 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1590 if (!LangOpts.CPlusPlus0x)
1591 return Diag(Loc, diag::err_delegation_0x_only)
1592 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001593
Sean Hunt41717662011-02-26 19:13:13 +00001594 // Initialize the object.
1595 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1596 QualType(ClassDecl->getTypeForDecl(), 0));
1597 InitializationKind Kind =
1598 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1599
1600 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1601
1602 ExprResult DelegationInit =
1603 InitSeq.Perform(*this, DelegationEntity, Kind,
1604 MultiExprArg(*this, Args, NumArgs), 0);
1605 if (DelegationInit.isInvalid())
1606 return true;
1607
1608 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001609 CXXConstructorDecl *Constructor
1610 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001611 assert(Constructor && "Delegating constructor with no target?");
1612
1613 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1614
1615 // C++0x [class.base.init]p7:
1616 // The initialization of each base and member constitutes a
1617 // full-expression.
1618 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1619 if (DelegationInit.isInvalid())
1620 return true;
1621
1622 // If we are in a dependent context, template instantiation will
1623 // perform this type-checking again. Just save the arguments that we
1624 // received in a ParenListExpr.
1625 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1626 // of the information that we have about the base
1627 // initializer. However, deconstructing the ASTs is a dicey process,
1628 // and this approach is far more likely to get the corner cases right.
1629 if (CurContext->isDependentContext()) {
1630 ExprResult Init
1631 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1632 NumArgs, RParenLoc));
1633 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1634 Constructor, Init.takeAs<Expr>(),
1635 RParenLoc);
1636 }
1637
1638 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1639 DelegationInit.takeAs<Expr>(),
1640 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001641}
1642
1643MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001644Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001645 Expr **Args, unsigned NumArgs,
1646 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001647 CXXRecordDecl *ClassDecl,
1648 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001649 bool HasDependentArg = false;
1650 for (unsigned i = 0; i < NumArgs; i++)
1651 HasDependentArg |= Args[i]->isTypeDependent();
1652
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001653 SourceLocation BaseLoc
1654 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1655
1656 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1657 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1658 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1659
1660 // C++ [class.base.init]p2:
1661 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001662 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001663 // of that class, the mem-initializer is ill-formed. A
1664 // mem-initializer-list can initialize a base class using any
1665 // name that denotes that base class type.
1666 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1667
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001668 if (EllipsisLoc.isValid()) {
1669 // This is a pack expansion.
1670 if (!BaseType->containsUnexpandedParameterPack()) {
1671 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1672 << SourceRange(BaseLoc, RParenLoc);
1673
1674 EllipsisLoc = SourceLocation();
1675 }
1676 } else {
1677 // Check for any unexpanded parameter packs.
1678 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1679 return true;
1680
1681 for (unsigned I = 0; I != NumArgs; ++I)
1682 if (DiagnoseUnexpandedParameterPack(Args[I]))
1683 return true;
1684 }
1685
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001686 // Check for direct and virtual base classes.
1687 const CXXBaseSpecifier *DirectBaseSpec = 0;
1688 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1689 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001690 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1691 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001692 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1693 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001694
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001695 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1696 VirtualBaseSpec);
1697
1698 // C++ [base.class.init]p2:
1699 // Unless the mem-initializer-id names a nonstatic data member of the
1700 // constructor's class or a direct or virtual base of that class, the
1701 // mem-initializer is ill-formed.
1702 if (!DirectBaseSpec && !VirtualBaseSpec) {
1703 // If the class has any dependent bases, then it's possible that
1704 // one of those types will resolve to the same type as
1705 // BaseType. Therefore, just treat this as a dependent base
1706 // class initialization. FIXME: Should we try to check the
1707 // initialization anyway? It seems odd.
1708 if (ClassDecl->hasAnyDependentBases())
1709 Dependent = true;
1710 else
1711 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1712 << BaseType << Context.getTypeDeclType(ClassDecl)
1713 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1714 }
1715 }
1716
1717 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001718 // Can't check initialization for a base of dependent type or when
1719 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001720 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001721 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1722 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001723
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001724 // Erase any temporaries within this evaluation context; we're not
1725 // going to track them in the AST, since we'll be rebuilding the
1726 // ASTs during template instantiation.
1727 ExprTemporaries.erase(
1728 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1729 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Sean Huntcbb67482011-01-08 20:30:50 +00001731 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001732 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001733 LParenLoc,
1734 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001735 RParenLoc,
1736 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001737 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001738
1739 // C++ [base.class.init]p2:
1740 // If a mem-initializer-id is ambiguous because it designates both
1741 // a direct non-virtual base class and an inherited virtual base
1742 // class, the mem-initializer is ill-formed.
1743 if (DirectBaseSpec && VirtualBaseSpec)
1744 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001745 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001746
1747 CXXBaseSpecifier *BaseSpec
1748 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1749 if (!BaseSpec)
1750 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1751
1752 // Initialize the base.
1753 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001754 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001755 InitializationKind Kind =
1756 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1757
1758 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1759
John McCall60d7b3a2010-08-24 06:29:42 +00001760 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001761 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001762 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001763 if (BaseInit.isInvalid())
1764 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001765
1766 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001767
1768 // C++0x [class.base.init]p7:
1769 // The initialization of each base and member constitutes a
1770 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001771 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001772 if (BaseInit.isInvalid())
1773 return true;
1774
1775 // If we are in a dependent context, template instantiation will
1776 // perform this type-checking again. Just save the arguments that we
1777 // received in a ParenListExpr.
1778 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1779 // of the information that we have about the base
1780 // initializer. However, deconstructing the ASTs is a dicey process,
1781 // and this approach is far more likely to get the corner cases right.
1782 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001783 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001784 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1785 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001786 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001787 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001788 LParenLoc,
1789 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001790 RParenLoc,
1791 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001792 }
1793
Sean Huntcbb67482011-01-08 20:30:50 +00001794 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001795 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001796 LParenLoc,
1797 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001798 RParenLoc,
1799 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001800}
1801
Anders Carlssone5ef7402010-04-23 03:10:23 +00001802/// ImplicitInitializerKind - How an implicit base or member initializer should
1803/// initialize its base or member.
1804enum ImplicitInitializerKind {
1805 IIK_Default,
1806 IIK_Copy,
1807 IIK_Move
1808};
1809
Anders Carlssondefefd22010-04-23 02:00:02 +00001810static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001811BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001812 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001813 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001814 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001815 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001816 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001817 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1818 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001819
John McCall60d7b3a2010-08-24 06:29:42 +00001820 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001821
1822 switch (ImplicitInitKind) {
1823 case IIK_Default: {
1824 InitializationKind InitKind
1825 = InitializationKind::CreateDefault(Constructor->getLocation());
1826 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1827 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001828 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001829 break;
1830 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001831
Anders Carlssone5ef7402010-04-23 03:10:23 +00001832 case IIK_Copy: {
1833 ParmVarDecl *Param = Constructor->getParamDecl(0);
1834 QualType ParamType = Param->getType().getNonReferenceType();
1835
1836 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001837 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001838 Constructor->getLocation(), ParamType,
1839 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001840
Anders Carlssonc7957502010-04-24 22:02:54 +00001841 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001842 QualType ArgTy =
1843 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1844 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001845
1846 CXXCastPath BasePath;
1847 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001848 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1849 CK_UncheckedDerivedToBase,
1850 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001851
Anders Carlssone5ef7402010-04-23 03:10:23 +00001852 InitializationKind InitKind
1853 = InitializationKind::CreateDirect(Constructor->getLocation(),
1854 SourceLocation(), SourceLocation());
1855 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1856 &CopyCtorArg, 1);
1857 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001858 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001859 break;
1860 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001861
Anders Carlssone5ef7402010-04-23 03:10:23 +00001862 case IIK_Move:
1863 assert(false && "Unhandled initializer kind!");
1864 }
John McCall9ae2f072010-08-23 23:25:46 +00001865
Douglas Gregor53c374f2010-12-07 00:41:46 +00001866 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001867 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001868 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001869
Anders Carlssondefefd22010-04-23 02:00:02 +00001870 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001871 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001872 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1873 SourceLocation()),
1874 BaseSpec->isVirtual(),
1875 SourceLocation(),
1876 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001877 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001878 SourceLocation());
1879
Anders Carlssondefefd22010-04-23 02:00:02 +00001880 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001881}
1882
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001883static bool
1884BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001885 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001886 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001887 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001888 if (Field->isInvalidDecl())
1889 return true;
1890
Chandler Carruthf186b542010-06-29 23:50:44 +00001891 SourceLocation Loc = Constructor->getLocation();
1892
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001893 if (ImplicitInitKind == IIK_Copy) {
1894 ParmVarDecl *Param = Constructor->getParamDecl(0);
1895 QualType ParamType = Param->getType().getNonReferenceType();
1896
1897 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001898 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001899 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001900
1901 // Build a reference to this field within the parameter.
1902 CXXScopeSpec SS;
1903 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1904 Sema::LookupMemberName);
1905 MemberLookup.addDecl(Field, AS_public);
1906 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001907 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001908 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001909 ParamType, Loc,
1910 /*IsArrow=*/false,
1911 SS,
1912 /*FirstQualifierInScope=*/0,
1913 MemberLookup,
1914 /*TemplateArgs=*/0);
1915 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001916 return true;
1917
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001918 // When the field we are copying is an array, create index variables for
1919 // each dimension of the array. We use these index variables to subscript
1920 // the source array, and other clients (e.g., CodeGen) will perform the
1921 // necessary iteration with these index variables.
1922 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1923 QualType BaseType = Field->getType();
1924 QualType SizeType = SemaRef.Context.getSizeType();
1925 while (const ConstantArrayType *Array
1926 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1927 // Create the iteration variable for this array index.
1928 IdentifierInfo *IterationVarName = 0;
1929 {
1930 llvm::SmallString<8> Str;
1931 llvm::raw_svector_ostream OS(Str);
1932 OS << "__i" << IndexVariables.size();
1933 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1934 }
1935 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001936 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001937 IterationVarName, SizeType,
1938 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001939 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001940 IndexVariables.push_back(IterationVar);
1941
1942 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001943 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001944 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001945 assert(!IterationVarRef.isInvalid() &&
1946 "Reference to invented variable cannot fail!");
1947
1948 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001949 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001950 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001951 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001952 Loc);
1953 if (CopyCtorArg.isInvalid())
1954 return true;
1955
1956 BaseType = Array->getElementType();
1957 }
1958
1959 // Construct the entity that we will be initializing. For an array, this
1960 // will be first element in the array, which may require several levels
1961 // of array-subscript entities.
1962 llvm::SmallVector<InitializedEntity, 4> Entities;
1963 Entities.reserve(1 + IndexVariables.size());
1964 Entities.push_back(InitializedEntity::InitializeMember(Field));
1965 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1966 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1967 0,
1968 Entities.back()));
1969
1970 // Direct-initialize to use the copy constructor.
1971 InitializationKind InitKind =
1972 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1973
1974 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1975 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1976 &CopyCtorArgE, 1);
1977
John McCall60d7b3a2010-08-24 06:29:42 +00001978 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001979 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001980 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001981 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001982 if (MemberInit.isInvalid())
1983 return true;
1984
1985 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001986 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001987 MemberInit.takeAs<Expr>(), Loc,
1988 IndexVariables.data(),
1989 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001990 return false;
1991 }
1992
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001993 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1994
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001995 QualType FieldBaseElementType =
1996 SemaRef.Context.getBaseElementType(Field->getType());
1997
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001998 if (FieldBaseElementType->isRecordType()) {
1999 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002000 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002001 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002002
2003 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002004 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002005 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002006
Douglas Gregor53c374f2010-12-07 00:41:46 +00002007 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002008 if (MemberInit.isInvalid())
2009 return true;
2010
2011 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002012 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00002013 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002014 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00002015 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002016 return false;
2017 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002018
2019 if (FieldBaseElementType->isReferenceType()) {
2020 SemaRef.Diag(Constructor->getLocation(),
2021 diag::err_uninitialized_member_in_ctor)
2022 << (int)Constructor->isImplicit()
2023 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2024 << 0 << Field->getDeclName();
2025 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2026 return true;
2027 }
2028
2029 if (FieldBaseElementType.isConstQualified()) {
2030 SemaRef.Diag(Constructor->getLocation(),
2031 diag::err_uninitialized_member_in_ctor)
2032 << (int)Constructor->isImplicit()
2033 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2034 << 1 << Field->getDeclName();
2035 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2036 return true;
2037 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002038
2039 // Nothing to initialize.
2040 CXXMemberInit = 0;
2041 return false;
2042}
John McCallf1860e52010-05-20 23:23:51 +00002043
2044namespace {
2045struct BaseAndFieldInfo {
2046 Sema &S;
2047 CXXConstructorDecl *Ctor;
2048 bool AnyErrorsInInits;
2049 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002050 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2051 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002052
2053 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2054 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2055 // FIXME: Handle implicit move constructors.
2056 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2057 IIK = IIK_Copy;
2058 else
2059 IIK = IIK_Default;
2060 }
2061};
2062}
2063
2064static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2065 FieldDecl *Top, FieldDecl *Field) {
2066
Chandler Carruthe861c602010-06-30 02:59:29 +00002067 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002068 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002069 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002070 return false;
2071 }
2072
2073 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2074 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2075 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002076 CXXRecordDecl *FieldClassDecl
2077 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002078
2079 // Even though union members never have non-trivial default
2080 // constructions in C++03, we still build member initializers for aggregate
2081 // record types which can be union members, and C++0x allows non-trivial
2082 // default constructors for union members, so we ensure that only one
2083 // member is initialized for these.
2084 if (FieldClassDecl->isUnion()) {
2085 // First check for an explicit initializer for one field.
2086 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2087 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002088 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002089 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002090
2091 // Once we've initialized a field of an anonymous union, the union
2092 // field in the class is also initialized, so exit immediately.
2093 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002094 } else if ((*FA)->isAnonymousStructOrUnion()) {
2095 if (CollectFieldInitializer(Info, Top, *FA))
2096 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002097 }
2098 }
2099
2100 // Fallthrough and construct a default initializer for the union as
2101 // a whole, which can call its default constructor if such a thing exists
2102 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2103 // behavior going forward with C++0x, when anonymous unions there are
2104 // finalized, we should revisit this.
2105 } else {
2106 // For structs, we simply descend through to initialize all members where
2107 // necessary.
2108 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2109 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2110 if (CollectFieldInitializer(Info, Top, *FA))
2111 return true;
2112 }
2113 }
John McCallf1860e52010-05-20 23:23:51 +00002114 }
2115
2116 // Don't try to build an implicit initializer if there were semantic
2117 // errors in any of the initializers (and therefore we might be
2118 // missing some that the user actually wrote).
2119 if (Info.AnyErrorsInInits)
2120 return false;
2121
Sean Huntcbb67482011-01-08 20:30:50 +00002122 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002123 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2124 return true;
John McCallf1860e52010-05-20 23:23:51 +00002125
Francois Pichet00eb3f92010-12-04 09:14:42 +00002126 if (Init)
2127 Info.AllToInit.push_back(Init);
2128
John McCallf1860e52010-05-20 23:23:51 +00002129 return false;
2130}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002131
2132bool
2133Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2134 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002135 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002136 Constructor->setNumCtorInitializers(1);
2137 CXXCtorInitializer **initializer =
2138 new (Context) CXXCtorInitializer*[1];
2139 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2140 Constructor->setCtorInitializers(initializer);
2141
Sean Huntb76af9c2011-05-03 23:05:34 +00002142 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2143 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2144 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2145 }
2146
Sean Huntc1598702011-05-05 00:05:47 +00002147 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002148
Sean Hunt059ce0d2011-05-01 07:04:31 +00002149 return false;
2150}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002151
Eli Friedman80c30da2009-11-09 19:20:36 +00002152bool
Sean Huntcbb67482011-01-08 20:30:50 +00002153Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2154 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002155 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002156 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002157 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002158 // Just store the initializers as written, they will be checked during
2159 // instantiation.
2160 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002161 Constructor->setNumCtorInitializers(NumInitializers);
2162 CXXCtorInitializer **baseOrMemberInitializers =
2163 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002164 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002165 NumInitializers * sizeof(CXXCtorInitializer*));
2166 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002167 }
2168
2169 return false;
2170 }
2171
John McCallf1860e52010-05-20 23:23:51 +00002172 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002173
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002174 // We need to build the initializer AST according to order of construction
2175 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002176 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002177 if (!ClassDecl)
2178 return true;
2179
Eli Friedman80c30da2009-11-09 19:20:36 +00002180 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002182 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002183 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002184
2185 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002186 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002187 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002188 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002189 }
2190
Anders Carlsson711f34a2010-04-21 19:52:01 +00002191 // Keep track of the direct virtual bases.
2192 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2193 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2194 E = ClassDecl->bases_end(); I != E; ++I) {
2195 if (I->isVirtual())
2196 DirectVBases.insert(I);
2197 }
2198
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002199 // Push virtual bases before others.
2200 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2201 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2202
Sean Huntcbb67482011-01-08 20:30:50 +00002203 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002204 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2205 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002206 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002207 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002208 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002209 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002210 VBase, IsInheritedVirtualBase,
2211 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002212 HadError = true;
2213 continue;
2214 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002215
John McCallf1860e52010-05-20 23:23:51 +00002216 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002217 }
2218 }
Mike Stump1eb44332009-09-09 15:08:12 +00002219
John McCallf1860e52010-05-20 23:23:51 +00002220 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002221 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2222 E = ClassDecl->bases_end(); Base != E; ++Base) {
2223 // Virtuals are in the virtual base list and already constructed.
2224 if (Base->isVirtual())
2225 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Sean Huntcbb67482011-01-08 20:30:50 +00002227 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002228 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2229 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002230 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002231 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002232 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002233 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002234 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002235 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002236 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002237 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002238
John McCallf1860e52010-05-20 23:23:51 +00002239 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002240 }
2241 }
Mike Stump1eb44332009-09-09 15:08:12 +00002242
John McCallf1860e52010-05-20 23:23:51 +00002243 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002244 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002245 E = ClassDecl->field_end(); Field != E; ++Field) {
2246 if ((*Field)->getType()->isIncompleteArrayType()) {
2247 assert(ClassDecl->hasFlexibleArrayMember() &&
2248 "Incomplete array type is not valid");
2249 continue;
2250 }
John McCallf1860e52010-05-20 23:23:51 +00002251 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002252 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002253 }
Mike Stump1eb44332009-09-09 15:08:12 +00002254
John McCallf1860e52010-05-20 23:23:51 +00002255 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002256 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002257 Constructor->setNumCtorInitializers(NumInitializers);
2258 CXXCtorInitializer **baseOrMemberInitializers =
2259 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002260 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002261 NumInitializers * sizeof(CXXCtorInitializer*));
2262 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002263
John McCallef027fe2010-03-16 21:39:52 +00002264 // Constructors implicitly reference the base and member
2265 // destructors.
2266 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2267 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002268 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002269
2270 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002271}
2272
Eli Friedman6347f422009-07-21 19:28:10 +00002273static void *GetKeyForTopLevelField(FieldDecl *Field) {
2274 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002275 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002276 if (RT->getDecl()->isAnonymousStructOrUnion())
2277 return static_cast<void *>(RT->getDecl());
2278 }
2279 return static_cast<void *>(Field);
2280}
2281
Anders Carlssonea356fb2010-04-02 05:42:15 +00002282static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002283 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002284}
2285
Anders Carlssonea356fb2010-04-02 05:42:15 +00002286static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002287 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002288 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002289 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002290
Eli Friedman6347f422009-07-21 19:28:10 +00002291 // For fields injected into the class via declaration of an anonymous union,
2292 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002293 FieldDecl *Field = Member->getAnyMember();
2294
John McCall3c3ccdb2010-04-10 09:28:51 +00002295 // If the field is a member of an anonymous struct or union, our key
2296 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002297 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002298 if (RD->isAnonymousStructOrUnion()) {
2299 while (true) {
2300 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2301 if (Parent->isAnonymousStructOrUnion())
2302 RD = Parent;
2303 else
2304 break;
2305 }
2306
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002307 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002310 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002311}
2312
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002313static void
2314DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002315 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002316 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002317 unsigned NumInits) {
2318 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002319 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002321 // Don't check initializers order unless the warning is enabled at the
2322 // location of at least one initializer.
2323 bool ShouldCheckOrder = false;
2324 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002325 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002326 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2327 Init->getSourceLocation())
2328 != Diagnostic::Ignored) {
2329 ShouldCheckOrder = true;
2330 break;
2331 }
2332 }
2333 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002334 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002335
John McCalld6ca8da2010-04-10 07:37:23 +00002336 // Build the list of bases and members in the order that they'll
2337 // actually be initialized. The explicit initializers should be in
2338 // this same order but may be missing things.
2339 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Anders Carlsson071d6102010-04-02 03:38:04 +00002341 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2342
John McCalld6ca8da2010-04-10 07:37:23 +00002343 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002344 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002345 ClassDecl->vbases_begin(),
2346 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002347 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002348
John McCalld6ca8da2010-04-10 07:37:23 +00002349 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002350 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002351 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002352 if (Base->isVirtual())
2353 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002354 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002355 }
Mike Stump1eb44332009-09-09 15:08:12 +00002356
John McCalld6ca8da2010-04-10 07:37:23 +00002357 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002358 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2359 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002360 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002361
John McCalld6ca8da2010-04-10 07:37:23 +00002362 unsigned NumIdealInits = IdealInitKeys.size();
2363 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002364
Sean Huntcbb67482011-01-08 20:30:50 +00002365 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002366 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002367 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002368 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002369
2370 // Scan forward to try to find this initializer in the idealized
2371 // initializers list.
2372 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2373 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002374 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002375
2376 // If we didn't find this initializer, it must be because we
2377 // scanned past it on a previous iteration. That can only
2378 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002379 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002380 Sema::SemaDiagnosticBuilder D =
2381 SemaRef.Diag(PrevInit->getSourceLocation(),
2382 diag::warn_initializer_out_of_order);
2383
Francois Pichet00eb3f92010-12-04 09:14:42 +00002384 if (PrevInit->isAnyMemberInitializer())
2385 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002386 else
2387 D << 1 << PrevInit->getBaseClassInfo()->getType();
2388
Francois Pichet00eb3f92010-12-04 09:14:42 +00002389 if (Init->isAnyMemberInitializer())
2390 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002391 else
2392 D << 1 << Init->getBaseClassInfo()->getType();
2393
2394 // Move back to the initializer's location in the ideal list.
2395 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2396 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002397 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002398
2399 assert(IdealIndex != NumIdealInits &&
2400 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002401 }
John McCalld6ca8da2010-04-10 07:37:23 +00002402
2403 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002404 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002405}
2406
John McCall3c3ccdb2010-04-10 09:28:51 +00002407namespace {
2408bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002409 CXXCtorInitializer *Init,
2410 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002411 if (!PrevInit) {
2412 PrevInit = Init;
2413 return false;
2414 }
2415
2416 if (FieldDecl *Field = Init->getMember())
2417 S.Diag(Init->getSourceLocation(),
2418 diag::err_multiple_mem_initialization)
2419 << Field->getDeclName()
2420 << Init->getSourceRange();
2421 else {
John McCallf4c73712011-01-19 06:33:43 +00002422 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002423 assert(BaseClass && "neither field nor base");
2424 S.Diag(Init->getSourceLocation(),
2425 diag::err_multiple_base_initialization)
2426 << QualType(BaseClass, 0)
2427 << Init->getSourceRange();
2428 }
2429 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2430 << 0 << PrevInit->getSourceRange();
2431
2432 return true;
2433}
2434
Sean Huntcbb67482011-01-08 20:30:50 +00002435typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002436typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2437
2438bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002439 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002440 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002441 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002442 RecordDecl *Parent = Field->getParent();
2443 if (!Parent->isAnonymousStructOrUnion())
2444 return false;
2445
2446 NamedDecl *Child = Field;
2447 do {
2448 if (Parent->isUnion()) {
2449 UnionEntry &En = Unions[Parent];
2450 if (En.first && En.first != Child) {
2451 S.Diag(Init->getSourceLocation(),
2452 diag::err_multiple_mem_union_initialization)
2453 << Field->getDeclName()
2454 << Init->getSourceRange();
2455 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2456 << 0 << En.second->getSourceRange();
2457 return true;
2458 } else if (!En.first) {
2459 En.first = Child;
2460 En.second = Init;
2461 }
2462 }
2463
2464 Child = Parent;
2465 Parent = cast<RecordDecl>(Parent->getDeclContext());
2466 } while (Parent->isAnonymousStructOrUnion());
2467
2468 return false;
2469}
2470}
2471
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002472/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002473void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002474 SourceLocation ColonLoc,
2475 MemInitTy **meminits, unsigned NumMemInits,
2476 bool AnyErrors) {
2477 if (!ConstructorDecl)
2478 return;
2479
2480 AdjustDeclIfTemplate(ConstructorDecl);
2481
2482 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002483 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002484
2485 if (!Constructor) {
2486 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2487 return;
2488 }
2489
Sean Huntcbb67482011-01-08 20:30:50 +00002490 CXXCtorInitializer **MemInits =
2491 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002492
2493 // Mapping for the duplicate initializers check.
2494 // For member initializers, this is keyed with a FieldDecl*.
2495 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002496 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002497
2498 // Mapping for the inconsistent anonymous-union initializers check.
2499 RedundantUnionMap MemberUnions;
2500
Anders Carlssonea356fb2010-04-02 05:42:15 +00002501 bool HadError = false;
2502 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002503 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002504
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002505 // Set the source order index.
2506 Init->setSourceOrder(i);
2507
Francois Pichet00eb3f92010-12-04 09:14:42 +00002508 if (Init->isAnyMemberInitializer()) {
2509 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002510 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2511 CheckRedundantUnionInit(*this, Init, MemberUnions))
2512 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002513 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002514 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2515 if (CheckRedundantInit(*this, Init, Members[Key]))
2516 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002517 } else {
2518 assert(Init->isDelegatingInitializer());
2519 // This must be the only initializer
2520 if (i != 0 || NumMemInits > 1) {
2521 Diag(MemInits[0]->getSourceLocation(),
2522 diag::err_delegating_initializer_alone)
2523 << MemInits[0]->getSourceRange();
2524 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002525 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002526 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002527 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002528 // Return immediately as the initializer is set.
2529 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002530 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002531 }
2532
Anders Carlssonea356fb2010-04-02 05:42:15 +00002533 if (HadError)
2534 return;
2535
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002536 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002537
Sean Huntcbb67482011-01-08 20:30:50 +00002538 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002539}
2540
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002541void
John McCallef027fe2010-03-16 21:39:52 +00002542Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2543 CXXRecordDecl *ClassDecl) {
2544 // Ignore dependent contexts.
2545 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002546 return;
John McCall58e6f342010-03-16 05:22:47 +00002547
2548 // FIXME: all the access-control diagnostics are positioned on the
2549 // field/base declaration. That's probably good; that said, the
2550 // user might reasonably want to know why the destructor is being
2551 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002552
Anders Carlsson9f853df2009-11-17 04:44:12 +00002553 // Non-static data members.
2554 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2555 E = ClassDecl->field_end(); I != E; ++I) {
2556 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002557 if (Field->isInvalidDecl())
2558 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002559 QualType FieldType = Context.getBaseElementType(Field->getType());
2560
2561 const RecordType* RT = FieldType->getAs<RecordType>();
2562 if (!RT)
2563 continue;
2564
2565 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002566 if (FieldClassDecl->isInvalidDecl())
2567 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002568 if (FieldClassDecl->hasTrivialDestructor())
2569 continue;
2570
Douglas Gregordb89f282010-07-01 22:47:18 +00002571 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002572 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002573 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002574 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002575 << Field->getDeclName()
2576 << FieldType);
2577
John McCallef027fe2010-03-16 21:39:52 +00002578 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002579 }
2580
John McCall58e6f342010-03-16 05:22:47 +00002581 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2582
Anders Carlsson9f853df2009-11-17 04:44:12 +00002583 // Bases.
2584 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2585 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002586 // Bases are always records in a well-formed non-dependent class.
2587 const RecordType *RT = Base->getType()->getAs<RecordType>();
2588
2589 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002590 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002591 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002592
John McCall58e6f342010-03-16 05:22:47 +00002593 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002594 // If our base class is invalid, we probably can't get its dtor anyway.
2595 if (BaseClassDecl->isInvalidDecl())
2596 continue;
2597 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002598 if (BaseClassDecl->hasTrivialDestructor())
2599 continue;
John McCall58e6f342010-03-16 05:22:47 +00002600
Douglas Gregordb89f282010-07-01 22:47:18 +00002601 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002602 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002603
2604 // FIXME: caret should be on the start of the class name
2605 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002606 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002607 << Base->getType()
2608 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002609
John McCallef027fe2010-03-16 21:39:52 +00002610 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002611 }
2612
2613 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002614 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2615 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002616
2617 // Bases are always records in a well-formed non-dependent class.
2618 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2619
2620 // Ignore direct virtual bases.
2621 if (DirectVirtualBases.count(RT))
2622 continue;
2623
John McCall58e6f342010-03-16 05:22:47 +00002624 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002625 // If our base class is invalid, we probably can't get its dtor anyway.
2626 if (BaseClassDecl->isInvalidDecl())
2627 continue;
2628 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002629 if (BaseClassDecl->hasTrivialDestructor())
2630 continue;
John McCall58e6f342010-03-16 05:22:47 +00002631
Douglas Gregordb89f282010-07-01 22:47:18 +00002632 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002633 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002634 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002635 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002636 << VBase->getType());
2637
John McCallef027fe2010-03-16 21:39:52 +00002638 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002639 }
2640}
2641
John McCalld226f652010-08-21 09:40:31 +00002642void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002643 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002644 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Mike Stump1eb44332009-09-09 15:08:12 +00002646 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002647 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002648 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002649}
2650
Mike Stump1eb44332009-09-09 15:08:12 +00002651bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002652 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002653 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002654 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002655 else
John McCall94c3b562010-08-18 09:41:07 +00002656 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002657}
2658
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002659bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002660 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002661 if (!getLangOptions().CPlusPlus)
2662 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Anders Carlsson11f21a02009-03-23 19:10:31 +00002664 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002665 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Ted Kremenek6217b802009-07-29 21:53:49 +00002667 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002668 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002669 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002670 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002672 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002673 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002674 }
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Ted Kremenek6217b802009-07-29 21:53:49 +00002676 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002677 if (!RT)
2678 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002679
John McCall86ff3082010-02-04 22:26:26 +00002680 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002681
John McCall94c3b562010-08-18 09:41:07 +00002682 // We can't answer whether something is abstract until it has a
2683 // definition. If it's currently being defined, we'll walk back
2684 // over all the declarations when we have a full definition.
2685 const CXXRecordDecl *Def = RD->getDefinition();
2686 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002687 return false;
2688
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002689 if (!RD->isAbstract())
2690 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002692 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002693 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002694
John McCall94c3b562010-08-18 09:41:07 +00002695 return true;
2696}
2697
2698void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2699 // Check if we've already emitted the list of pure virtual functions
2700 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002701 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002702 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002704 CXXFinalOverriderMap FinalOverriders;
2705 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002707 // Keep a set of seen pure methods so we won't diagnose the same method
2708 // more than once.
2709 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2710
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002711 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2712 MEnd = FinalOverriders.end();
2713 M != MEnd;
2714 ++M) {
2715 for (OverridingMethods::iterator SO = M->second.begin(),
2716 SOEnd = M->second.end();
2717 SO != SOEnd; ++SO) {
2718 // C++ [class.abstract]p4:
2719 // A class is abstract if it contains or inherits at least one
2720 // pure virtual function for which the final overrider is pure
2721 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002723 //
2724 if (SO->second.size() != 1)
2725 continue;
2726
2727 if (!SO->second.front().Method->isPure())
2728 continue;
2729
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002730 if (!SeenPureMethods.insert(SO->second.front().Method))
2731 continue;
2732
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002733 Diag(SO->second.front().Method->getLocation(),
2734 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002735 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002736 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002737 }
2738
2739 if (!PureVirtualClassDiagSet)
2740 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2741 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002742}
2743
Anders Carlsson8211eff2009-03-24 01:19:16 +00002744namespace {
John McCall94c3b562010-08-18 09:41:07 +00002745struct AbstractUsageInfo {
2746 Sema &S;
2747 CXXRecordDecl *Record;
2748 CanQualType AbstractType;
2749 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002750
John McCall94c3b562010-08-18 09:41:07 +00002751 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2752 : S(S), Record(Record),
2753 AbstractType(S.Context.getCanonicalType(
2754 S.Context.getTypeDeclType(Record))),
2755 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002756
John McCall94c3b562010-08-18 09:41:07 +00002757 void DiagnoseAbstractType() {
2758 if (Invalid) return;
2759 S.DiagnoseAbstractType(Record);
2760 Invalid = true;
2761 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002762
John McCall94c3b562010-08-18 09:41:07 +00002763 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2764};
2765
2766struct CheckAbstractUsage {
2767 AbstractUsageInfo &Info;
2768 const NamedDecl *Ctx;
2769
2770 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2771 : Info(Info), Ctx(Ctx) {}
2772
2773 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2774 switch (TL.getTypeLocClass()) {
2775#define ABSTRACT_TYPELOC(CLASS, PARENT)
2776#define TYPELOC(CLASS, PARENT) \
2777 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2778#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002779 }
John McCall94c3b562010-08-18 09:41:07 +00002780 }
Mike Stump1eb44332009-09-09 15:08:12 +00002781
John McCall94c3b562010-08-18 09:41:07 +00002782 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2783 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2784 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002785 if (!TL.getArg(I))
2786 continue;
2787
John McCall94c3b562010-08-18 09:41:07 +00002788 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2789 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002790 }
John McCall94c3b562010-08-18 09:41:07 +00002791 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002792
John McCall94c3b562010-08-18 09:41:07 +00002793 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2794 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2795 }
Mike Stump1eb44332009-09-09 15:08:12 +00002796
John McCall94c3b562010-08-18 09:41:07 +00002797 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2798 // Visit the type parameters from a permissive context.
2799 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2800 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2801 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2802 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2803 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2804 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002805 }
John McCall94c3b562010-08-18 09:41:07 +00002806 }
Mike Stump1eb44332009-09-09 15:08:12 +00002807
John McCall94c3b562010-08-18 09:41:07 +00002808 // Visit pointee types from a permissive context.
2809#define CheckPolymorphic(Type) \
2810 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2811 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2812 }
2813 CheckPolymorphic(PointerTypeLoc)
2814 CheckPolymorphic(ReferenceTypeLoc)
2815 CheckPolymorphic(MemberPointerTypeLoc)
2816 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002817
John McCall94c3b562010-08-18 09:41:07 +00002818 /// Handle all the types we haven't given a more specific
2819 /// implementation for above.
2820 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2821 // Every other kind of type that we haven't called out already
2822 // that has an inner type is either (1) sugar or (2) contains that
2823 // inner type in some way as a subobject.
2824 if (TypeLoc Next = TL.getNextTypeLoc())
2825 return Visit(Next, Sel);
2826
2827 // If there's no inner type and we're in a permissive context,
2828 // don't diagnose.
2829 if (Sel == Sema::AbstractNone) return;
2830
2831 // Check whether the type matches the abstract type.
2832 QualType T = TL.getType();
2833 if (T->isArrayType()) {
2834 Sel = Sema::AbstractArrayType;
2835 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002836 }
John McCall94c3b562010-08-18 09:41:07 +00002837 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2838 if (CT != Info.AbstractType) return;
2839
2840 // It matched; do some magic.
2841 if (Sel == Sema::AbstractArrayType) {
2842 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2843 << T << TL.getSourceRange();
2844 } else {
2845 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2846 << Sel << T << TL.getSourceRange();
2847 }
2848 Info.DiagnoseAbstractType();
2849 }
2850};
2851
2852void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2853 Sema::AbstractDiagSelID Sel) {
2854 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2855}
2856
2857}
2858
2859/// Check for invalid uses of an abstract type in a method declaration.
2860static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2861 CXXMethodDecl *MD) {
2862 // No need to do the check on definitions, which require that
2863 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00002864 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00002865 return;
2866
2867 // For safety's sake, just ignore it if we don't have type source
2868 // information. This should never happen for non-implicit methods,
2869 // but...
2870 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2871 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2872}
2873
2874/// Check for invalid uses of an abstract type within a class definition.
2875static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2876 CXXRecordDecl *RD) {
2877 for (CXXRecordDecl::decl_iterator
2878 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2879 Decl *D = *I;
2880 if (D->isImplicit()) continue;
2881
2882 // Methods and method templates.
2883 if (isa<CXXMethodDecl>(D)) {
2884 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2885 } else if (isa<FunctionTemplateDecl>(D)) {
2886 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2887 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2888
2889 // Fields and static variables.
2890 } else if (isa<FieldDecl>(D)) {
2891 FieldDecl *FD = cast<FieldDecl>(D);
2892 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2893 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2894 } else if (isa<VarDecl>(D)) {
2895 VarDecl *VD = cast<VarDecl>(D);
2896 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2897 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2898
2899 // Nested classes and class templates.
2900 } else if (isa<CXXRecordDecl>(D)) {
2901 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2902 } else if (isa<ClassTemplateDecl>(D)) {
2903 CheckAbstractClassUsage(Info,
2904 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2905 }
2906 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002907}
2908
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002909/// \brief Perform semantic checks on a class definition that has been
2910/// completing, introducing implicitly-declared members, checking for
2911/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002912void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002913 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002914 return;
2915
John McCall94c3b562010-08-18 09:41:07 +00002916 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2917 AbstractUsageInfo Info(*this, Record);
2918 CheckAbstractClassUsage(Info, Record);
2919 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002920
2921 // If this is not an aggregate type and has no user-declared constructor,
2922 // complain about any non-static data members of reference or const scalar
2923 // type, since they will never get initializers.
2924 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2925 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2926 bool Complained = false;
2927 for (RecordDecl::field_iterator F = Record->field_begin(),
2928 FEnd = Record->field_end();
2929 F != FEnd; ++F) {
2930 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002931 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002932 if (!Complained) {
2933 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2934 << Record->getTagKind() << Record;
2935 Complained = true;
2936 }
2937
2938 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2939 << F->getType()->isReferenceType()
2940 << F->getDeclName();
2941 }
2942 }
2943 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002944
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002945 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002946 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002947
2948 if (Record->getIdentifier()) {
2949 // C++ [class.mem]p13:
2950 // If T is the name of a class, then each of the following shall have a
2951 // name different from T:
2952 // - every member of every anonymous union that is a member of class T.
2953 //
2954 // C++ [class.mem]p14:
2955 // In addition, if class T has a user-declared constructor (12.1), every
2956 // non-static data member of class T shall have a name different from T.
2957 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002958 R.first != R.second; ++R.first) {
2959 NamedDecl *D = *R.first;
2960 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2961 isa<IndirectFieldDecl>(D)) {
2962 Diag(D->getLocation(), diag::err_member_name_of_class)
2963 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002964 break;
2965 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002966 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002967 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002968
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002969 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002970 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002971 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002972 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002973 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2974 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2975 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002976
2977 // See if a method overloads virtual methods in a base
2978 /// class without overriding any.
2979 if (!Record->isDependentType()) {
2980 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2981 MEnd = Record->method_end();
2982 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002983 if (!(*M)->isStatic())
2984 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002985 }
2986 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002987
2988 // Declare inherited constructors. We do this eagerly here because:
2989 // - The standard requires an eager diagnostic for conflicting inherited
2990 // constructors from different classes.
2991 // - The lazy declaration of the other implicit constructors is so as to not
2992 // waste space and performance on classes that are not meant to be
2993 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2994 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002995 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00002996
2997 CheckExplicitlyDefaultedMethods(Record);
2998}
2999
3000void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003001 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3002 ME = Record->method_end();
3003 MI != ME; ++MI) {
3004 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3005 switch (getSpecialMember(*MI)) {
3006 case CXXDefaultConstructor:
3007 CheckExplicitlyDefaultedDefaultConstructor(
3008 cast<CXXConstructorDecl>(*MI));
3009 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003010
Sean Huntcb45a0f2011-05-12 22:46:25 +00003011 case CXXDestructor:
3012 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3013 break;
3014
3015 case CXXCopyConstructor:
3016 case CXXCopyAssignment:
3017 // FIXME: Do copy and move constructors and assignment operators
3018 break;
3019
3020 default:
3021 llvm_unreachable("non-special member explicitly defaulted!");
3022 }
Sean Hunt001cad92011-05-10 00:49:42 +00003023 }
3024 }
3025
Sean Hunt001cad92011-05-10 00:49:42 +00003026}
3027
3028void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3029 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3030
3031 // Whether this was the first-declared instance of the constructor.
3032 // This affects whether we implicitly add an exception spec (and, eventually,
3033 // constexpr). It is also ill-formed to explicitly default a constructor such
3034 // that it would be deleted. (C++0x [decl.fct.def.default])
3035 bool First = CD == CD->getCanonicalDecl();
3036
3037 if (CD->getNumParams() != 0) {
3038 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3039 << CD->getSourceRange();
3040 CD->setInvalidDecl();
3041 return;
3042 }
3043
3044 ImplicitExceptionSpecification Spec
3045 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3046 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3047 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3048 *ExceptionType = Context.getFunctionType(
3049 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3050
3051 if (CtorType->hasExceptionSpec()) {
3052 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003053 PDiag(diag::err_incorrect_defaulted_exception_spec)
3054 << 0 /* default constructor */,
Sean Hunt001cad92011-05-10 00:49:42 +00003055 PDiag(),
3056 ExceptionType, SourceLocation(),
3057 CtorType, CD->getLocation())) {
3058 CD->setInvalidDecl();
3059 return;
3060 }
3061 } else if (First) {
3062 // We set the declaration to have the computed exception spec here.
3063 // We know there are no parameters.
3064 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3065 }
Sean Huntca46d132011-05-12 03:51:48 +00003066
3067 if (ShouldDeleteDefaultConstructor(CD)) {
3068 if (First)
3069 CD->setDeletedAsWritten();
3070 else
3071 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Huntcb45a0f2011-05-12 22:46:25 +00003072 << 0 /* default constructor */;
Sean Huntca46d132011-05-12 03:51:48 +00003073 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003074}
Sean Hunt001cad92011-05-10 00:49:42 +00003075
Sean Huntcb45a0f2011-05-12 22:46:25 +00003076void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3077 assert(DD->isExplicitlyDefaulted());
3078
3079 // Whether this was the first-declared instance of the destructor.
3080 bool First = DD == DD->getCanonicalDecl();
3081
3082 ImplicitExceptionSpecification Spec
3083 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3084 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3085 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3086 *ExceptionType = Context.getFunctionType(
3087 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3088
3089 if (DtorType->hasExceptionSpec()) {
3090 if (CheckEquivalentExceptionSpec(
3091 PDiag(diag::err_incorrect_defaulted_exception_spec)
3092 << 3 /* destructor */,
3093 PDiag(),
3094 ExceptionType, SourceLocation(),
3095 DtorType, DD->getLocation())) {
3096 DD->setInvalidDecl();
3097 return;
3098 }
3099 } else if (First) {
3100 // We set the declaration to have the computed exception spec here.
3101 // There are no parameters.
3102 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3103 }
3104
3105 if (ShouldDeleteDestructor(DD)) {
3106 if (First)
3107 DD->setDeletedAsWritten();
3108 else
3109 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3110 << 3 /* destructor */;
3111 }
3112
3113 CheckDestructor(DD);
3114}
3115
Sean Huntcdee3fe2011-05-11 22:34:38 +00003116bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3117 CXXRecordDecl *RD = CD->getParent();
3118 assert(!RD->isDependentType() && "do deletion after instantiation");
3119 if (!LangOpts.CPlusPlus0x)
3120 return false;
3121
3122 // Do access control from the constructor
3123 ContextRAII CtorContext(*this, CD);
3124
3125 bool Union = RD->isUnion();
3126 bool AllConst = true;
3127
Sean Huntcdee3fe2011-05-11 22:34:38 +00003128 // We do this because we should never actually use an anonymous
3129 // union's constructor.
3130 if (Union && RD->isAnonymousStructOrUnion())
3131 return false;
3132
3133 // FIXME: We should put some diagnostic logic right into this function.
3134
3135 // C++0x [class.ctor]/5
3136 // A defaulted default constructor for class X is defined as delete if:
3137
3138 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3139 BE = RD->bases_end();
3140 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003141 // We'll handle this one later
3142 if (BI->isVirtual())
3143 continue;
3144
Sean Huntcdee3fe2011-05-11 22:34:38 +00003145 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3146 assert(BaseDecl && "base isn't a CXXRecordDecl");
3147
3148 // -- any [direct base class] has a type with a destructor that is
3149 // delete or inaccessible from the defaulted default constructor
3150 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3151 if (BaseDtor->isDeleted())
3152 return true;
3153 if (CheckDestructorAccess(SourceLocation(), BaseDtor, PDiag()) !=
3154 AR_accessible)
3155 return true;
3156
Sean Huntcdee3fe2011-05-11 22:34:38 +00003157 // -- any [direct base class either] has no default constructor or
3158 // overload resolution as applied to [its] default constructor
3159 // results in an ambiguity or in a function that is deleted or
3160 // inaccessible from the defaulted default constructor
3161 InitializedEntity BaseEntity =
3162 InitializedEntity::InitializeBase(Context, BI, 0);
3163 InitializationKind Kind =
3164 InitializationKind::CreateDirect(SourceLocation(), SourceLocation(),
3165 SourceLocation());
3166
3167 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3168
3169 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3170 return true;
3171 }
3172
3173 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3174 BE = RD->vbases_end();
3175 BI != BE; ++BI) {
3176 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3177 assert(BaseDecl && "base isn't a CXXRecordDecl");
3178
3179 // -- any [virtual base class] has a type with a destructor that is
3180 // delete or inaccessible from the defaulted default constructor
3181 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3182 if (BaseDtor->isDeleted())
3183 return true;
3184 if (CheckDestructorAccess(SourceLocation(), BaseDtor, PDiag()) !=
3185 AR_accessible)
3186 return true;
3187
3188 // -- any [virtual base class either] has no default constructor or
3189 // overload resolution as applied to [its] default constructor
3190 // results in an ambiguity or in a function that is deleted or
3191 // inaccessible from the defaulted default constructor
3192 InitializedEntity BaseEntity =
3193 InitializedEntity::InitializeBase(Context, BI, BI);
3194 InitializationKind Kind =
3195 InitializationKind::CreateDirect(SourceLocation(), SourceLocation(),
3196 SourceLocation());
3197
3198 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3199
3200 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3201 return true;
3202 }
3203
3204 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3205 FE = RD->field_end();
3206 FI != FE; ++FI) {
3207 QualType FieldType = Context.getBaseElementType(FI->getType());
3208 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3209
3210 // -- any non-static data member with no brace-or-equal-initializer is of
3211 // reference type
3212 if (FieldType->isReferenceType())
3213 return true;
3214
3215 // -- X is a union and all its variant members are of const-qualified type
3216 // (or array thereof)
3217 if (Union && !FieldType.isConstQualified())
3218 AllConst = false;
3219
3220 if (FieldRecord) {
3221 // -- X is a union-like class that has a variant member with a non-trivial
3222 // default constructor
3223 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3224 return true;
3225
3226 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3227 if (FieldDtor->isDeleted())
3228 return true;
3229 if (CheckDestructorAccess(SourceLocation(), FieldDtor, PDiag()) !=
3230 AR_accessible)
3231 return true;
3232
3233 // -- any non-variant non-static data member of const-qualified type (or
3234 // array thereof) with no brace-or-equal-initializer does not have a
3235 // user-provided default constructor
3236 if (FieldType.isConstQualified() &&
3237 !FieldRecord->hasUserProvidedDefaultConstructor())
3238 return true;
3239
3240 if (!Union && FieldRecord->isUnion() &&
3241 FieldRecord->isAnonymousStructOrUnion()) {
3242 // We're okay to reuse AllConst here since we only care about the
3243 // value otherwise if we're in a union.
3244 AllConst = true;
3245
3246 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3247 UE = FieldRecord->field_end();
3248 UI != UE; ++UI) {
3249 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3250 CXXRecordDecl *UnionFieldRecord =
3251 UnionFieldType->getAsCXXRecordDecl();
3252
3253 if (!UnionFieldType.isConstQualified())
3254 AllConst = false;
3255
3256 if (UnionFieldRecord &&
3257 !UnionFieldRecord->hasTrivialDefaultConstructor())
3258 return true;
3259 }
3260
3261 if (AllConst)
3262 return true;
3263
3264 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003265 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003266 continue;
3267 }
3268 }
3269
3270 InitializedEntity MemberEntity =
3271 InitializedEntity::InitializeMember(*FI, 0);
3272 InitializationKind Kind =
3273 InitializationKind::CreateDirect(SourceLocation(), SourceLocation(),
3274 SourceLocation());
3275
3276 InitializationSequence InitSeq(*this, MemberEntity, Kind, 0, 0);
3277
3278 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3279 return true;
3280 }
3281
3282 if (Union && AllConst)
3283 return true;
3284
3285 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003286}
3287
Sean Huntcb45a0f2011-05-12 22:46:25 +00003288bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3289 CXXRecordDecl *RD = DD->getParent();
3290 assert(!RD->isDependentType() && "do deletion after instantiation");
3291 if (!LangOpts.CPlusPlus0x)
3292 return false;
3293
3294 // Do access control from the destructor
3295 ContextRAII CtorContext(*this, DD);
3296
3297 bool Union = RD->isUnion();
3298
3299 // C++0x [class.dtor]p5
3300 // A defaulted destructor for a class X is defined as deleted if:
3301 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3302 BE = RD->bases_end();
3303 BI != BE; ++BI) {
3304 // We'll handle this one later
3305 if (BI->isVirtual())
3306 continue;
3307
3308 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3309 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3310 assert(BaseDtor && "base has no destructor");
3311
3312 // -- any direct or virtual base class has a deleted destructor or
3313 // a destructor that is inaccessible from the defaulted destructor
3314 if (BaseDtor->isDeleted())
3315 return true;
3316 if (CheckDestructorAccess(SourceLocation(), BaseDtor, PDiag()) !=
3317 AR_accessible)
3318 return true;
3319 }
3320
3321 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3322 BE = RD->vbases_end();
3323 BI != BE; ++BI) {
3324 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3325 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3326 assert(BaseDtor && "base has no destructor");
3327
3328 // -- any direct or virtual base class has a deleted destructor or
3329 // a destructor that is inaccessible from the defaulted destructor
3330 if (BaseDtor->isDeleted())
3331 return true;
3332 if (CheckDestructorAccess(SourceLocation(), BaseDtor, PDiag()) !=
3333 AR_accessible)
3334 return true;
3335 }
3336
3337 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3338 FE = RD->field_end();
3339 FI != FE; ++FI) {
3340 QualType FieldType = Context.getBaseElementType(FI->getType());
3341 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3342 if (FieldRecord) {
3343 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3344 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3345 UE = FieldRecord->field_end();
3346 UI != UE; ++UI) {
3347 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3348 CXXRecordDecl *UnionFieldRecord =
3349 UnionFieldType->getAsCXXRecordDecl();
3350
3351 // -- X is a union-like class that has a variant member with a non-
3352 // trivial destructor.
3353 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3354 return true;
3355 }
3356 // Technically we are supposed to do this next check unconditionally.
3357 // But that makes absolutely no sense.
3358 } else {
3359 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3360
3361 // -- any of the non-static data members has class type M (or array
3362 // thereof) and M has a deleted destructor or a destructor that is
3363 // inaccessible from the defaulted destructor
3364 if (FieldDtor->isDeleted())
3365 return true;
3366 if (CheckDestructorAccess(SourceLocation(), FieldDtor, PDiag()) !=
3367 AR_accessible)
3368 return true;
3369
3370 // -- X is a union-like class that has a variant member with a non-
3371 // trivial destructor.
3372 if (Union && !FieldDtor->isTrivial())
3373 return true;
3374 }
3375 }
3376 }
3377
3378 if (DD->isVirtual()) {
3379 FunctionDecl *OperatorDelete = 0;
3380 DeclarationName Name =
3381 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3382 if (FindDeallocationFunction(SourceLocation(), RD, Name, OperatorDelete,
3383 false))
3384 return true;
3385 }
3386
3387
3388 return false;
3389}
3390
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003391/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00003392namespace {
3393 struct FindHiddenVirtualMethodData {
3394 Sema *S;
3395 CXXMethodDecl *Method;
3396 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3397 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3398 };
3399}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003400
3401/// \brief Member lookup function that determines whether a given C++
3402/// method overloads virtual methods in a base class without overriding any,
3403/// to be used with CXXRecordDecl::lookupInBases().
3404static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3405 CXXBasePath &Path,
3406 void *UserData) {
3407 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3408
3409 FindHiddenVirtualMethodData &Data
3410 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3411
3412 DeclarationName Name = Data.Method->getDeclName();
3413 assert(Name.getNameKind() == DeclarationName::Identifier);
3414
3415 bool foundSameNameMethod = false;
3416 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3417 for (Path.Decls = BaseRecord->lookup(Name);
3418 Path.Decls.first != Path.Decls.second;
3419 ++Path.Decls.first) {
3420 NamedDecl *D = *Path.Decls.first;
3421 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003422 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003423 foundSameNameMethod = true;
3424 // Interested only in hidden virtual methods.
3425 if (!MD->isVirtual())
3426 continue;
3427 // If the method we are checking overrides a method from its base
3428 // don't warn about the other overloaded methods.
3429 if (!Data.S->IsOverload(Data.Method, MD, false))
3430 return true;
3431 // Collect the overload only if its hidden.
3432 if (!Data.OverridenAndUsingBaseMethods.count(MD))
3433 overloadedMethods.push_back(MD);
3434 }
3435 }
3436
3437 if (foundSameNameMethod)
3438 Data.OverloadedMethods.append(overloadedMethods.begin(),
3439 overloadedMethods.end());
3440 return foundSameNameMethod;
3441}
3442
3443/// \brief See if a method overloads virtual methods in a base class without
3444/// overriding any.
3445void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
3446 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
3447 MD->getLocation()) == Diagnostic::Ignored)
3448 return;
3449 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
3450 return;
3451
3452 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
3453 /*bool RecordPaths=*/false,
3454 /*bool DetectVirtual=*/false);
3455 FindHiddenVirtualMethodData Data;
3456 Data.Method = MD;
3457 Data.S = this;
3458
3459 // Keep the base methods that were overriden or introduced in the subclass
3460 // by 'using' in a set. A base method not in this set is hidden.
3461 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
3462 res.first != res.second; ++res.first) {
3463 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
3464 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
3465 E = MD->end_overridden_methods();
3466 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003467 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003468 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
3469 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003470 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003471 }
3472
3473 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
3474 !Data.OverloadedMethods.empty()) {
3475 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
3476 << MD << (Data.OverloadedMethods.size() > 1);
3477
3478 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3479 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3480 Diag(overloadedMD->getLocation(),
3481 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3482 }
3483 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003484}
3485
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003486void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00003487 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003488 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003489 SourceLocation RBrac,
3490 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003491 if (!TagDecl)
3492 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003493
Douglas Gregor42af25f2009-05-11 19:58:34 +00003494 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003495
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003496 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00003497 // strict aliasing violation!
3498 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003499 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00003500
Douglas Gregor23c94db2010-07-02 17:43:08 +00003501 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00003502 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003503}
3504
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003505/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3506/// special functions, such as the default constructor, copy
3507/// constructor, or destructor, to the given C++ class (C++
3508/// [special]p1). This routine can only be executed just before the
3509/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003510void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00003511 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00003512 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003513
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00003514 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00003515 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003516
Douglas Gregora376d102010-07-02 21:50:04 +00003517 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3518 ++ASTContext::NumImplicitCopyAssignmentOperators;
3519
3520 // If we have a dynamic class, then the copy assignment operator may be
3521 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3522 // it shows up in the right place in the vtable and that we diagnose
3523 // problems with the implicit exception specification.
3524 if (ClassDecl->isDynamicClass())
3525 DeclareImplicitCopyAssignment(ClassDecl);
3526 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003527
Douglas Gregor4923aa22010-07-02 20:37:36 +00003528 if (!ClassDecl->hasUserDeclaredDestructor()) {
3529 ++ASTContext::NumImplicitDestructors;
3530
3531 // If we have a dynamic class, then the destructor may be virtual, so we
3532 // have to declare the destructor immediately. This ensures that, e.g., it
3533 // shows up in the right place in the vtable and that we diagnose problems
3534 // with the implicit exception specification.
3535 if (ClassDecl->isDynamicClass())
3536 DeclareImplicitDestructor(ClassDecl);
3537 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003538}
3539
Francois Pichet8387e2a2011-04-22 22:18:13 +00003540void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3541 if (!D)
3542 return;
3543
3544 int NumParamList = D->getNumTemplateParameterLists();
3545 for (int i = 0; i < NumParamList; i++) {
3546 TemplateParameterList* Params = D->getTemplateParameterList(i);
3547 for (TemplateParameterList::iterator Param = Params->begin(),
3548 ParamEnd = Params->end();
3549 Param != ParamEnd; ++Param) {
3550 NamedDecl *Named = cast<NamedDecl>(*Param);
3551 if (Named->getDeclName()) {
3552 S->AddDecl(Named);
3553 IdResolver.AddDecl(Named);
3554 }
3555 }
3556 }
3557}
3558
John McCalld226f652010-08-21 09:40:31 +00003559void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003560 if (!D)
3561 return;
3562
3563 TemplateParameterList *Params = 0;
3564 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3565 Params = Template->getTemplateParameters();
3566 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3567 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3568 Params = PartialSpec->getTemplateParameters();
3569 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003570 return;
3571
Douglas Gregor6569d682009-05-27 23:11:45 +00003572 for (TemplateParameterList::iterator Param = Params->begin(),
3573 ParamEnd = Params->end();
3574 Param != ParamEnd; ++Param) {
3575 NamedDecl *Named = cast<NamedDecl>(*Param);
3576 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003577 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003578 IdResolver.AddDecl(Named);
3579 }
3580 }
3581}
3582
John McCalld226f652010-08-21 09:40:31 +00003583void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003584 if (!RecordD) return;
3585 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003586 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003587 PushDeclContext(S, Record);
3588}
3589
John McCalld226f652010-08-21 09:40:31 +00003590void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003591 if (!RecordD) return;
3592 PopDeclContext();
3593}
3594
Douglas Gregor72b505b2008-12-16 21:30:33 +00003595/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3596/// parsing a top-level (non-nested) C++ class, and we are now
3597/// parsing those parts of the given Method declaration that could
3598/// not be parsed earlier (C++ [class.mem]p2), such as default
3599/// arguments. This action should enter the scope of the given
3600/// Method declaration as if we had just parsed the qualified method
3601/// name. However, it should not bring the parameters into scope;
3602/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003603void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003604}
3605
3606/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3607/// C++ method declaration. We're (re-)introducing the given
3608/// function parameter into scope for use in parsing later parts of
3609/// the method declaration. For example, we could see an
3610/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003611void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003612 if (!ParamD)
3613 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003614
John McCalld226f652010-08-21 09:40:31 +00003615 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003616
3617 // If this parameter has an unparsed default argument, clear it out
3618 // to make way for the parsed default argument.
3619 if (Param->hasUnparsedDefaultArg())
3620 Param->setDefaultArg(0);
3621
John McCalld226f652010-08-21 09:40:31 +00003622 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003623 if (Param->getDeclName())
3624 IdResolver.AddDecl(Param);
3625}
3626
3627/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3628/// processing the delayed method declaration for Method. The method
3629/// declaration is now considered finished. There may be a separate
3630/// ActOnStartOfFunctionDef action later (not necessarily
3631/// immediately!) for this method, if it was also defined inside the
3632/// class body.
John McCalld226f652010-08-21 09:40:31 +00003633void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003634 if (!MethodD)
3635 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003636
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003637 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003638
John McCalld226f652010-08-21 09:40:31 +00003639 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003640
3641 // Now that we have our default arguments, check the constructor
3642 // again. It could produce additional diagnostics or affect whether
3643 // the class has implicitly-declared destructors, among other
3644 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003645 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3646 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003647
3648 // Check the default arguments, which we may have added.
3649 if (!Method->isInvalidDecl())
3650 CheckCXXDefaultArguments(Method);
3651}
3652
Douglas Gregor42a552f2008-11-05 20:51:48 +00003653/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003654/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003655/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003656/// emit diagnostics and set the invalid bit to true. In any case, the type
3657/// will be updated to reflect a well-formed type for the constructor and
3658/// returned.
3659QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003660 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003661 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003662
3663 // C++ [class.ctor]p3:
3664 // A constructor shall not be virtual (10.3) or static (9.4). A
3665 // constructor can be invoked for a const, volatile or const
3666 // volatile object. A constructor shall not be declared const,
3667 // volatile, or const volatile (9.3.2).
3668 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003669 if (!D.isInvalidType())
3670 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3671 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3672 << SourceRange(D.getIdentifierLoc());
3673 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003674 }
John McCalld931b082010-08-26 03:08:43 +00003675 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003676 if (!D.isInvalidType())
3677 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3678 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3679 << SourceRange(D.getIdentifierLoc());
3680 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003681 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003682 }
Mike Stump1eb44332009-09-09 15:08:12 +00003683
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003684 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003685 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003686 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003687 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3688 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003689 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003690 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3691 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003692 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003693 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3694 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003695 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003696 }
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Douglas Gregorc938c162011-01-26 05:01:58 +00003698 // C++0x [class.ctor]p4:
3699 // A constructor shall not be declared with a ref-qualifier.
3700 if (FTI.hasRefQualifier()) {
3701 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3702 << FTI.RefQualifierIsLValueRef
3703 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3704 D.setInvalidType();
3705 }
3706
Douglas Gregor42a552f2008-11-05 20:51:48 +00003707 // Rebuild the function type "R" without any type qualifiers (in
3708 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003709 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003710 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003711 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3712 return R;
3713
3714 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3715 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003716 EPI.RefQualifier = RQ_None;
3717
Chris Lattner65401802009-04-25 08:28:21 +00003718 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003719 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003720}
3721
Douglas Gregor72b505b2008-12-16 21:30:33 +00003722/// CheckConstructor - Checks a fully-formed constructor for
3723/// well-formedness, issuing any diagnostics required. Returns true if
3724/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003725void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003726 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003727 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3728 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003729 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003730
3731 // C++ [class.copy]p3:
3732 // A declaration of a constructor for a class X is ill-formed if
3733 // its first parameter is of type (optionally cv-qualified) X and
3734 // either there are no other parameters or else all other
3735 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003736 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003737 ((Constructor->getNumParams() == 1) ||
3738 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003739 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3740 Constructor->getTemplateSpecializationKind()
3741 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003742 QualType ParamType = Constructor->getParamDecl(0)->getType();
3743 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3744 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003745 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003746 const char *ConstRef
3747 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3748 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003749 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003750 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003751
3752 // FIXME: Rather that making the constructor invalid, we should endeavor
3753 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003754 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003755 }
3756 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003757}
3758
John McCall15442822010-08-04 01:04:25 +00003759/// CheckDestructor - Checks a fully-formed destructor definition for
3760/// well-formedness, issuing any diagnostics required. Returns true
3761/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003762bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003763 CXXRecordDecl *RD = Destructor->getParent();
3764
3765 if (Destructor->isVirtual()) {
3766 SourceLocation Loc;
3767
3768 if (!Destructor->isImplicit())
3769 Loc = Destructor->getLocation();
3770 else
3771 Loc = RD->getLocation();
3772
3773 // If we have a virtual destructor, look up the deallocation function
3774 FunctionDecl *OperatorDelete = 0;
3775 DeclarationName Name =
3776 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003777 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003778 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003779
3780 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003781
3782 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003783 }
Anders Carlsson37909802009-11-30 21:24:50 +00003784
3785 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003786}
3787
Mike Stump1eb44332009-09-09 15:08:12 +00003788static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003789FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3790 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3791 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003792 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003793}
3794
Douglas Gregor42a552f2008-11-05 20:51:48 +00003795/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3796/// the well-formednes of the destructor declarator @p D with type @p
3797/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003798/// emit diagnostics and set the declarator to invalid. Even if this happens,
3799/// will be updated to reflect a well-formed type for the destructor and
3800/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003801QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003802 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003803 // C++ [class.dtor]p1:
3804 // [...] A typedef-name that names a class is a class-name
3805 // (7.1.3); however, a typedef-name that names a class shall not
3806 // be used as the identifier in the declarator for a destructor
3807 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003808 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00003809 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00003810 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00003811 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003812 else if (const TemplateSpecializationType *TST =
3813 DeclaratorType->getAs<TemplateSpecializationType>())
3814 if (TST->isTypeAlias())
3815 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
3816 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003817
3818 // C++ [class.dtor]p2:
3819 // A destructor is used to destroy objects of its class type. A
3820 // destructor takes no parameters, and no return type can be
3821 // specified for it (not even void). The address of a destructor
3822 // shall not be taken. A destructor shall not be static. A
3823 // destructor can be invoked for a const, volatile or const
3824 // volatile object. A destructor shall not be declared const,
3825 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003826 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003827 if (!D.isInvalidType())
3828 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3829 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003830 << SourceRange(D.getIdentifierLoc())
3831 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3832
John McCalld931b082010-08-26 03:08:43 +00003833 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003834 }
Chris Lattner65401802009-04-25 08:28:21 +00003835 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003836 // Destructors don't have return types, but the parser will
3837 // happily parse something like:
3838 //
3839 // class X {
3840 // float ~X();
3841 // };
3842 //
3843 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003844 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3845 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3846 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003847 }
Mike Stump1eb44332009-09-09 15:08:12 +00003848
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003849 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003850 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003851 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003852 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3853 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003854 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003855 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3856 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003857 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003858 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3859 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003860 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003861 }
3862
Douglas Gregorc938c162011-01-26 05:01:58 +00003863 // C++0x [class.dtor]p2:
3864 // A destructor shall not be declared with a ref-qualifier.
3865 if (FTI.hasRefQualifier()) {
3866 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3867 << FTI.RefQualifierIsLValueRef
3868 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3869 D.setInvalidType();
3870 }
3871
Douglas Gregor42a552f2008-11-05 20:51:48 +00003872 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003873 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003874 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3875
3876 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003877 FTI.freeArgs();
3878 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003879 }
3880
Mike Stump1eb44332009-09-09 15:08:12 +00003881 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003882 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003883 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003884 D.setInvalidType();
3885 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003886
3887 // Rebuild the function type "R" without any type qualifiers or
3888 // parameters (in case any of the errors above fired) and with
3889 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003890 // types.
John McCalle23cf432010-12-14 08:05:40 +00003891 if (!D.isInvalidType())
3892 return R;
3893
Douglas Gregord92ec472010-07-01 05:10:53 +00003894 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003895 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3896 EPI.Variadic = false;
3897 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003898 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003899 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003900}
3901
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003902/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3903/// well-formednes of the conversion function declarator @p D with
3904/// type @p R. If there are any errors in the declarator, this routine
3905/// will emit diagnostics and return true. Otherwise, it will return
3906/// false. Either way, the type @p R will be updated to reflect a
3907/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003908void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003909 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003910 // C++ [class.conv.fct]p1:
3911 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003912 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003913 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003914 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003915 if (!D.isInvalidType())
3916 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3917 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3918 << SourceRange(D.getIdentifierLoc());
3919 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003920 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003921 }
John McCalla3f81372010-04-13 00:04:31 +00003922
3923 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3924
Chris Lattner6e475012009-04-25 08:35:12 +00003925 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003926 // Conversion functions don't have return types, but the parser will
3927 // happily parse something like:
3928 //
3929 // class X {
3930 // float operator bool();
3931 // };
3932 //
3933 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003934 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3935 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3936 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003937 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003938 }
3939
John McCalla3f81372010-04-13 00:04:31 +00003940 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3941
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003942 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003943 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003944 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3945
3946 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003947 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003948 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003949 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003950 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003951 D.setInvalidType();
3952 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003953
John McCalla3f81372010-04-13 00:04:31 +00003954 // Diagnose "&operator bool()" and other such nonsense. This
3955 // is actually a gcc extension which we don't support.
3956 if (Proto->getResultType() != ConvType) {
3957 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3958 << Proto->getResultType();
3959 D.setInvalidType();
3960 ConvType = Proto->getResultType();
3961 }
3962
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003963 // C++ [class.conv.fct]p4:
3964 // The conversion-type-id shall not represent a function type nor
3965 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003966 if (ConvType->isArrayType()) {
3967 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3968 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003969 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003970 } else if (ConvType->isFunctionType()) {
3971 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3972 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003973 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003974 }
3975
3976 // Rebuild the function type "R" without any parameters (in case any
3977 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003978 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003979 if (D.isInvalidType())
3980 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003981
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003982 // C++0x explicit conversion operators.
3983 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003984 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003985 diag::warn_explicit_conversion_functions)
3986 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003987}
3988
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003989/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3990/// the declaration of the given C++ conversion function. This routine
3991/// is responsible for recording the conversion function in the C++
3992/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003993Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003994 assert(Conversion && "Expected to receive a conversion function declaration");
3995
Douglas Gregor9d350972008-12-12 08:25:50 +00003996 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003997
3998 // Make sure we aren't redeclaring the conversion function.
3999 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004000
4001 // C++ [class.conv.fct]p1:
4002 // [...] A conversion function is never used to convert a
4003 // (possibly cv-qualified) object to the (possibly cv-qualified)
4004 // same object type (or a reference to it), to a (possibly
4005 // cv-qualified) base class of that type (or a reference to it),
4006 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00004007 // FIXME: Suppress this warning if the conversion function ends up being a
4008 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00004009 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004010 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00004011 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004012 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004013 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4014 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00004015 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004016 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004017 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4018 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00004019 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004020 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004021 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00004022 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004023 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004024 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00004025 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004026 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004027 }
4028
Douglas Gregore80622f2010-09-29 04:25:11 +00004029 if (FunctionTemplateDecl *ConversionTemplate
4030 = Conversion->getDescribedFunctionTemplate())
4031 return ConversionTemplate;
4032
John McCalld226f652010-08-21 09:40:31 +00004033 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004034}
4035
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004036//===----------------------------------------------------------------------===//
4037// Namespace Handling
4038//===----------------------------------------------------------------------===//
4039
John McCallea318642010-08-26 09:15:37 +00004040
4041
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004042/// ActOnStartNamespaceDef - This is called at the start of a namespace
4043/// definition.
John McCalld226f652010-08-21 09:40:31 +00004044Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00004045 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004046 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00004047 SourceLocation IdentLoc,
4048 IdentifierInfo *II,
4049 SourceLocation LBrace,
4050 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004051 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4052 // For anonymous namespace, take the location of the left brace.
4053 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00004054 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004055 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004056 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004057
4058 Scope *DeclRegionScope = NamespcScope->getParent();
4059
Anders Carlsson2a3503d2010-02-07 01:09:23 +00004060 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4061
John McCall90f14502010-12-10 02:59:44 +00004062 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4063 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004064
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004065 if (II) {
4066 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00004067 // The identifier in an original-namespace-definition shall not
4068 // have been previously defined in the declarative region in
4069 // which the original-namespace-definition appears. The
4070 // identifier in an original-namespace-definition is the name of
4071 // the namespace. Subsequently in that declarative region, it is
4072 // treated as an original-namespace-name.
4073 //
4074 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00004075 // look through using directives, just look for any ordinary names.
4076
4077 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4078 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4079 Decl::IDNS_Namespace;
4080 NamedDecl *PrevDecl = 0;
4081 for (DeclContext::lookup_result R
4082 = CurContext->getRedeclContext()->lookup(II);
4083 R.first != R.second; ++R.first) {
4084 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4085 PrevDecl = *R.first;
4086 break;
4087 }
4088 }
4089
Douglas Gregor44b43212008-12-11 16:49:14 +00004090 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4091 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004092 if (Namespc->isInline() != OrigNS->isInline()) {
4093 // inline-ness must match
4094 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4095 << Namespc->isInline();
4096 Diag(OrigNS->getLocation(), diag::note_previous_definition);
4097 Namespc->setInvalidDecl();
4098 // Recover by ignoring the new namespace's inline status.
4099 Namespc->setInline(OrigNS->isInline());
4100 }
4101
Douglas Gregor44b43212008-12-11 16:49:14 +00004102 // Attach this namespace decl to the chain of extended namespace
4103 // definitions.
4104 OrigNS->setNextNamespace(Namespc);
4105 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004106
Mike Stump1eb44332009-09-09 15:08:12 +00004107 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00004108 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00004109 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00004110 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004111 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004112 } else if (PrevDecl) {
4113 // This is an invalid name redefinition.
4114 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4115 << Namespc->getDeclName();
4116 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4117 Namespc->setInvalidDecl();
4118 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004119 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004120 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004121 // This is the first "real" definition of the namespace "std", so update
4122 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004123 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004124 // We had already defined a dummy namespace "std". Link this new
4125 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004126 StdNS->setNextNamespace(Namespc);
4127 StdNS->setLocation(IdentLoc);
4128 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004129 }
4130
4131 // Make our StdNamespace cache point at the first real definition of the
4132 // "std" namespace.
4133 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00004134 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004135
4136 PushOnScopeChains(Namespc, DeclRegionScope);
4137 } else {
John McCall9aeed322009-10-01 00:25:31 +00004138 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00004139 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00004140
4141 // Link the anonymous namespace into its parent.
4142 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004143 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00004144 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4145 PrevDecl = TU->getAnonymousNamespace();
4146 TU->setAnonymousNamespace(Namespc);
4147 } else {
4148 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4149 PrevDecl = ND->getAnonymousNamespace();
4150 ND->setAnonymousNamespace(Namespc);
4151 }
4152
4153 // Link the anonymous namespace with its previous declaration.
4154 if (PrevDecl) {
4155 assert(PrevDecl->isAnonymousNamespace());
4156 assert(!PrevDecl->getNextNamespace());
4157 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4158 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004159
4160 if (Namespc->isInline() != PrevDecl->isInline()) {
4161 // inline-ness must match
4162 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4163 << Namespc->isInline();
4164 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4165 Namespc->setInvalidDecl();
4166 // Recover by ignoring the new namespace's inline status.
4167 Namespc->setInline(PrevDecl->isInline());
4168 }
John McCall5fdd7642009-12-16 02:06:49 +00004169 }
John McCall9aeed322009-10-01 00:25:31 +00004170
Douglas Gregora4181472010-03-24 00:46:35 +00004171 CurContext->addDecl(Namespc);
4172
John McCall9aeed322009-10-01 00:25:31 +00004173 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4174 // behaves as if it were replaced by
4175 // namespace unique { /* empty body */ }
4176 // using namespace unique;
4177 // namespace unique { namespace-body }
4178 // where all occurrences of 'unique' in a translation unit are
4179 // replaced by the same identifier and this identifier differs
4180 // from all other identifiers in the entire program.
4181
4182 // We just create the namespace with an empty name and then add an
4183 // implicit using declaration, just like the standard suggests.
4184 //
4185 // CodeGen enforces the "universally unique" aspect by giving all
4186 // declarations semantically contained within an anonymous
4187 // namespace internal linkage.
4188
John McCall5fdd7642009-12-16 02:06:49 +00004189 if (!PrevDecl) {
4190 UsingDirectiveDecl* UD
4191 = UsingDirectiveDecl::Create(Context, CurContext,
4192 /* 'using' */ LBrace,
4193 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00004194 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00004195 /* identifier */ SourceLocation(),
4196 Namespc,
4197 /* Ancestor */ CurContext);
4198 UD->setImplicit();
4199 CurContext->addDecl(UD);
4200 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004201 }
4202
4203 // Although we could have an invalid decl (i.e. the namespace name is a
4204 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00004205 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4206 // for the namespace has the declarations that showed up in that particular
4207 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00004208 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00004209 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004210}
4211
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004212/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4213/// is a namespace alias, returns the namespace it points to.
4214static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4215 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4216 return AD->getNamespace();
4217 return dyn_cast_or_null<NamespaceDecl>(D);
4218}
4219
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004220/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4221/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00004222void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004223 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4224 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004225 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004226 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004227 if (Namespc->hasAttr<VisibilityAttr>())
4228 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004229}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004230
John McCall384aff82010-08-25 07:42:41 +00004231CXXRecordDecl *Sema::getStdBadAlloc() const {
4232 return cast_or_null<CXXRecordDecl>(
4233 StdBadAlloc.get(Context.getExternalSource()));
4234}
4235
4236NamespaceDecl *Sema::getStdNamespace() const {
4237 return cast_or_null<NamespaceDecl>(
4238 StdNamespace.get(Context.getExternalSource()));
4239}
4240
Douglas Gregor66992202010-06-29 17:53:46 +00004241/// \brief Retrieve the special "std" namespace, which may require us to
4242/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004243NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00004244 if (!StdNamespace) {
4245 // The "std" namespace has not yet been defined, so build one implicitly.
4246 StdNamespace = NamespaceDecl::Create(Context,
4247 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004248 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00004249 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004250 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00004251 }
4252
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004253 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00004254}
4255
Douglas Gregor9172aa62011-03-26 22:25:30 +00004256/// \brief Determine whether a using statement is in a context where it will be
4257/// apply in all contexts.
4258static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4259 switch (CurContext->getDeclKind()) {
4260 case Decl::TranslationUnit:
4261 return true;
4262 case Decl::LinkageSpec:
4263 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4264 default:
4265 return false;
4266 }
4267}
4268
John McCalld226f652010-08-21 09:40:31 +00004269Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004270 SourceLocation UsingLoc,
4271 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004272 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004273 SourceLocation IdentLoc,
4274 IdentifierInfo *NamespcName,
4275 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00004276 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4277 assert(NamespcName && "Invalid NamespcName.");
4278 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00004279
4280 // This can only happen along a recovery path.
4281 while (S->getFlags() & Scope::TemplateParamScope)
4282 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004283 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00004284
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004285 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00004286 NestedNameSpecifier *Qualifier = 0;
4287 if (SS.isSet())
4288 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4289
Douglas Gregoreb11cd02009-01-14 22:20:51 +00004290 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004291 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4292 LookupParsedName(R, S, &SS);
4293 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004294 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004295
Douglas Gregor66992202010-06-29 17:53:46 +00004296 if (R.empty()) {
4297 // Allow "using namespace std;" or "using namespace ::std;" even if
4298 // "std" hasn't been defined yet, for GCC compatibility.
4299 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4300 NamespcName->isStr("std")) {
4301 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004302 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00004303 R.resolveKind();
4304 }
4305 // Otherwise, attempt typo correction.
4306 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4307 CTC_NoKeywords, 0)) {
4308 if (R.getAsSingle<NamespaceDecl>() ||
4309 R.getAsSingle<NamespaceAliasDecl>()) {
4310 if (DeclContext *DC = computeDeclContext(SS, false))
4311 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4312 << NamespcName << DC << Corrected << SS.getRange()
4313 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4314 else
4315 Diag(IdentLoc, diag::err_using_directive_suggest)
4316 << NamespcName << Corrected
4317 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4318 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4319 << Corrected;
4320
4321 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004322 } else {
4323 R.clear();
4324 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00004325 }
4326 }
4327 }
4328
John McCallf36e02d2009-10-09 21:13:30 +00004329 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004330 NamedDecl *Named = R.getFoundDecl();
4331 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4332 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004333 // C++ [namespace.udir]p1:
4334 // A using-directive specifies that the names in the nominated
4335 // namespace can be used in the scope in which the
4336 // using-directive appears after the using-directive. During
4337 // unqualified name lookup (3.4.1), the names appear as if they
4338 // were declared in the nearest enclosing namespace which
4339 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00004340 // namespace. [Note: in this context, "contains" means "contains
4341 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004342
4343 // Find enclosing context containing both using-directive and
4344 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004345 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004346 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4347 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4348 CommonAncestor = CommonAncestor->getParent();
4349
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004350 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00004351 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004352 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004353
Douglas Gregor9172aa62011-03-26 22:25:30 +00004354 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00004355 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004356 Diag(IdentLoc, diag::warn_using_directive_in_header);
4357 }
4358
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004359 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004360 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00004361 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00004362 }
4363
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004364 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00004365 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004366}
4367
4368void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4369 // If scope has associated entity, then using directive is at namespace
4370 // or translation unit scope. We add UsingDirectiveDecls, into
4371 // it's lookup structure.
4372 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004373 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004374 else
4375 // Otherwise it is block-sope. using-directives will affect lookup
4376 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00004377 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004378}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004379
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004380
John McCalld226f652010-08-21 09:40:31 +00004381Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00004382 AccessSpecifier AS,
4383 bool HasUsingKeyword,
4384 SourceLocation UsingLoc,
4385 CXXScopeSpec &SS,
4386 UnqualifiedId &Name,
4387 AttributeList *AttrList,
4388 bool IsTypeName,
4389 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004390 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00004391
Douglas Gregor12c118a2009-11-04 16:30:06 +00004392 switch (Name.getKind()) {
4393 case UnqualifiedId::IK_Identifier:
4394 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00004395 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004396 case UnqualifiedId::IK_ConversionFunctionId:
4397 break;
4398
4399 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00004400 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00004401 // C++0x inherited constructors.
4402 if (getLangOptions().CPlusPlus0x) break;
4403
Douglas Gregor12c118a2009-11-04 16:30:06 +00004404 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4405 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004406 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004407
4408 case UnqualifiedId::IK_DestructorName:
4409 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4410 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004411 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004412
4413 case UnqualifiedId::IK_TemplateId:
4414 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4415 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00004416 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004417 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004418
4419 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4420 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00004421 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00004422 return 0;
John McCall604e7f12009-12-08 07:46:18 +00004423
John McCall60fa3cf2009-12-11 02:10:03 +00004424 // Warn about using declarations.
4425 // TODO: store that the declaration was written without 'using' and
4426 // talk about access decls instead of using decls in the
4427 // diagnostics.
4428 if (!HasUsingKeyword) {
4429 UsingLoc = Name.getSourceRange().getBegin();
4430
4431 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00004432 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00004433 }
4434
Douglas Gregor56c04582010-12-16 00:46:58 +00004435 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4436 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4437 return 0;
4438
John McCall9488ea12009-11-17 05:59:44 +00004439 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004440 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004441 /* IsInstantiation */ false,
4442 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00004443 if (UD)
4444 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00004445
John McCalld226f652010-08-21 09:40:31 +00004446 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00004447}
4448
Douglas Gregor09acc982010-07-07 23:08:52 +00004449/// \brief Determine whether a using declaration considers the given
4450/// declarations as "equivalent", e.g., if they are redeclarations of
4451/// the same entity or are both typedefs of the same type.
4452static bool
4453IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4454 bool &SuppressRedeclaration) {
4455 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4456 SuppressRedeclaration = false;
4457 return true;
4458 }
4459
Richard Smith162e1c12011-04-15 14:24:37 +00004460 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4461 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00004462 SuppressRedeclaration = true;
4463 return Context.hasSameType(TD1->getUnderlyingType(),
4464 TD2->getUnderlyingType());
4465 }
4466
4467 return false;
4468}
4469
4470
John McCall9f54ad42009-12-10 09:41:52 +00004471/// Determines whether to create a using shadow decl for a particular
4472/// decl, given the set of decls existing prior to this using lookup.
4473bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4474 const LookupResult &Previous) {
4475 // Diagnose finding a decl which is not from a base class of the
4476 // current class. We do this now because there are cases where this
4477 // function will silently decide not to build a shadow decl, which
4478 // will pre-empt further diagnostics.
4479 //
4480 // We don't need to do this in C++0x because we do the check once on
4481 // the qualifier.
4482 //
4483 // FIXME: diagnose the following if we care enough:
4484 // struct A { int foo; };
4485 // struct B : A { using A::foo; };
4486 // template <class T> struct C : A {};
4487 // template <class T> struct D : C<T> { using B::foo; } // <---
4488 // This is invalid (during instantiation) in C++03 because B::foo
4489 // resolves to the using decl in B, which is not a base class of D<T>.
4490 // We can't diagnose it immediately because C<T> is an unknown
4491 // specialization. The UsingShadowDecl in D<T> then points directly
4492 // to A::foo, which will look well-formed when we instantiate.
4493 // The right solution is to not collapse the shadow-decl chain.
4494 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4495 DeclContext *OrigDC = Orig->getDeclContext();
4496
4497 // Handle enums and anonymous structs.
4498 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4499 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4500 while (OrigRec->isAnonymousStructOrUnion())
4501 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4502
4503 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4504 if (OrigDC == CurContext) {
4505 Diag(Using->getLocation(),
4506 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004507 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004508 Diag(Orig->getLocation(), diag::note_using_decl_target);
4509 return true;
4510 }
4511
Douglas Gregordc355712011-02-25 00:36:19 +00004512 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00004513 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004514 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00004515 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00004516 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004517 Diag(Orig->getLocation(), diag::note_using_decl_target);
4518 return true;
4519 }
4520 }
4521
4522 if (Previous.empty()) return false;
4523
4524 NamedDecl *Target = Orig;
4525 if (isa<UsingShadowDecl>(Target))
4526 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4527
John McCalld7533ec2009-12-11 02:33:26 +00004528 // If the target happens to be one of the previous declarations, we
4529 // don't have a conflict.
4530 //
4531 // FIXME: but we might be increasing its access, in which case we
4532 // should redeclare it.
4533 NamedDecl *NonTag = 0, *Tag = 0;
4534 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4535 I != E; ++I) {
4536 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00004537 bool Result;
4538 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4539 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00004540
4541 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4542 }
4543
John McCall9f54ad42009-12-10 09:41:52 +00004544 if (Target->isFunctionOrFunctionTemplate()) {
4545 FunctionDecl *FD;
4546 if (isa<FunctionTemplateDecl>(Target))
4547 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4548 else
4549 FD = cast<FunctionDecl>(Target);
4550
4551 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00004552 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00004553 case Ovl_Overload:
4554 return false;
4555
4556 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00004557 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004558 break;
4559
4560 // We found a decl with the exact signature.
4561 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004562 // If we're in a record, we want to hide the target, so we
4563 // return true (without a diagnostic) to tell the caller not to
4564 // build a shadow decl.
4565 if (CurContext->isRecord())
4566 return true;
4567
4568 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00004569 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004570 break;
4571 }
4572
4573 Diag(Target->getLocation(), diag::note_using_decl_target);
4574 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4575 return true;
4576 }
4577
4578 // Target is not a function.
4579
John McCall9f54ad42009-12-10 09:41:52 +00004580 if (isa<TagDecl>(Target)) {
4581 // No conflict between a tag and a non-tag.
4582 if (!Tag) return false;
4583
John McCall41ce66f2009-12-10 19:51:03 +00004584 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004585 Diag(Target->getLocation(), diag::note_using_decl_target);
4586 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4587 return true;
4588 }
4589
4590 // No conflict between a tag and a non-tag.
4591 if (!NonTag) return false;
4592
John McCall41ce66f2009-12-10 19:51:03 +00004593 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004594 Diag(Target->getLocation(), diag::note_using_decl_target);
4595 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4596 return true;
4597}
4598
John McCall9488ea12009-11-17 05:59:44 +00004599/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004600UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004601 UsingDecl *UD,
4602 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004603
4604 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004605 NamedDecl *Target = Orig;
4606 if (isa<UsingShadowDecl>(Target)) {
4607 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4608 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004609 }
4610
4611 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004612 = UsingShadowDecl::Create(Context, CurContext,
4613 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004614 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004615
4616 Shadow->setAccess(UD->getAccess());
4617 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4618 Shadow->setInvalidDecl();
4619
John McCall9488ea12009-11-17 05:59:44 +00004620 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004621 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004622 else
John McCall604e7f12009-12-08 07:46:18 +00004623 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004624
John McCall604e7f12009-12-08 07:46:18 +00004625
John McCall9f54ad42009-12-10 09:41:52 +00004626 return Shadow;
4627}
John McCall604e7f12009-12-08 07:46:18 +00004628
John McCall9f54ad42009-12-10 09:41:52 +00004629/// Hides a using shadow declaration. This is required by the current
4630/// using-decl implementation when a resolvable using declaration in a
4631/// class is followed by a declaration which would hide or override
4632/// one or more of the using decl's targets; for example:
4633///
4634/// struct Base { void foo(int); };
4635/// struct Derived : Base {
4636/// using Base::foo;
4637/// void foo(int);
4638/// };
4639///
4640/// The governing language is C++03 [namespace.udecl]p12:
4641///
4642/// When a using-declaration brings names from a base class into a
4643/// derived class scope, member functions in the derived class
4644/// override and/or hide member functions with the same name and
4645/// parameter types in a base class (rather than conflicting).
4646///
4647/// There are two ways to implement this:
4648/// (1) optimistically create shadow decls when they're not hidden
4649/// by existing declarations, or
4650/// (2) don't create any shadow decls (or at least don't make them
4651/// visible) until we've fully parsed/instantiated the class.
4652/// The problem with (1) is that we might have to retroactively remove
4653/// a shadow decl, which requires several O(n) operations because the
4654/// decl structures are (very reasonably) not designed for removal.
4655/// (2) avoids this but is very fiddly and phase-dependent.
4656void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004657 if (Shadow->getDeclName().getNameKind() ==
4658 DeclarationName::CXXConversionFunctionName)
4659 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4660
John McCall9f54ad42009-12-10 09:41:52 +00004661 // Remove it from the DeclContext...
4662 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004663
John McCall9f54ad42009-12-10 09:41:52 +00004664 // ...and the scope, if applicable...
4665 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004666 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004667 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004668 }
4669
John McCall9f54ad42009-12-10 09:41:52 +00004670 // ...and the using decl.
4671 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4672
4673 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004674 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004675}
4676
John McCall7ba107a2009-11-18 02:36:19 +00004677/// Builds a using declaration.
4678///
4679/// \param IsInstantiation - Whether this call arises from an
4680/// instantiation of an unresolved using declaration. We treat
4681/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004682NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4683 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004684 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004685 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004686 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004687 bool IsInstantiation,
4688 bool IsTypeName,
4689 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004690 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004691 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004692 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004693
Anders Carlsson550b14b2009-08-28 05:49:21 +00004694 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004696 if (SS.isEmpty()) {
4697 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004698 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004699 }
Mike Stump1eb44332009-09-09 15:08:12 +00004700
John McCall9f54ad42009-12-10 09:41:52 +00004701 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004702 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004703 ForRedeclaration);
4704 Previous.setHideTags(false);
4705 if (S) {
4706 LookupName(Previous, S);
4707
4708 // It is really dumb that we have to do this.
4709 LookupResult::Filter F = Previous.makeFilter();
4710 while (F.hasNext()) {
4711 NamedDecl *D = F.next();
4712 if (!isDeclInScope(D, CurContext, S))
4713 F.erase();
4714 }
4715 F.done();
4716 } else {
4717 assert(IsInstantiation && "no scope in non-instantiation");
4718 assert(CurContext->isRecord() && "scope not record in instantiation");
4719 LookupQualifiedName(Previous, CurContext);
4720 }
4721
John McCall9f54ad42009-12-10 09:41:52 +00004722 // Check for invalid redeclarations.
4723 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4724 return 0;
4725
4726 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004727 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4728 return 0;
4729
John McCallaf8e6ed2009-11-12 03:15:40 +00004730 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004731 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00004732 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00004733 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004734 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004735 // FIXME: not all declaration name kinds are legal here
4736 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4737 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00004738 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004739 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004740 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004741 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4742 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004743 }
John McCalled976492009-12-04 22:46:56 +00004744 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004745 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4746 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004747 }
John McCalled976492009-12-04 22:46:56 +00004748 D->setAccess(AS);
4749 CurContext->addDecl(D);
4750
4751 if (!LookupContext) return D;
4752 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004753
John McCall77bb1aa2010-05-01 00:40:08 +00004754 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004755 UD->setInvalidDecl();
4756 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004757 }
4758
Sebastian Redlf677ea32011-02-05 19:23:19 +00004759 // Constructor inheriting using decls get special treatment.
4760 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004761 if (CheckInheritedConstructorUsingDecl(UD))
4762 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004763 return UD;
4764 }
4765
4766 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004767
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004768 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004769
John McCall604e7f12009-12-08 07:46:18 +00004770 // Unlike most lookups, we don't always want to hide tag
4771 // declarations: tag names are visible through the using declaration
4772 // even if hidden by ordinary names, *except* in a dependent context
4773 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004774 if (!IsInstantiation)
4775 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004776
John McCalla24dc2e2009-11-17 02:14:36 +00004777 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004778
John McCallf36e02d2009-10-09 21:13:30 +00004779 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004780 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004781 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004782 UD->setInvalidDecl();
4783 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004784 }
4785
John McCalled976492009-12-04 22:46:56 +00004786 if (R.isAmbiguous()) {
4787 UD->setInvalidDecl();
4788 return UD;
4789 }
Mike Stump1eb44332009-09-09 15:08:12 +00004790
John McCall7ba107a2009-11-18 02:36:19 +00004791 if (IsTypeName) {
4792 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004793 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004794 Diag(IdentLoc, diag::err_using_typename_non_type);
4795 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4796 Diag((*I)->getUnderlyingDecl()->getLocation(),
4797 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004798 UD->setInvalidDecl();
4799 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004800 }
4801 } else {
4802 // If we asked for a non-typename and we got a type, error out,
4803 // but only if this is an instantiation of an unresolved using
4804 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004805 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004806 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4807 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004808 UD->setInvalidDecl();
4809 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004810 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004811 }
4812
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004813 // C++0x N2914 [namespace.udecl]p6:
4814 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004815 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004816 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4817 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004818 UD->setInvalidDecl();
4819 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004820 }
Mike Stump1eb44332009-09-09 15:08:12 +00004821
John McCall9f54ad42009-12-10 09:41:52 +00004822 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4823 if (!CheckUsingShadowDecl(UD, *I, Previous))
4824 BuildUsingShadowDecl(S, UD, *I);
4825 }
John McCall9488ea12009-11-17 05:59:44 +00004826
4827 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004828}
4829
Sebastian Redlf677ea32011-02-05 19:23:19 +00004830/// Additional checks for a using declaration referring to a constructor name.
4831bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4832 if (UD->isTypeName()) {
4833 // FIXME: Cannot specify typename when specifying constructor
4834 return true;
4835 }
4836
Douglas Gregordc355712011-02-25 00:36:19 +00004837 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004838 assert(SourceType &&
4839 "Using decl naming constructor doesn't have type in scope spec.");
4840 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4841
4842 // Check whether the named type is a direct base class.
4843 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4844 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4845 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4846 BaseIt != BaseE; ++BaseIt) {
4847 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4848 if (CanonicalSourceType == BaseType)
4849 break;
4850 }
4851
4852 if (BaseIt == BaseE) {
4853 // Did not find SourceType in the bases.
4854 Diag(UD->getUsingLocation(),
4855 diag::err_using_decl_constructor_not_in_direct_base)
4856 << UD->getNameInfo().getSourceRange()
4857 << QualType(SourceType, 0) << TargetClass;
4858 return true;
4859 }
4860
4861 BaseIt->setInheritConstructors();
4862
4863 return false;
4864}
4865
John McCall9f54ad42009-12-10 09:41:52 +00004866/// Checks that the given using declaration is not an invalid
4867/// redeclaration. Note that this is checking only for the using decl
4868/// itself, not for any ill-formedness among the UsingShadowDecls.
4869bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4870 bool isTypeName,
4871 const CXXScopeSpec &SS,
4872 SourceLocation NameLoc,
4873 const LookupResult &Prev) {
4874 // C++03 [namespace.udecl]p8:
4875 // C++0x [namespace.udecl]p10:
4876 // A using-declaration is a declaration and can therefore be used
4877 // repeatedly where (and only where) multiple declarations are
4878 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004879 //
John McCall8a726212010-11-29 18:01:58 +00004880 // That's in non-member contexts.
4881 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004882 return false;
4883
4884 NestedNameSpecifier *Qual
4885 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4886
4887 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4888 NamedDecl *D = *I;
4889
4890 bool DTypename;
4891 NestedNameSpecifier *DQual;
4892 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4893 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00004894 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004895 } else if (UnresolvedUsingValueDecl *UD
4896 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4897 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00004898 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004899 } else if (UnresolvedUsingTypenameDecl *UD
4900 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4901 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00004902 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004903 } else continue;
4904
4905 // using decls differ if one says 'typename' and the other doesn't.
4906 // FIXME: non-dependent using decls?
4907 if (isTypeName != DTypename) continue;
4908
4909 // using decls differ if they name different scopes (but note that
4910 // template instantiation can cause this check to trigger when it
4911 // didn't before instantiation).
4912 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4913 Context.getCanonicalNestedNameSpecifier(DQual))
4914 continue;
4915
4916 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004917 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004918 return true;
4919 }
4920
4921 return false;
4922}
4923
John McCall604e7f12009-12-08 07:46:18 +00004924
John McCalled976492009-12-04 22:46:56 +00004925/// Checks that the given nested-name qualifier used in a using decl
4926/// in the current context is appropriately related to the current
4927/// scope. If an error is found, diagnoses it and returns true.
4928bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4929 const CXXScopeSpec &SS,
4930 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004931 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004932
John McCall604e7f12009-12-08 07:46:18 +00004933 if (!CurContext->isRecord()) {
4934 // C++03 [namespace.udecl]p3:
4935 // C++0x [namespace.udecl]p8:
4936 // A using-declaration for a class member shall be a member-declaration.
4937
4938 // If we weren't able to compute a valid scope, it must be a
4939 // dependent class scope.
4940 if (!NamedContext || NamedContext->isRecord()) {
4941 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4942 << SS.getRange();
4943 return true;
4944 }
4945
4946 // Otherwise, everything is known to be fine.
4947 return false;
4948 }
4949
4950 // The current scope is a record.
4951
4952 // If the named context is dependent, we can't decide much.
4953 if (!NamedContext) {
4954 // FIXME: in C++0x, we can diagnose if we can prove that the
4955 // nested-name-specifier does not refer to a base class, which is
4956 // still possible in some cases.
4957
4958 // Otherwise we have to conservatively report that things might be
4959 // okay.
4960 return false;
4961 }
4962
4963 if (!NamedContext->isRecord()) {
4964 // Ideally this would point at the last name in the specifier,
4965 // but we don't have that level of source info.
4966 Diag(SS.getRange().getBegin(),
4967 diag::err_using_decl_nested_name_specifier_is_not_class)
4968 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4969 return true;
4970 }
4971
Douglas Gregor6fb07292010-12-21 07:41:49 +00004972 if (!NamedContext->isDependentContext() &&
4973 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4974 return true;
4975
John McCall604e7f12009-12-08 07:46:18 +00004976 if (getLangOptions().CPlusPlus0x) {
4977 // C++0x [namespace.udecl]p3:
4978 // In a using-declaration used as a member-declaration, the
4979 // nested-name-specifier shall name a base class of the class
4980 // being defined.
4981
4982 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4983 cast<CXXRecordDecl>(NamedContext))) {
4984 if (CurContext == NamedContext) {
4985 Diag(NameLoc,
4986 diag::err_using_decl_nested_name_specifier_is_current_class)
4987 << SS.getRange();
4988 return true;
4989 }
4990
4991 Diag(SS.getRange().getBegin(),
4992 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4993 << (NestedNameSpecifier*) SS.getScopeRep()
4994 << cast<CXXRecordDecl>(CurContext)
4995 << SS.getRange();
4996 return true;
4997 }
4998
4999 return false;
5000 }
5001
5002 // C++03 [namespace.udecl]p4:
5003 // A using-declaration used as a member-declaration shall refer
5004 // to a member of a base class of the class being defined [etc.].
5005
5006 // Salient point: SS doesn't have to name a base class as long as
5007 // lookup only finds members from base classes. Therefore we can
5008 // diagnose here only if we can prove that that can't happen,
5009 // i.e. if the class hierarchies provably don't intersect.
5010
5011 // TODO: it would be nice if "definitely valid" results were cached
5012 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5013 // need to be repeated.
5014
5015 struct UserData {
5016 llvm::DenseSet<const CXXRecordDecl*> Bases;
5017
5018 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5019 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5020 Data->Bases.insert(Base);
5021 return true;
5022 }
5023
5024 bool hasDependentBases(const CXXRecordDecl *Class) {
5025 return !Class->forallBases(collect, this);
5026 }
5027
5028 /// Returns true if the base is dependent or is one of the
5029 /// accumulated base classes.
5030 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5031 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5032 return !Data->Bases.count(Base);
5033 }
5034
5035 bool mightShareBases(const CXXRecordDecl *Class) {
5036 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5037 }
5038 };
5039
5040 UserData Data;
5041
5042 // Returns false if we find a dependent base.
5043 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5044 return false;
5045
5046 // Returns false if the class has a dependent base or if it or one
5047 // of its bases is present in the base set of the current context.
5048 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5049 return false;
5050
5051 Diag(SS.getRange().getBegin(),
5052 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5053 << (NestedNameSpecifier*) SS.getScopeRep()
5054 << cast<CXXRecordDecl>(CurContext)
5055 << SS.getRange();
5056
5057 return true;
John McCalled976492009-12-04 22:46:56 +00005058}
5059
Richard Smith162e1c12011-04-15 14:24:37 +00005060Decl *Sema::ActOnAliasDeclaration(Scope *S,
5061 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005062 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00005063 SourceLocation UsingLoc,
5064 UnqualifiedId &Name,
5065 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00005066 // Skip up to the relevant declaration scope.
5067 while (S->getFlags() & Scope::TemplateParamScope)
5068 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00005069 assert((S->getFlags() & Scope::DeclScope) &&
5070 "got alias-declaration outside of declaration scope");
5071
5072 if (Type.isInvalid())
5073 return 0;
5074
5075 bool Invalid = false;
5076 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5077 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00005078 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00005079
5080 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5081 return 0;
5082
5083 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005084 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00005085 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005086 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5087 TInfo->getTypeLoc().getBeginLoc());
5088 }
Richard Smith162e1c12011-04-15 14:24:37 +00005089
5090 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5091 LookupName(Previous, S);
5092
5093 // Warn about shadowing the name of a template parameter.
5094 if (Previous.isSingleResult() &&
5095 Previous.getFoundDecl()->isTemplateParameter()) {
5096 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5097 Previous.getFoundDecl()))
5098 Invalid = true;
5099 Previous.clear();
5100 }
5101
5102 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5103 "name in alias declaration must be an identifier");
5104 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5105 Name.StartLocation,
5106 Name.Identifier, TInfo);
5107
5108 NewTD->setAccess(AS);
5109
5110 if (Invalid)
5111 NewTD->setInvalidDecl();
5112
Richard Smith3e4c6c42011-05-05 21:57:07 +00005113 CheckTypedefForVariablyModifiedType(S, NewTD);
5114 Invalid |= NewTD->isInvalidDecl();
5115
Richard Smith162e1c12011-04-15 14:24:37 +00005116 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005117
5118 NamedDecl *NewND;
5119 if (TemplateParamLists.size()) {
5120 TypeAliasTemplateDecl *OldDecl = 0;
5121 TemplateParameterList *OldTemplateParams = 0;
5122
5123 if (TemplateParamLists.size() != 1) {
5124 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5125 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5126 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5127 }
5128 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5129
5130 // Only consider previous declarations in the same scope.
5131 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5132 /*ExplicitInstantiationOrSpecialization*/false);
5133 if (!Previous.empty()) {
5134 Redeclaration = true;
5135
5136 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5137 if (!OldDecl && !Invalid) {
5138 Diag(UsingLoc, diag::err_redefinition_different_kind)
5139 << Name.Identifier;
5140
5141 NamedDecl *OldD = Previous.getRepresentativeDecl();
5142 if (OldD->getLocation().isValid())
5143 Diag(OldD->getLocation(), diag::note_previous_definition);
5144
5145 Invalid = true;
5146 }
5147
5148 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5149 if (TemplateParameterListsAreEqual(TemplateParams,
5150 OldDecl->getTemplateParameters(),
5151 /*Complain=*/true,
5152 TPL_TemplateMatch))
5153 OldTemplateParams = OldDecl->getTemplateParameters();
5154 else
5155 Invalid = true;
5156
5157 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5158 if (!Invalid &&
5159 !Context.hasSameType(OldTD->getUnderlyingType(),
5160 NewTD->getUnderlyingType())) {
5161 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5162 // but we can't reasonably accept it.
5163 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5164 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5165 if (OldTD->getLocation().isValid())
5166 Diag(OldTD->getLocation(), diag::note_previous_definition);
5167 Invalid = true;
5168 }
5169 }
5170 }
5171
5172 // Merge any previous default template arguments into our parameters,
5173 // and check the parameter list.
5174 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5175 TPC_TypeAliasTemplate))
5176 return 0;
5177
5178 TypeAliasTemplateDecl *NewDecl =
5179 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5180 Name.Identifier, TemplateParams,
5181 NewTD);
5182
5183 NewDecl->setAccess(AS);
5184
5185 if (Invalid)
5186 NewDecl->setInvalidDecl();
5187 else if (OldDecl)
5188 NewDecl->setPreviousDeclaration(OldDecl);
5189
5190 NewND = NewDecl;
5191 } else {
5192 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5193 NewND = NewTD;
5194 }
Richard Smith162e1c12011-04-15 14:24:37 +00005195
5196 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00005197 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00005198
Richard Smith3e4c6c42011-05-05 21:57:07 +00005199 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00005200}
5201
John McCalld226f652010-08-21 09:40:31 +00005202Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005203 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005204 SourceLocation AliasLoc,
5205 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005206 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005207 SourceLocation IdentLoc,
5208 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00005209
Anders Carlsson81c85c42009-03-28 23:53:49 +00005210 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005211 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5212 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00005213
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005214 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00005215 NamedDecl *PrevDecl
5216 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5217 ForRedeclaration);
5218 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5219 PrevDecl = 0;
5220
5221 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00005222 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005223 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00005224 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00005225 // FIXME: At some point, we'll want to create the (redundant)
5226 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00005227 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00005228 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00005229 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00005230 }
Mike Stump1eb44332009-09-09 15:08:12 +00005231
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005232 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5233 diag::err_redefinition_different_kind;
5234 Diag(AliasLoc, DiagID) << Alias;
5235 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00005236 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005237 }
5238
John McCalla24dc2e2009-11-17 02:14:36 +00005239 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005240 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005241
John McCallf36e02d2009-10-09 21:13:30 +00005242 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005243 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5244 CTC_NoKeywords, 0)) {
5245 if (R.getAsSingle<NamespaceDecl>() ||
5246 R.getAsSingle<NamespaceAliasDecl>()) {
5247 if (DeclContext *DC = computeDeclContext(SS, false))
5248 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5249 << Ident << DC << Corrected << SS.getRange()
5250 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5251 else
5252 Diag(IdentLoc, diag::err_using_directive_suggest)
5253 << Ident << Corrected
5254 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5255
5256 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5257 << Corrected;
5258
5259 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00005260 } else {
5261 R.clear();
5262 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005263 }
5264 }
5265
5266 if (R.empty()) {
5267 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005268 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005269 }
Anders Carlsson5721c682009-03-28 06:42:02 +00005270 }
Mike Stump1eb44332009-09-09 15:08:12 +00005271
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005272 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00005273 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00005274 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00005275 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00005276
John McCall3dbd3d52010-02-16 06:53:13 +00005277 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00005278 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00005279}
5280
Douglas Gregor39957dc2010-05-01 15:04:51 +00005281namespace {
5282 /// \brief Scoped object used to handle the state changes required in Sema
5283 /// to implicitly define the body of a C++ member function;
5284 class ImplicitlyDefinedFunctionScope {
5285 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00005286 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00005287
5288 public:
5289 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00005290 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00005291 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00005292 S.PushFunctionScope();
5293 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5294 }
5295
5296 ~ImplicitlyDefinedFunctionScope() {
5297 S.PopExpressionEvaluationContext();
5298 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00005299 }
5300 };
5301}
5302
Sebastian Redl751025d2010-09-13 22:02:47 +00005303static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
5304 CXXRecordDecl *D) {
5305 ASTContext &Context = Self.Context;
5306 QualType ClassType = Context.getTypeDeclType(D);
5307 DeclarationName ConstructorName
5308 = Context.DeclarationNames.getCXXConstructorName(
5309 Context.getCanonicalType(ClassType.getUnqualifiedType()));
5310
5311 DeclContext::lookup_const_iterator Con, ConEnd;
5312 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
5313 Con != ConEnd; ++Con) {
5314 // FIXME: In C++0x, a constructor template can be a default constructor.
5315 if (isa<FunctionTemplateDecl>(*Con))
5316 continue;
5317
5318 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
5319 if (Constructor->isDefaultConstructor())
5320 return Constructor;
5321 }
5322 return 0;
5323}
5324
Sean Hunt001cad92011-05-10 00:49:42 +00005325Sema::ImplicitExceptionSpecification
5326Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005327 // C++ [except.spec]p14:
5328 // An implicitly declared special member function (Clause 12) shall have an
5329 // exception-specification. [...]
5330 ImplicitExceptionSpecification ExceptSpec(Context);
5331
Sebastian Redl60618fa2011-03-12 11:50:43 +00005332 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005333 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5334 BEnd = ClassDecl->bases_end();
5335 B != BEnd; ++B) {
5336 if (B->isVirtual()) // Handled below.
5337 continue;
5338
Douglas Gregor18274032010-07-03 00:47:00 +00005339 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5340 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntcdee3fe2011-05-11 22:34:38 +00005341 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005342 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00005343 else if (CXXConstructorDecl *Constructor
5344 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005345 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005346 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005347 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005348
5349 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005350 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5351 BEnd = ClassDecl->vbases_end();
5352 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00005353 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5354 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntcdee3fe2011-05-11 22:34:38 +00005355 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005356 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5357 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005358 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005359 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005360 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005361 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005362
5363 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005364 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5365 FEnd = ClassDecl->field_end();
5366 F != FEnd; ++F) {
5367 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00005368 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5369 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Sean Huntcdee3fe2011-05-11 22:34:38 +00005370 if (FieldClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005371 ExceptSpec.CalledDecl(
5372 DeclareImplicitDefaultConstructor(FieldClassDecl));
5373 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00005374 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005375 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005376 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005377 }
John McCalle23cf432010-12-14 08:05:40 +00005378
Sean Hunt001cad92011-05-10 00:49:42 +00005379 return ExceptSpec;
5380}
5381
5382CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5383 CXXRecordDecl *ClassDecl) {
5384 // C++ [class.ctor]p5:
5385 // A default constructor for a class X is a constructor of class X
5386 // that can be called without an argument. If there is no
5387 // user-declared constructor for class X, a default constructor is
5388 // implicitly declared. An implicitly-declared default constructor
5389 // is an inline public member of its class.
5390 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5391 "Should not build implicit default constructor!");
5392
5393 ImplicitExceptionSpecification Spec =
5394 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5395 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00005396
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005397 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00005398 CanQualType ClassType
5399 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005400 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005401 DeclarationName Name
5402 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005403 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005404 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005405 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00005406 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005407 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00005408 /*TInfo=*/0,
5409 /*isExplicit=*/false,
5410 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005411 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005412 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00005413 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005414 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00005415 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00005416
5417 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00005418 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005419
5420 // Do not delete this yet if we're in a template
5421 if (!ClassDecl->isDependentType() &&
5422 ShouldDeleteDefaultConstructor(DefaultCon))
5423 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00005424
Douglas Gregor23c94db2010-07-02 17:43:08 +00005425 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00005426 PushOnScopeChains(DefaultCon, S, false);
5427 ClassDecl->addDecl(DefaultCon);
5428
Douglas Gregor32df23e2010-07-01 22:02:46 +00005429 return DefaultCon;
5430}
5431
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005432void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5433 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00005434 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00005435 !Constructor->isUsed(false) && !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00005436 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Anders Carlssonf6513ed2010-04-23 16:04:08 +00005438 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00005439 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00005440
Douglas Gregor39957dc2010-05-01 15:04:51 +00005441 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005442 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00005443 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005444 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005445 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00005446 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00005447 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005448 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00005449 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005450
5451 SourceLocation Loc = Constructor->getLocation();
5452 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5453
5454 Constructor->setUsed();
5455 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005456
5457 if (ASTMutationListener *L = getASTMutationListener()) {
5458 L->CompletedImplicitDefinition(Constructor);
5459 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005460}
5461
Sebastian Redlf677ea32011-02-05 19:23:19 +00005462void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
5463 // We start with an initial pass over the base classes to collect those that
5464 // inherit constructors from. If there are none, we can forgo all further
5465 // processing.
5466 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
5467 BasesVector BasesToInheritFrom;
5468 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
5469 BaseE = ClassDecl->bases_end();
5470 BaseIt != BaseE; ++BaseIt) {
5471 if (BaseIt->getInheritConstructors()) {
5472 QualType Base = BaseIt->getType();
5473 if (Base->isDependentType()) {
5474 // If we inherit constructors from anything that is dependent, just
5475 // abort processing altogether. We'll get another chance for the
5476 // instantiations.
5477 return;
5478 }
5479 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
5480 }
5481 }
5482 if (BasesToInheritFrom.empty())
5483 return;
5484
5485 // Now collect the constructors that we already have in the current class.
5486 // Those take precedence over inherited constructors.
5487 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5488 // unless there is a user-declared constructor with the same signature in
5489 // the class where the using-declaration appears.
5490 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5491 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5492 CtorE = ClassDecl->ctor_end();
5493 CtorIt != CtorE; ++CtorIt) {
5494 ExistingConstructors.insert(
5495 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5496 }
5497
5498 Scope *S = getScopeForContext(ClassDecl);
5499 DeclarationName CreatedCtorName =
5500 Context.DeclarationNames.getCXXConstructorName(
5501 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5502
5503 // Now comes the true work.
5504 // First, we keep a map from constructor types to the base that introduced
5505 // them. Needed for finding conflicting constructors. We also keep the
5506 // actually inserted declarations in there, for pretty diagnostics.
5507 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5508 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5509 ConstructorToSourceMap InheritedConstructors;
5510 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5511 BaseE = BasesToInheritFrom.end();
5512 BaseIt != BaseE; ++BaseIt) {
5513 const RecordType *Base = *BaseIt;
5514 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5515 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5516 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5517 CtorE = BaseDecl->ctor_end();
5518 CtorIt != CtorE; ++CtorIt) {
5519 // Find the using declaration for inheriting this base's constructors.
5520 DeclarationName Name =
5521 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5522 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5523 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5524 SourceLocation UsingLoc = UD ? UD->getLocation() :
5525 ClassDecl->getLocation();
5526
5527 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5528 // from the class X named in the using-declaration consists of actual
5529 // constructors and notional constructors that result from the
5530 // transformation of defaulted parameters as follows:
5531 // - all non-template default constructors of X, and
5532 // - for each non-template constructor of X that has at least one
5533 // parameter with a default argument, the set of constructors that
5534 // results from omitting any ellipsis parameter specification and
5535 // successively omitting parameters with a default argument from the
5536 // end of the parameter-type-list.
5537 CXXConstructorDecl *BaseCtor = *CtorIt;
5538 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5539 const FunctionProtoType *BaseCtorType =
5540 BaseCtor->getType()->getAs<FunctionProtoType>();
5541
5542 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5543 maxParams = BaseCtor->getNumParams();
5544 params <= maxParams; ++params) {
5545 // Skip default constructors. They're never inherited.
5546 if (params == 0)
5547 continue;
5548 // Skip copy and move constructors for the same reason.
5549 if (CanBeCopyOrMove && params == 1)
5550 continue;
5551
5552 // Build up a function type for this particular constructor.
5553 // FIXME: The working paper does not consider that the exception spec
5554 // for the inheriting constructor might be larger than that of the
5555 // source. This code doesn't yet, either.
5556 const Type *NewCtorType;
5557 if (params == maxParams)
5558 NewCtorType = BaseCtorType;
5559 else {
5560 llvm::SmallVector<QualType, 16> Args;
5561 for (unsigned i = 0; i < params; ++i) {
5562 Args.push_back(BaseCtorType->getArgType(i));
5563 }
5564 FunctionProtoType::ExtProtoInfo ExtInfo =
5565 BaseCtorType->getExtProtoInfo();
5566 ExtInfo.Variadic = false;
5567 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5568 Args.data(), params, ExtInfo)
5569 .getTypePtr();
5570 }
5571 const Type *CanonicalNewCtorType =
5572 Context.getCanonicalType(NewCtorType);
5573
5574 // Now that we have the type, first check if the class already has a
5575 // constructor with this signature.
5576 if (ExistingConstructors.count(CanonicalNewCtorType))
5577 continue;
5578
5579 // Then we check if we have already declared an inherited constructor
5580 // with this signature.
5581 std::pair<ConstructorToSourceMap::iterator, bool> result =
5582 InheritedConstructors.insert(std::make_pair(
5583 CanonicalNewCtorType,
5584 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5585 if (!result.second) {
5586 // Already in the map. If it came from a different class, that's an
5587 // error. Not if it's from the same.
5588 CanQualType PreviousBase = result.first->second.first;
5589 if (CanonicalBase != PreviousBase) {
5590 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5591 const CXXConstructorDecl *PrevBaseCtor =
5592 PrevCtor->getInheritedConstructor();
5593 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5594
5595 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5596 Diag(BaseCtor->getLocation(),
5597 diag::note_using_decl_constructor_conflict_current_ctor);
5598 Diag(PrevBaseCtor->getLocation(),
5599 diag::note_using_decl_constructor_conflict_previous_ctor);
5600 Diag(PrevCtor->getLocation(),
5601 diag::note_using_decl_constructor_conflict_previous_using);
5602 }
5603 continue;
5604 }
5605
5606 // OK, we're there, now add the constructor.
5607 // C++0x [class.inhctor]p8: [...] that would be performed by a
5608 // user-writtern inline constructor [...]
5609 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5610 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005611 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5612 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005613 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00005614 NewCtor->setAccess(BaseCtor->getAccess());
5615
5616 // Build up the parameter decls and add them.
5617 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5618 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005619 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5620 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005621 /*IdentifierInfo=*/0,
5622 BaseCtorType->getArgType(i),
5623 /*TInfo=*/0, SC_None,
5624 SC_None, /*DefaultArg=*/0));
5625 }
5626 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5627 NewCtor->setInheritedConstructor(BaseCtor);
5628
5629 PushOnScopeChains(NewCtor, S, false);
5630 ClassDecl->addDecl(NewCtor);
5631 result.first->second.second = NewCtor;
5632 }
5633 }
5634 }
5635}
5636
Sean Huntcb45a0f2011-05-12 22:46:25 +00005637Sema::ImplicitExceptionSpecification
5638Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005639 // C++ [except.spec]p14:
5640 // An implicitly declared special member function (Clause 12) shall have
5641 // an exception-specification.
5642 ImplicitExceptionSpecification ExceptSpec(Context);
5643
5644 // Direct base-class destructors.
5645 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5646 BEnd = ClassDecl->bases_end();
5647 B != BEnd; ++B) {
5648 if (B->isVirtual()) // Handled below.
5649 continue;
5650
5651 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5652 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005653 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005654 }
5655
5656 // Virtual base-class destructors.
5657 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5658 BEnd = ClassDecl->vbases_end();
5659 B != BEnd; ++B) {
5660 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5661 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005662 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005663 }
5664
5665 // Field destructors.
5666 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5667 FEnd = ClassDecl->field_end();
5668 F != FEnd; ++F) {
5669 if (const RecordType *RecordTy
5670 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5671 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005672 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005673 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005674
Sean Huntcb45a0f2011-05-12 22:46:25 +00005675 return ExceptSpec;
5676}
5677
5678CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
5679 // C++ [class.dtor]p2:
5680 // If a class has no user-declared destructor, a destructor is
5681 // declared implicitly. An implicitly-declared destructor is an
5682 // inline public member of its class.
5683
5684 ImplicitExceptionSpecification Spec =
5685 ComputeDefaultedDtorExceptionSpec(ClassDecl);
5686 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
5687
Douglas Gregor4923aa22010-07-02 20:37:36 +00005688 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00005689 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00005690
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005691 CanQualType ClassType
5692 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005693 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005694 DeclarationName Name
5695 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005696 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005697 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00005698 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5699 /*isInline=*/true,
5700 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005701 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00005702 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005703 Destructor->setImplicit();
5704 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00005705
5706 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00005707 ++ASTContext::NumImplicitDestructorsDeclared;
5708
5709 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005710 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00005711 PushOnScopeChains(Destructor, S, false);
5712 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005713
5714 // This could be uniqued if it ever proves significant.
5715 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00005716
5717 if (ShouldDeleteDestructor(Destructor))
5718 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005719
5720 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00005721
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005722 return Destructor;
5723}
5724
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005725void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00005726 CXXDestructorDecl *Destructor) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00005727 assert((Destructor->isDefaulted() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005728 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00005729 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005730 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005731
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005732 if (Destructor->isInvalidDecl())
5733 return;
5734
Douglas Gregor39957dc2010-05-01 15:04:51 +00005735 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005736
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005737 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00005738 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5739 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00005740
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005741 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005742 Diag(CurrentLocation, diag::note_member_synthesized_at)
5743 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5744
5745 Destructor->setInvalidDecl();
5746 return;
5747 }
5748
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005749 SourceLocation Loc = Destructor->getLocation();
5750 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5751
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005752 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005753 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005754
5755 if (ASTMutationListener *L = getASTMutationListener()) {
5756 L->CompletedImplicitDefinition(Destructor);
5757 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005758}
5759
Douglas Gregor06a9f362010-05-01 20:49:11 +00005760/// \brief Builds a statement that copies the given entity from \p From to
5761/// \c To.
5762///
5763/// This routine is used to copy the members of a class with an
5764/// implicitly-declared copy assignment operator. When the entities being
5765/// copied are arrays, this routine builds for loops to copy them.
5766///
5767/// \param S The Sema object used for type-checking.
5768///
5769/// \param Loc The location where the implicit copy is being generated.
5770///
5771/// \param T The type of the expressions being copied. Both expressions must
5772/// have this type.
5773///
5774/// \param To The expression we are copying to.
5775///
5776/// \param From The expression we are copying from.
5777///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005778/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5779/// Otherwise, it's a non-static member subobject.
5780///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005781/// \param Depth Internal parameter recording the depth of the recursion.
5782///
5783/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005784static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005785BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005786 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005787 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005788 // C++0x [class.copy]p30:
5789 // Each subobject is assigned in the manner appropriate to its type:
5790 //
5791 // - if the subobject is of class type, the copy assignment operator
5792 // for the class is used (as if by explicit qualification; that is,
5793 // ignoring any possible virtual overriding functions in more derived
5794 // classes);
5795 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5796 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5797
5798 // Look for operator=.
5799 DeclarationName Name
5800 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5801 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5802 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5803
5804 // Filter out any result that isn't a copy-assignment operator.
5805 LookupResult::Filter F = OpLookup.makeFilter();
5806 while (F.hasNext()) {
5807 NamedDecl *D = F.next();
5808 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5809 if (Method->isCopyAssignmentOperator())
5810 continue;
5811
5812 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005813 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005814 F.done();
5815
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005816 // Suppress the protected check (C++ [class.protected]) for each of the
5817 // assignment operators we found. This strange dance is required when
5818 // we're assigning via a base classes's copy-assignment operator. To
5819 // ensure that we're getting the right base class subobject (without
5820 // ambiguities), we need to cast "this" to that subobject type; to
5821 // ensure that we don't go through the virtual call mechanism, we need
5822 // to qualify the operator= name with the base class (see below). However,
5823 // this means that if the base class has a protected copy assignment
5824 // operator, the protected member access check will fail. So, we
5825 // rewrite "protected" access to "public" access in this case, since we
5826 // know by construction that we're calling from a derived class.
5827 if (CopyingBaseSubobject) {
5828 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5829 L != LEnd; ++L) {
5830 if (L.getAccess() == AS_protected)
5831 L.setAccess(AS_public);
5832 }
5833 }
5834
Douglas Gregor06a9f362010-05-01 20:49:11 +00005835 // Create the nested-name-specifier that will be used to qualify the
5836 // reference to operator=; this is required to suppress the virtual
5837 // call mechanism.
5838 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00005839 SS.MakeTrivial(S.Context,
5840 NestedNameSpecifier::Create(S.Context, 0, false,
5841 T.getTypePtr()),
5842 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005843
5844 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005845 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005846 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005847 /*FirstQualifierInScope=*/0, OpLookup,
5848 /*TemplateArgs=*/0,
5849 /*SuppressQualifierCheck=*/true);
5850 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005851 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005852
5853 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005854
John McCall60d7b3a2010-08-24 06:29:42 +00005855 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005856 OpEqualRef.takeAs<Expr>(),
5857 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005858 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005859 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005860
5861 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005862 }
John McCallb0207482010-03-16 06:11:48 +00005863
Douglas Gregor06a9f362010-05-01 20:49:11 +00005864 // - if the subobject is of scalar type, the built-in assignment
5865 // operator is used.
5866 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5867 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005868 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005869 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005870 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005871
5872 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005873 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005874
5875 // - if the subobject is an array, each element is assigned, in the
5876 // manner appropriate to the element type;
5877
5878 // Construct a loop over the array bounds, e.g.,
5879 //
5880 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5881 //
5882 // that will copy each of the array elements.
5883 QualType SizeType = S.Context.getSizeType();
5884
5885 // Create the iteration variable.
5886 IdentifierInfo *IterationVarName = 0;
5887 {
5888 llvm::SmallString<8> Str;
5889 llvm::raw_svector_ostream OS(Str);
5890 OS << "__i" << Depth;
5891 IterationVarName = &S.Context.Idents.get(OS.str());
5892 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005893 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005894 IterationVarName, SizeType,
5895 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005896 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005897
5898 // Initialize the iteration variable to zero.
5899 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005900 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005901
5902 // Create a reference to the iteration variable; we'll use this several
5903 // times throughout.
5904 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005905 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005906 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5907
5908 // Create the DeclStmt that holds the iteration variable.
5909 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5910
5911 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005912 llvm::APInt Upper
5913 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005914 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005915 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005916 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5917 BO_NE, S.Context.BoolTy,
5918 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005919
5920 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005921 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005922 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5923 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005924
5925 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005926 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5927 IterationVarRef, Loc));
5928 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5929 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005930
5931 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005932 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5933 To, From, CopyingBaseSubobject,
5934 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005935 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005936 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005937
5938 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005939 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005940 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005941 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005942 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005943}
5944
Douglas Gregora376d102010-07-02 21:50:04 +00005945/// \brief Determine whether the given class has a copy assignment operator
5946/// that accepts a const-qualified argument.
5947static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5948 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5949
5950 if (!Class->hasDeclaredCopyAssignment())
5951 S.DeclareImplicitCopyAssignment(Class);
5952
5953 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5954 DeclarationName OpName
5955 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5956
5957 DeclContext::lookup_const_iterator Op, OpEnd;
5958 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5959 // C++ [class.copy]p9:
5960 // A user-declared copy assignment operator is a non-static non-template
5961 // member function of class X with exactly one parameter of type X, X&,
5962 // const X&, volatile X& or const volatile X&.
5963 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5964 if (!Method)
5965 continue;
5966
5967 if (Method->isStatic())
5968 continue;
5969 if (Method->getPrimaryTemplate())
5970 continue;
5971 const FunctionProtoType *FnType =
5972 Method->getType()->getAs<FunctionProtoType>();
5973 assert(FnType && "Overloaded operator has no prototype.");
5974 // Don't assert on this; an invalid decl might have been left in the AST.
5975 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5976 continue;
5977 bool AcceptsConst = true;
5978 QualType ArgType = FnType->getArgType(0);
5979 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5980 ArgType = Ref->getPointeeType();
5981 // Is it a non-const lvalue reference?
5982 if (!ArgType.isConstQualified())
5983 AcceptsConst = false;
5984 }
5985 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5986 continue;
5987
5988 // We have a single argument of type cv X or cv X&, i.e. we've found the
5989 // copy assignment operator. Return whether it accepts const arguments.
5990 return AcceptsConst;
5991 }
5992 assert(Class->isInvalidDecl() &&
5993 "No copy assignment operator declared in valid code.");
5994 return false;
5995}
5996
Douglas Gregor23c94db2010-07-02 17:43:08 +00005997CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005998 // Note: The following rules are largely analoguous to the copy
5999 // constructor rules. Note that virtual bases are not taken into account
6000 // for determining the argument type of the operator. Note also that
6001 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00006002
6003
Douglas Gregord3c35902010-07-01 16:36:15 +00006004 // C++ [class.copy]p10:
6005 // If the class definition does not explicitly declare a copy
6006 // assignment operator, one is declared implicitly.
6007 // The implicitly-defined copy assignment operator for a class X
6008 // will have the form
6009 //
6010 // X& X::operator=(const X&)
6011 //
6012 // if
6013 bool HasConstCopyAssignment = true;
6014
6015 // -- each direct base class B of X has a copy assignment operator
6016 // whose parameter is of type const B&, const volatile B& or B,
6017 // and
6018 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6019 BaseEnd = ClassDecl->bases_end();
6020 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6021 assert(!Base->getType()->isDependentType() &&
6022 "Cannot generate implicit members for class with dependent bases.");
6023 const CXXRecordDecl *BaseClassDecl
6024 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006025 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006026 }
6027
6028 // -- for all the nonstatic data members of X that are of a class
6029 // type M (or array thereof), each such class type has a copy
6030 // assignment operator whose parameter is of type const M&,
6031 // const volatile M& or M.
6032 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6033 FieldEnd = ClassDecl->field_end();
6034 HasConstCopyAssignment && Field != FieldEnd;
6035 ++Field) {
6036 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6037 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6038 const CXXRecordDecl *FieldClassDecl
6039 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006040 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006041 }
6042 }
6043
6044 // Otherwise, the implicitly declared copy assignment operator will
6045 // have the form
6046 //
6047 // X& X::operator=(X&)
6048 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6049 QualType RetType = Context.getLValueReferenceType(ArgType);
6050 if (HasConstCopyAssignment)
6051 ArgType = ArgType.withConst();
6052 ArgType = Context.getLValueReferenceType(ArgType);
6053
Douglas Gregorb87786f2010-07-01 17:48:08 +00006054 // C++ [except.spec]p14:
6055 // An implicitly declared special member function (Clause 12) shall have an
6056 // exception-specification. [...]
6057 ImplicitExceptionSpecification ExceptSpec(Context);
6058 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6059 BaseEnd = ClassDecl->bases_end();
6060 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00006061 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006062 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006063
6064 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6065 DeclareImplicitCopyAssignment(BaseClassDecl);
6066
Douglas Gregorb87786f2010-07-01 17:48:08 +00006067 if (CXXMethodDecl *CopyAssign
6068 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6069 ExceptSpec.CalledDecl(CopyAssign);
6070 }
6071 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6072 FieldEnd = ClassDecl->field_end();
6073 Field != FieldEnd;
6074 ++Field) {
6075 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6076 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00006077 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006078 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00006079
6080 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6081 DeclareImplicitCopyAssignment(FieldClassDecl);
6082
Douglas Gregorb87786f2010-07-01 17:48:08 +00006083 if (CXXMethodDecl *CopyAssign
6084 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6085 ExceptSpec.CalledDecl(CopyAssign);
6086 }
6087 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006088
Douglas Gregord3c35902010-07-01 16:36:15 +00006089 // An implicitly-declared copy assignment operator is an inline public
6090 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00006091 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00006092 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00006093 EPI.NumExceptions = ExceptSpec.size();
6094 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00006095 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006096 SourceLocation ClassLoc = ClassDecl->getLocation();
6097 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00006098 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006099 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00006100 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00006101 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00006102 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00006103 /*isInline=*/true,
6104 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00006105 CopyAssignment->setAccess(AS_public);
6106 CopyAssignment->setImplicit();
6107 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00006108
6109 // Add the parameter to the operator.
6110 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006111 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00006112 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006113 SC_None,
6114 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00006115 CopyAssignment->setParams(&FromParam, 1);
6116
Douglas Gregora376d102010-07-02 21:50:04 +00006117 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00006118 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
6119
Douglas Gregor23c94db2010-07-02 17:43:08 +00006120 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00006121 PushOnScopeChains(CopyAssignment, S, false);
6122 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006123
6124 AddOverriddenMethods(ClassDecl, CopyAssignment);
6125 return CopyAssignment;
6126}
6127
Douglas Gregor06a9f362010-05-01 20:49:11 +00006128void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6129 CXXMethodDecl *CopyAssignOperator) {
6130 assert((CopyAssignOperator->isImplicit() &&
6131 CopyAssignOperator->isOverloadedOperator() &&
6132 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006133 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006134 "DefineImplicitCopyAssignment called for wrong function");
6135
6136 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6137
6138 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6139 CopyAssignOperator->setInvalidDecl();
6140 return;
6141 }
6142
6143 CopyAssignOperator->setUsed();
6144
6145 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006146 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006147
6148 // C++0x [class.copy]p30:
6149 // The implicitly-defined or explicitly-defaulted copy assignment operator
6150 // for a non-union class X performs memberwise copy assignment of its
6151 // subobjects. The direct base classes of X are assigned first, in the
6152 // order of their declaration in the base-specifier-list, and then the
6153 // immediate non-static data members of X are assigned, in the order in
6154 // which they were declared in the class definition.
6155
6156 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00006157 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006158
6159 // The parameter for the "other" object, which we are copying from.
6160 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6161 Qualifiers OtherQuals = Other->getType().getQualifiers();
6162 QualType OtherRefType = Other->getType();
6163 if (const LValueReferenceType *OtherRef
6164 = OtherRefType->getAs<LValueReferenceType>()) {
6165 OtherRefType = OtherRef->getPointeeType();
6166 OtherQuals = OtherRefType.getQualifiers();
6167 }
6168
6169 // Our location for everything implicitly-generated.
6170 SourceLocation Loc = CopyAssignOperator->getLocation();
6171
6172 // Construct a reference to the "other" object. We'll be using this
6173 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00006174 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006175 assert(OtherRef && "Reference to parameter cannot fail!");
6176
6177 // Construct the "this" pointer. We'll be using this throughout the generated
6178 // ASTs.
6179 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6180 assert(This && "Reference to this cannot fail!");
6181
6182 // Assign base classes.
6183 bool Invalid = false;
6184 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6185 E = ClassDecl->bases_end(); Base != E; ++Base) {
6186 // Form the assignment:
6187 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6188 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00006189 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006190 Invalid = true;
6191 continue;
6192 }
6193
John McCallf871d0c2010-08-07 06:22:56 +00006194 CXXCastPath BasePath;
6195 BasePath.push_back(Base);
6196
Douglas Gregor06a9f362010-05-01 20:49:11 +00006197 // Construct the "from" expression, which is an implicit cast to the
6198 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00006199 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00006200 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6201 CK_UncheckedDerivedToBase,
6202 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006203
6204 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00006205 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006206
6207 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00006208 To = ImpCastExprToType(To.take(),
6209 Context.getCVRQualifiedType(BaseType,
6210 CopyAssignOperator->getTypeQualifiers()),
6211 CK_UncheckedDerivedToBase,
6212 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006213
6214 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00006215 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00006216 To.get(), From,
6217 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006218 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006219 Diag(CurrentLocation, diag::note_member_synthesized_at)
6220 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6221 CopyAssignOperator->setInvalidDecl();
6222 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006223 }
6224
6225 // Success! Record the copy.
6226 Statements.push_back(Copy.takeAs<Expr>());
6227 }
6228
6229 // \brief Reference to the __builtin_memcpy function.
6230 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006231 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006232 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006233
6234 // Assign non-static members.
6235 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6236 FieldEnd = ClassDecl->field_end();
6237 Field != FieldEnd; ++Field) {
6238 // Check for members of reference type; we can't copy those.
6239 if (Field->getType()->isReferenceType()) {
6240 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6241 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6242 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006243 Diag(CurrentLocation, diag::note_member_synthesized_at)
6244 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006245 Invalid = true;
6246 continue;
6247 }
6248
6249 // Check for members of const-qualified, non-class type.
6250 QualType BaseType = Context.getBaseElementType(Field->getType());
6251 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6252 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6253 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6254 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006255 Diag(CurrentLocation, diag::note_member_synthesized_at)
6256 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006257 Invalid = true;
6258 continue;
6259 }
6260
6261 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006262 if (FieldType->isIncompleteArrayType()) {
6263 assert(ClassDecl->hasFlexibleArrayMember() &&
6264 "Incomplete array type is not valid");
6265 continue;
6266 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006267
6268 // Build references to the field in the object we're copying from and to.
6269 CXXScopeSpec SS; // Intentionally empty
6270 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6271 LookupMemberName);
6272 MemberLookup.addDecl(*Field);
6273 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00006274 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00006275 Loc, /*IsArrow=*/false,
6276 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006277 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00006278 Loc, /*IsArrow=*/true,
6279 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006280 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6281 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6282
6283 // If the field should be copied with __builtin_memcpy rather than via
6284 // explicit assignments, do so. This optimization only applies for arrays
6285 // of scalars and arrays of class type with trivial copy-assignment
6286 // operators.
6287 if (FieldType->isArrayType() &&
6288 (!BaseType->isRecordType() ||
6289 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
6290 ->hasTrivialCopyAssignment())) {
6291 // Compute the size of the memory buffer to be copied.
6292 QualType SizeType = Context.getSizeType();
6293 llvm::APInt Size(Context.getTypeSize(SizeType),
6294 Context.getTypeSizeInChars(BaseType).getQuantity());
6295 for (const ConstantArrayType *Array
6296 = Context.getAsConstantArrayType(FieldType);
6297 Array;
6298 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00006299 llvm::APInt ArraySize
6300 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006301 Size *= ArraySize;
6302 }
6303
6304 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00006305 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6306 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006307
6308 bool NeedsCollectableMemCpy =
6309 (BaseType->isRecordType() &&
6310 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6311
6312 if (NeedsCollectableMemCpy) {
6313 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006314 // Create a reference to the __builtin_objc_memmove_collectable function.
6315 LookupResult R(*this,
6316 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006317 Loc, LookupOrdinaryName);
6318 LookupName(R, TUScope, true);
6319
6320 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6321 if (!CollectableMemCpy) {
6322 // Something went horribly wrong earlier, and we will have
6323 // complained about it.
6324 Invalid = true;
6325 continue;
6326 }
6327
6328 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6329 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00006330 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006331 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6332 }
6333 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006334 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006335 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006336 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6337 LookupOrdinaryName);
6338 LookupName(R, TUScope, true);
6339
6340 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6341 if (!BuiltinMemCpy) {
6342 // Something went horribly wrong earlier, and we will have complained
6343 // about it.
6344 Invalid = true;
6345 continue;
6346 }
6347
6348 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6349 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00006350 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006351 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6352 }
6353
John McCallca0408f2010-08-23 06:44:23 +00006354 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006355 CallArgs.push_back(To.takeAs<Expr>());
6356 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006357 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00006358 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006359 if (NeedsCollectableMemCpy)
6360 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00006361 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006362 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00006363 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006364 else
6365 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00006366 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006367 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00006368 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00006369
Douglas Gregor06a9f362010-05-01 20:49:11 +00006370 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
6371 Statements.push_back(Call.takeAs<Expr>());
6372 continue;
6373 }
6374
6375 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00006376 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00006377 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006378 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006379 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006380 Diag(CurrentLocation, diag::note_member_synthesized_at)
6381 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6382 CopyAssignOperator->setInvalidDecl();
6383 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006384 }
6385
6386 // Success! Record the copy.
6387 Statements.push_back(Copy.takeAs<Stmt>());
6388 }
6389
6390 if (!Invalid) {
6391 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00006392 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006393
John McCall60d7b3a2010-08-24 06:29:42 +00006394 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006395 if (Return.isInvalid())
6396 Invalid = true;
6397 else {
6398 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006399
6400 if (Trap.hasErrorOccurred()) {
6401 Diag(CurrentLocation, diag::note_member_synthesized_at)
6402 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6403 Invalid = true;
6404 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006405 }
6406 }
6407
6408 if (Invalid) {
6409 CopyAssignOperator->setInvalidDecl();
6410 return;
6411 }
6412
John McCall60d7b3a2010-08-24 06:29:42 +00006413 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00006414 /*isStmtExpr=*/false);
6415 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
6416 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006417
6418 if (ASTMutationListener *L = getASTMutationListener()) {
6419 L->CompletedImplicitDefinition(CopyAssignOperator);
6420 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006421}
6422
Douglas Gregor23c94db2010-07-02 17:43:08 +00006423CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
6424 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006425 // C++ [class.copy]p4:
6426 // If the class definition does not explicitly declare a copy
6427 // constructor, one is declared implicitly.
6428
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006429 // C++ [class.copy]p5:
6430 // The implicitly-declared copy constructor for a class X will
6431 // have the form
6432 //
6433 // X::X(const X&)
6434 //
6435 // if
6436 bool HasConstCopyConstructor = true;
6437
6438 // -- each direct or virtual base class B of X has a copy
6439 // constructor whose first parameter is of type const B& or
6440 // const volatile B&, and
6441 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6442 BaseEnd = ClassDecl->bases_end();
6443 HasConstCopyConstructor && Base != BaseEnd;
6444 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00006445 // Virtual bases are handled below.
6446 if (Base->isVirtual())
6447 continue;
6448
Douglas Gregor22584312010-07-02 23:41:54 +00006449 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00006450 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006451 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6452 DeclareImplicitCopyConstructor(BaseClassDecl);
6453
Douglas Gregor598a8542010-07-01 18:27:03 +00006454 HasConstCopyConstructor
6455 = BaseClassDecl->hasConstCopyConstructor(Context);
6456 }
6457
6458 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6459 BaseEnd = ClassDecl->vbases_end();
6460 HasConstCopyConstructor && Base != BaseEnd;
6461 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006462 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006463 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006464 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6465 DeclareImplicitCopyConstructor(BaseClassDecl);
6466
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006467 HasConstCopyConstructor
6468 = BaseClassDecl->hasConstCopyConstructor(Context);
6469 }
6470
6471 // -- for all the nonstatic data members of X that are of a
6472 // class type M (or array thereof), each such class type
6473 // has a copy constructor whose first parameter is of type
6474 // const M& or const volatile M&.
6475 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6476 FieldEnd = ClassDecl->field_end();
6477 HasConstCopyConstructor && Field != FieldEnd;
6478 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00006479 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006480 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006481 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00006482 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006483 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6484 DeclareImplicitCopyConstructor(FieldClassDecl);
6485
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006486 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00006487 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006488 }
6489 }
6490
6491 // Otherwise, the implicitly declared copy constructor will have
6492 // the form
6493 //
6494 // X::X(X&)
6495 QualType ClassType = Context.getTypeDeclType(ClassDecl);
6496 QualType ArgType = ClassType;
6497 if (HasConstCopyConstructor)
6498 ArgType = ArgType.withConst();
6499 ArgType = Context.getLValueReferenceType(ArgType);
6500
Douglas Gregor0d405db2010-07-01 20:59:04 +00006501 // C++ [except.spec]p14:
6502 // An implicitly declared special member function (Clause 12) shall have an
6503 // exception-specification. [...]
6504 ImplicitExceptionSpecification ExceptSpec(Context);
6505 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6506 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6507 BaseEnd = ClassDecl->bases_end();
6508 Base != BaseEnd;
6509 ++Base) {
6510 // Virtual bases are handled below.
6511 if (Base->isVirtual())
6512 continue;
6513
Douglas Gregor22584312010-07-02 23:41:54 +00006514 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006515 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006516 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6517 DeclareImplicitCopyConstructor(BaseClassDecl);
6518
Douglas Gregor0d405db2010-07-01 20:59:04 +00006519 if (CXXConstructorDecl *CopyConstructor
6520 = BaseClassDecl->getCopyConstructor(Context, Quals))
6521 ExceptSpec.CalledDecl(CopyConstructor);
6522 }
6523 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6524 BaseEnd = ClassDecl->vbases_end();
6525 Base != BaseEnd;
6526 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006527 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006528 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006529 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6530 DeclareImplicitCopyConstructor(BaseClassDecl);
6531
Douglas Gregor0d405db2010-07-01 20:59:04 +00006532 if (CXXConstructorDecl *CopyConstructor
6533 = BaseClassDecl->getCopyConstructor(Context, Quals))
6534 ExceptSpec.CalledDecl(CopyConstructor);
6535 }
6536 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6537 FieldEnd = ClassDecl->field_end();
6538 Field != FieldEnd;
6539 ++Field) {
6540 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6541 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006542 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006543 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006544 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6545 DeclareImplicitCopyConstructor(FieldClassDecl);
6546
Douglas Gregor0d405db2010-07-01 20:59:04 +00006547 if (CXXConstructorDecl *CopyConstructor
6548 = FieldClassDecl->getCopyConstructor(Context, Quals))
6549 ExceptSpec.CalledDecl(CopyConstructor);
6550 }
6551 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006552
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006553 // An implicitly-declared copy constructor is an inline public
6554 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00006555 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00006556 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00006557 EPI.NumExceptions = ExceptSpec.size();
6558 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006559 DeclarationName Name
6560 = Context.DeclarationNames.getCXXConstructorName(
6561 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006562 SourceLocation ClassLoc = ClassDecl->getLocation();
6563 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006564 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006565 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006566 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006567 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006568 /*TInfo=*/0,
6569 /*isExplicit=*/false,
6570 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006571 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006572 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006573 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6574
Douglas Gregor22584312010-07-02 23:41:54 +00006575 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00006576 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6577
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006578 // Add the parameter to the constructor.
6579 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006580 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006581 /*IdentifierInfo=*/0,
6582 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006583 SC_None,
6584 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006585 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00006586 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00006587 PushOnScopeChains(CopyConstructor, S, false);
6588 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006589
6590 return CopyConstructor;
6591}
6592
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006593void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6594 CXXConstructorDecl *CopyConstructor,
6595 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00006596 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00006597 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006598 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006599 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006600
Anders Carlsson63010a72010-04-23 16:24:12 +00006601 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006602 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006603
Douglas Gregor39957dc2010-05-01 15:04:51 +00006604 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006605 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006606
Sean Huntcbb67482011-01-08 20:30:50 +00006607 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006608 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00006609 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006610 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00006611 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006612 } else {
6613 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6614 CopyConstructor->getLocation(),
6615 MultiStmtArg(*this, 0, 0),
6616 /*isStmtExpr=*/false)
6617 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00006618 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006619
6620 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006621
6622 if (ASTMutationListener *L = getASTMutationListener()) {
6623 L->CompletedImplicitDefinition(CopyConstructor);
6624 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006625}
6626
John McCall60d7b3a2010-08-24 06:29:42 +00006627ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006628Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00006629 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00006630 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006631 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006632 unsigned ConstructKind,
6633 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006634 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006635
Douglas Gregor2f599792010-04-02 18:24:57 +00006636 // C++0x [class.copy]p34:
6637 // When certain criteria are met, an implementation is allowed to
6638 // omit the copy/move construction of a class object, even if the
6639 // copy/move constructor and/or destructor for the object have
6640 // side effects. [...]
6641 // - when a temporary class object that has not been bound to a
6642 // reference (12.2) would be copied/moved to a class object
6643 // with the same cv-unqualified type, the copy/move operation
6644 // can be omitted by constructing the temporary object
6645 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00006646 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00006647 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00006648 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00006649 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006650 }
Mike Stump1eb44332009-09-09 15:08:12 +00006651
6652 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006653 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006654 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006655}
6656
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006657/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6658/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006659ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006660Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6661 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00006662 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006663 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006664 unsigned ConstructKind,
6665 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00006666 unsigned NumExprs = ExprArgs.size();
6667 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006668
Nick Lewycky909a70d2011-03-25 01:44:32 +00006669 for (specific_attr_iterator<NonNullAttr>
6670 i = Constructor->specific_attr_begin<NonNullAttr>(),
6671 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6672 const NonNullAttr *NonNull = *i;
6673 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6674 }
6675
Douglas Gregor7edfb692009-11-23 12:27:39 +00006676 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00006677 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00006678 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00006679 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006680 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6681 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006682}
6683
Mike Stump1eb44332009-09-09 15:08:12 +00006684bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006685 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00006686 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00006687 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00006688 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00006689 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006690 move(Exprs), false, CXXConstructExpr::CK_Complete,
6691 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00006692 if (TempResult.isInvalid())
6693 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006694
Anders Carlssonda3f4e22009-08-25 05:12:04 +00006695 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00006696 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006697 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00006698 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00006699 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00006700
Anders Carlssonfe2de492009-08-25 05:18:00 +00006701 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00006702}
6703
John McCall68c6c9a2010-02-02 09:10:11 +00006704void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006705 if (VD->isInvalidDecl()) return;
6706
John McCall68c6c9a2010-02-02 09:10:11 +00006707 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006708 if (ClassDecl->isInvalidDecl()) return;
6709 if (ClassDecl->hasTrivialDestructor()) return;
6710 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00006711
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006712 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6713 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6714 CheckDestructorAccess(VD->getLocation(), Destructor,
6715 PDiag(diag::err_access_dtor_var)
6716 << VD->getDeclName()
6717 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00006718
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006719 if (!VD->hasGlobalStorage()) return;
6720
6721 // Emit warning for non-trivial dtor in global scope (a real global,
6722 // class-static, function-static).
6723 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6724
6725 // TODO: this should be re-enabled for static locals by !CXAAtExit
6726 if (!VD->isStaticLocal())
6727 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006728}
6729
Mike Stump1eb44332009-09-09 15:08:12 +00006730/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006731/// ActOnDeclarator, when a C++ direct initializer is present.
6732/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00006733void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006734 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006735 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00006736 SourceLocation RParenLoc,
6737 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00006738 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006739
6740 // If there is no declaration, there was an error parsing it. Just ignore
6741 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006742 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006743 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006744
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006745 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6746 if (!VDecl) {
6747 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6748 RealDecl->setInvalidDecl();
6749 return;
6750 }
6751
Richard Smith34b41d92011-02-20 03:19:35 +00006752 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6753 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00006754 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6755 if (Exprs.size() > 1) {
6756 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6757 diag::err_auto_var_init_multiple_expressions)
6758 << VDecl->getDeclName() << VDecl->getType()
6759 << VDecl->getSourceRange();
6760 RealDecl->setInvalidDecl();
6761 return;
6762 }
6763
6764 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00006765 TypeSourceInfo *DeducedType = 0;
6766 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00006767 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6768 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6769 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00006770 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006771 RealDecl->setInvalidDecl();
6772 return;
6773 }
Richard Smitha085da82011-03-17 16:11:59 +00006774 VDecl->setTypeSourceInfo(DeducedType);
6775 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00006776
6777 // If this is a redeclaration, check that the type we just deduced matches
6778 // the previously declared type.
6779 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6780 MergeVarDeclTypes(VDecl, Old);
6781 }
6782
Douglas Gregor83ddad32009-08-26 21:14:46 +00006783 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006784 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006785 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6786 //
6787 // Clients that want to distinguish between the two forms, can check for
6788 // direct initializer using VarDecl::hasCXXDirectInitializer().
6789 // A major benefit is that clients that don't particularly care about which
6790 // exactly form was it (like the CodeGen) can handle both cases without
6791 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006792
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006793 // C++ 8.5p11:
6794 // The form of initialization (using parentheses or '=') is generally
6795 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006796 // class type.
6797
Douglas Gregor4dffad62010-02-11 22:55:30 +00006798 if (!VDecl->getType()->isDependentType() &&
6799 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00006800 diag::err_typecheck_decl_incomplete_type)) {
6801 VDecl->setInvalidDecl();
6802 return;
6803 }
6804
Douglas Gregor90f93822009-12-22 22:17:25 +00006805 // The variable can not have an abstract class type.
6806 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6807 diag::err_abstract_type_in_decl,
6808 AbstractVariableType))
6809 VDecl->setInvalidDecl();
6810
Sebastian Redl31310a22010-02-01 20:16:42 +00006811 const VarDecl *Def;
6812 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006813 Diag(VDecl->getLocation(), diag::err_redefinition)
6814 << VDecl->getDeclName();
6815 Diag(Def->getLocation(), diag::note_previous_definition);
6816 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006817 return;
6818 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006819
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006820 // C++ [class.static.data]p4
6821 // If a static data member is of const integral or const
6822 // enumeration type, its declaration in the class definition can
6823 // specify a constant-initializer which shall be an integral
6824 // constant expression (5.19). In that case, the member can appear
6825 // in integral constant expressions. The member shall still be
6826 // defined in a namespace scope if it is used in the program and the
6827 // namespace scope definition shall not contain an initializer.
6828 //
6829 // We already performed a redefinition check above, but for static
6830 // data members we also need to check whether there was an in-class
6831 // declaration with an initializer.
6832 const VarDecl* PrevInit = 0;
6833 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6834 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6835 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6836 return;
6837 }
6838
Douglas Gregora31040f2010-12-16 01:31:22 +00006839 bool IsDependent = false;
6840 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6841 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6842 VDecl->setInvalidDecl();
6843 return;
6844 }
6845
6846 if (Exprs.get()[I]->isTypeDependent())
6847 IsDependent = true;
6848 }
6849
Douglas Gregor4dffad62010-02-11 22:55:30 +00006850 // If either the declaration has a dependent type or if any of the
6851 // expressions is type-dependent, we represent the initialization
6852 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006853 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006854 // Let clients know that initialization was done with a direct initializer.
6855 VDecl->setCXXDirectInitializer(true);
6856
6857 // Store the initialization expressions as a ParenListExpr.
6858 unsigned NumExprs = Exprs.size();
6859 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6860 (Expr **)Exprs.release(),
6861 NumExprs, RParenLoc));
6862 return;
6863 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006864
6865 // Capture the variable that is being initialized and the style of
6866 // initialization.
6867 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6868
6869 // FIXME: Poor source location information.
6870 InitializationKind Kind
6871 = InitializationKind::CreateDirect(VDecl->getLocation(),
6872 LParenLoc, RParenLoc);
6873
6874 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006875 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006876 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006877 if (Result.isInvalid()) {
6878 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006879 return;
6880 }
John McCallb4eb64d2010-10-08 02:01:28 +00006881
6882 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006883
Douglas Gregor53c374f2010-12-07 00:41:46 +00006884 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006885 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006886 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006887
John McCall2998d6b2011-01-19 11:48:09 +00006888 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006889}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006890
Douglas Gregor39da0b82009-09-09 23:08:42 +00006891/// \brief Given a constructor and the set of arguments provided for the
6892/// constructor, convert the arguments and add any required default arguments
6893/// to form a proper call to this constructor.
6894///
6895/// \returns true if an error occurred, false otherwise.
6896bool
6897Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6898 MultiExprArg ArgsPtr,
6899 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006900 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006901 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6902 unsigned NumArgs = ArgsPtr.size();
6903 Expr **Args = (Expr **)ArgsPtr.get();
6904
6905 const FunctionProtoType *Proto
6906 = Constructor->getType()->getAs<FunctionProtoType>();
6907 assert(Proto && "Constructor without a prototype?");
6908 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006909
6910 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006911 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006912 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006913 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006914 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006915
6916 VariadicCallType CallType =
6917 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6918 llvm::SmallVector<Expr *, 8> AllArgs;
6919 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6920 Proto, 0, Args, NumArgs, AllArgs,
6921 CallType);
6922 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6923 ConvertedArgs.push_back(AllArgs[i]);
6924 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006925}
6926
Anders Carlsson20d45d22009-12-12 00:32:00 +00006927static inline bool
6928CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6929 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006930 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006931 if (isa<NamespaceDecl>(DC)) {
6932 return SemaRef.Diag(FnDecl->getLocation(),
6933 diag::err_operator_new_delete_declared_in_namespace)
6934 << FnDecl->getDeclName();
6935 }
6936
6937 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006938 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006939 return SemaRef.Diag(FnDecl->getLocation(),
6940 diag::err_operator_new_delete_declared_static)
6941 << FnDecl->getDeclName();
6942 }
6943
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006944 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006945}
6946
Anders Carlsson156c78e2009-12-13 17:53:43 +00006947static inline bool
6948CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6949 CanQualType ExpectedResultType,
6950 CanQualType ExpectedFirstParamType,
6951 unsigned DependentParamTypeDiag,
6952 unsigned InvalidParamTypeDiag) {
6953 QualType ResultType =
6954 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6955
6956 // Check that the result type is not dependent.
6957 if (ResultType->isDependentType())
6958 return SemaRef.Diag(FnDecl->getLocation(),
6959 diag::err_operator_new_delete_dependent_result_type)
6960 << FnDecl->getDeclName() << ExpectedResultType;
6961
6962 // Check that the result type is what we expect.
6963 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6964 return SemaRef.Diag(FnDecl->getLocation(),
6965 diag::err_operator_new_delete_invalid_result_type)
6966 << FnDecl->getDeclName() << ExpectedResultType;
6967
6968 // A function template must have at least 2 parameters.
6969 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6970 return SemaRef.Diag(FnDecl->getLocation(),
6971 diag::err_operator_new_delete_template_too_few_parameters)
6972 << FnDecl->getDeclName();
6973
6974 // The function decl must have at least 1 parameter.
6975 if (FnDecl->getNumParams() == 0)
6976 return SemaRef.Diag(FnDecl->getLocation(),
6977 diag::err_operator_new_delete_too_few_parameters)
6978 << FnDecl->getDeclName();
6979
6980 // Check the the first parameter type is not dependent.
6981 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6982 if (FirstParamType->isDependentType())
6983 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6984 << FnDecl->getDeclName() << ExpectedFirstParamType;
6985
6986 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006987 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006988 ExpectedFirstParamType)
6989 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6990 << FnDecl->getDeclName() << ExpectedFirstParamType;
6991
6992 return false;
6993}
6994
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006995static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006996CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006997 // C++ [basic.stc.dynamic.allocation]p1:
6998 // A program is ill-formed if an allocation function is declared in a
6999 // namespace scope other than global scope or declared static in global
7000 // scope.
7001 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7002 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00007003
7004 CanQualType SizeTy =
7005 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7006
7007 // C++ [basic.stc.dynamic.allocation]p1:
7008 // The return type shall be void*. The first parameter shall have type
7009 // std::size_t.
7010 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7011 SizeTy,
7012 diag::err_operator_new_dependent_param_type,
7013 diag::err_operator_new_param_type))
7014 return true;
7015
7016 // C++ [basic.stc.dynamic.allocation]p1:
7017 // The first parameter shall not have an associated default argument.
7018 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00007019 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00007020 diag::err_operator_new_default_arg)
7021 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7022
7023 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00007024}
7025
7026static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007027CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7028 // C++ [basic.stc.dynamic.deallocation]p1:
7029 // A program is ill-formed if deallocation functions are declared in a
7030 // namespace scope other than global scope or declared static in global
7031 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00007032 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7033 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007034
7035 // C++ [basic.stc.dynamic.deallocation]p2:
7036 // Each deallocation function shall return void and its first parameter
7037 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00007038 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7039 SemaRef.Context.VoidPtrTy,
7040 diag::err_operator_delete_dependent_param_type,
7041 diag::err_operator_delete_param_type))
7042 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007043
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007044 return false;
7045}
7046
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007047/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7048/// of this overloaded operator is well-formed. If so, returns false;
7049/// otherwise, emits appropriate diagnostics and returns true.
7050bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007051 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007052 "Expected an overloaded operator declaration");
7053
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007054 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7055
Mike Stump1eb44332009-09-09 15:08:12 +00007056 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007057 // The allocation and deallocation functions, operator new,
7058 // operator new[], operator delete and operator delete[], are
7059 // described completely in 3.7.3. The attributes and restrictions
7060 // found in the rest of this subclause do not apply to them unless
7061 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00007062 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007063 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00007064
Anders Carlssona3ccda52009-12-12 00:26:23 +00007065 if (Op == OO_New || Op == OO_Array_New)
7066 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007067
7068 // C++ [over.oper]p6:
7069 // An operator function shall either be a non-static member
7070 // function or be a non-member function and have at least one
7071 // parameter whose type is a class, a reference to a class, an
7072 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007073 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7074 if (MethodDecl->isStatic())
7075 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007076 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007077 } else {
7078 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007079 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7080 ParamEnd = FnDecl->param_end();
7081 Param != ParamEnd; ++Param) {
7082 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00007083 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7084 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007085 ClassOrEnumParam = true;
7086 break;
7087 }
7088 }
7089
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007090 if (!ClassOrEnumParam)
7091 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007092 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007093 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007094 }
7095
7096 // C++ [over.oper]p8:
7097 // An operator function cannot have default arguments (8.3.6),
7098 // except where explicitly stated below.
7099 //
Mike Stump1eb44332009-09-09 15:08:12 +00007100 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007101 // (C++ [over.call]p1).
7102 if (Op != OO_Call) {
7103 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7104 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00007105 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00007106 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00007107 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00007108 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007109 }
7110 }
7111
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007112 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7113 { false, false, false }
7114#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7115 , { Unary, Binary, MemberOnly }
7116#include "clang/Basic/OperatorKinds.def"
7117 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007118
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007119 bool CanBeUnaryOperator = OperatorUses[Op][0];
7120 bool CanBeBinaryOperator = OperatorUses[Op][1];
7121 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007122
7123 // C++ [over.oper]p8:
7124 // [...] Operator functions cannot have more or fewer parameters
7125 // than the number required for the corresponding operator, as
7126 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00007127 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007128 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007129 if (Op != OO_Call &&
7130 ((NumParams == 1 && !CanBeUnaryOperator) ||
7131 (NumParams == 2 && !CanBeBinaryOperator) ||
7132 (NumParams < 1) || (NumParams > 2))) {
7133 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00007134 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007135 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007136 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007137 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007138 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007139 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007140 assert(CanBeBinaryOperator &&
7141 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00007142 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007143 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007144
Chris Lattner416e46f2008-11-21 07:57:12 +00007145 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007146 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007147 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00007148
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007149 // Overloaded operators other than operator() cannot be variadic.
7150 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00007151 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007152 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007153 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007154 }
7155
7156 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007157 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7158 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007159 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007160 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007161 }
7162
7163 // C++ [over.inc]p1:
7164 // The user-defined function called operator++ implements the
7165 // prefix and postfix ++ operator. If this function is a member
7166 // function with no parameters, or a non-member function with one
7167 // parameter of class or enumeration type, it defines the prefix
7168 // increment operator ++ for objects of that type. If the function
7169 // is a member function with one parameter (which shall be of type
7170 // int) or a non-member function with two parameters (the second
7171 // of which shall be of type int), it defines the postfix
7172 // increment operator ++ for objects of that type.
7173 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7174 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7175 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00007176 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007177 ParamIsInt = BT->getKind() == BuiltinType::Int;
7178
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007179 if (!ParamIsInt)
7180 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00007181 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00007182 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007183 }
7184
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007185 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007186}
Chris Lattner5a003a42008-12-17 07:09:26 +00007187
Sean Hunta6c058d2010-01-13 09:01:02 +00007188/// CheckLiteralOperatorDeclaration - Check whether the declaration
7189/// of this literal operator function is well-formed. If so, returns
7190/// false; otherwise, emits appropriate diagnostics and returns true.
7191bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7192 DeclContext *DC = FnDecl->getDeclContext();
7193 Decl::Kind Kind = DC->getDeclKind();
7194 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7195 Kind != Decl::LinkageSpec) {
7196 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7197 << FnDecl->getDeclName();
7198 return true;
7199 }
7200
7201 bool Valid = false;
7202
Sean Hunt216c2782010-04-07 23:11:06 +00007203 // template <char...> type operator "" name() is the only valid template
7204 // signature, and the only valid signature with no parameters.
7205 if (FnDecl->param_size() == 0) {
7206 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7207 // Must have only one template parameter
7208 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7209 if (Params->size() == 1) {
7210 NonTypeTemplateParmDecl *PmDecl =
7211 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00007212
Sean Hunt216c2782010-04-07 23:11:06 +00007213 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00007214 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7215 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7216 Valid = true;
7217 }
7218 }
7219 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00007220 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00007221 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7222
Sean Hunta6c058d2010-01-13 09:01:02 +00007223 QualType T = (*Param)->getType();
7224
Sean Hunt30019c02010-04-07 22:57:35 +00007225 // unsigned long long int, long double, and any character type are allowed
7226 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00007227 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7228 Context.hasSameType(T, Context.LongDoubleTy) ||
7229 Context.hasSameType(T, Context.CharTy) ||
7230 Context.hasSameType(T, Context.WCharTy) ||
7231 Context.hasSameType(T, Context.Char16Ty) ||
7232 Context.hasSameType(T, Context.Char32Ty)) {
7233 if (++Param == FnDecl->param_end())
7234 Valid = true;
7235 goto FinishedParams;
7236 }
7237
Sean Hunt30019c02010-04-07 22:57:35 +00007238 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00007239 const PointerType *PT = T->getAs<PointerType>();
7240 if (!PT)
7241 goto FinishedParams;
7242 T = PT->getPointeeType();
7243 if (!T.isConstQualified())
7244 goto FinishedParams;
7245 T = T.getUnqualifiedType();
7246
7247 // Move on to the second parameter;
7248 ++Param;
7249
7250 // If there is no second parameter, the first must be a const char *
7251 if (Param == FnDecl->param_end()) {
7252 if (Context.hasSameType(T, Context.CharTy))
7253 Valid = true;
7254 goto FinishedParams;
7255 }
7256
7257 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7258 // are allowed as the first parameter to a two-parameter function
7259 if (!(Context.hasSameType(T, Context.CharTy) ||
7260 Context.hasSameType(T, Context.WCharTy) ||
7261 Context.hasSameType(T, Context.Char16Ty) ||
7262 Context.hasSameType(T, Context.Char32Ty)))
7263 goto FinishedParams;
7264
7265 // The second and final parameter must be an std::size_t
7266 T = (*Param)->getType().getUnqualifiedType();
7267 if (Context.hasSameType(T, Context.getSizeType()) &&
7268 ++Param == FnDecl->param_end())
7269 Valid = true;
7270 }
7271
7272 // FIXME: This diagnostic is absolutely terrible.
7273FinishedParams:
7274 if (!Valid) {
7275 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7276 << FnDecl->getDeclName();
7277 return true;
7278 }
7279
7280 return false;
7281}
7282
Douglas Gregor074149e2009-01-05 19:45:36 +00007283/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7284/// linkage specification, including the language and (if present)
7285/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7286/// the location of the language string literal, which is provided
7287/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7288/// the '{' brace. Otherwise, this linkage specification does not
7289/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00007290Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7291 SourceLocation LangLoc,
7292 llvm::StringRef Lang,
7293 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00007294 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007295 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007296 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007297 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007298 Language = LinkageSpecDecl::lang_cxx;
7299 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00007300 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00007301 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00007302 }
Mike Stump1eb44332009-09-09 15:08:12 +00007303
Chris Lattnercc98eac2008-12-17 07:13:27 +00007304 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00007305
Douglas Gregor074149e2009-01-05 19:45:36 +00007306 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007307 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007308 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00007309 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00007310 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00007311}
7312
Abramo Bagnara35f9a192010-07-30 16:47:02 +00007313/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00007314/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7315/// valid, it's the position of the closing '}' brace in a linkage
7316/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00007317Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00007318 Decl *LinkageSpec,
7319 SourceLocation RBraceLoc) {
7320 if (LinkageSpec) {
7321 if (RBraceLoc.isValid()) {
7322 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7323 LSDecl->setRBraceLoc(RBraceLoc);
7324 }
Douglas Gregor074149e2009-01-05 19:45:36 +00007325 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00007326 }
Douglas Gregor074149e2009-01-05 19:45:36 +00007327 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00007328}
7329
Douglas Gregord308e622009-05-18 20:51:54 +00007330/// \brief Perform semantic analysis for the variable declaration that
7331/// occurs within a C++ catch clause, returning the newly-created
7332/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007333VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00007334 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007335 SourceLocation StartLoc,
7336 SourceLocation Loc,
7337 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00007338 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00007339 QualType ExDeclType = TInfo->getType();
7340
Sebastian Redl4b07b292008-12-22 19:15:10 +00007341 // Arrays and functions decay.
7342 if (ExDeclType->isArrayType())
7343 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7344 else if (ExDeclType->isFunctionType())
7345 ExDeclType = Context.getPointerType(ExDeclType);
7346
7347 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7348 // The exception-declaration shall not denote a pointer or reference to an
7349 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007350 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00007351 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00007352 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007353 Invalid = true;
7354 }
Douglas Gregord308e622009-05-18 20:51:54 +00007355
Douglas Gregora2762912010-03-08 01:47:36 +00007356 // GCC allows catching pointers and references to incomplete types
7357 // as an extension; so do we, but we warn by default.
7358
Sebastian Redl4b07b292008-12-22 19:15:10 +00007359 QualType BaseType = ExDeclType;
7360 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007361 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00007362 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00007363 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007364 BaseType = Ptr->getPointeeType();
7365 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00007366 DK = diag::ext_catch_incomplete_ptr;
7367 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00007368 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007369 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00007370 BaseType = Ref->getPointeeType();
7371 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00007372 DK = diag::ext_catch_incomplete_ref;
7373 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007374 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00007375 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00007376 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
7377 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00007378 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007379
Mike Stump1eb44332009-09-09 15:08:12 +00007380 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00007381 RequireNonAbstractType(Loc, ExDeclType,
7382 diag::err_abstract_type_in_decl,
7383 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00007384 Invalid = true;
7385
John McCall5a180392010-07-24 00:37:23 +00007386 // Only the non-fragile NeXT runtime currently supports C++ catches
7387 // of ObjC types, and no runtime supports catching ObjC types by value.
7388 if (!Invalid && getLangOptions().ObjC1) {
7389 QualType T = ExDeclType;
7390 if (const ReferenceType *RT = T->getAs<ReferenceType>())
7391 T = RT->getPointeeType();
7392
7393 if (T->isObjCObjectType()) {
7394 Diag(Loc, diag::err_objc_object_catch);
7395 Invalid = true;
7396 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00007397 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00007398 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
7399 Invalid = true;
7400 }
7401 }
7402 }
7403
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007404 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
7405 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00007406 ExDecl->setExceptionVariable(true);
7407
Douglas Gregor6d182892010-03-05 23:38:39 +00007408 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00007409 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00007410 // C++ [except.handle]p16:
7411 // The object declared in an exception-declaration or, if the
7412 // exception-declaration does not specify a name, a temporary (12.2) is
7413 // copy-initialized (8.5) from the exception object. [...]
7414 // The object is destroyed when the handler exits, after the destruction
7415 // of any automatic objects initialized within the handler.
7416 //
7417 // We just pretend to initialize the object with itself, then make sure
7418 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00007419 QualType initType = ExDeclType;
7420
7421 InitializedEntity entity =
7422 InitializedEntity::InitializeVariable(ExDecl);
7423 InitializationKind initKind =
7424 InitializationKind::CreateCopy(Loc, SourceLocation());
7425
7426 Expr *opaqueValue =
7427 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
7428 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
7429 ExprResult result = sequence.Perform(*this, entity, initKind,
7430 MultiExprArg(&opaqueValue, 1));
7431 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00007432 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00007433 else {
7434 // If the constructor used was non-trivial, set this as the
7435 // "initializer".
7436 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
7437 if (!construct->getConstructor()->isTrivial()) {
7438 Expr *init = MaybeCreateExprWithCleanups(construct);
7439 ExDecl->setInit(init);
7440 }
7441
7442 // And make sure it's destructable.
7443 FinalizeVarWithDestructor(ExDecl, recordType);
7444 }
Douglas Gregor6d182892010-03-05 23:38:39 +00007445 }
7446 }
7447
Douglas Gregord308e622009-05-18 20:51:54 +00007448 if (Invalid)
7449 ExDecl->setInvalidDecl();
7450
7451 return ExDecl;
7452}
7453
7454/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
7455/// handler.
John McCalld226f652010-08-21 09:40:31 +00007456Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00007457 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00007458 bool Invalid = D.isInvalidType();
7459
7460 // Check for unexpanded parameter packs.
7461 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7462 UPPC_ExceptionType)) {
7463 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7464 D.getIdentifierLoc());
7465 Invalid = true;
7466 }
7467
Sebastian Redl4b07b292008-12-22 19:15:10 +00007468 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00007469 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00007470 LookupOrdinaryName,
7471 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007472 // The scope should be freshly made just for us. There is just no way
7473 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00007474 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00007475 if (PrevDecl->isTemplateParameter()) {
7476 // Maybe we will complain about the shadowed template parameter.
7477 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007478 }
7479 }
7480
Chris Lattnereaaebc72009-04-25 08:06:05 +00007481 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007482 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
7483 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00007484 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007485 }
7486
Douglas Gregor83cb9422010-09-09 17:09:21 +00007487 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007488 D.getSourceRange().getBegin(),
7489 D.getIdentifierLoc(),
7490 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00007491 if (Invalid)
7492 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00007493
Sebastian Redl4b07b292008-12-22 19:15:10 +00007494 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00007495 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00007496 PushOnScopeChains(ExDecl, S);
7497 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007498 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007499
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007500 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00007501 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007502}
Anders Carlssonfb311762009-03-14 00:25:26 +00007503
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007504Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007505 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007506 Expr *AssertMessageExpr_,
7507 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00007508 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00007509
Anders Carlssonc3082412009-03-14 00:33:21 +00007510 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7511 llvm::APSInt Value(32);
7512 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007513 Diag(StaticAssertLoc,
7514 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00007515 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007516 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00007517 }
Anders Carlssonfb311762009-03-14 00:25:26 +00007518
Anders Carlssonc3082412009-03-14 00:33:21 +00007519 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007520 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00007521 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00007522 }
7523 }
Mike Stump1eb44332009-09-09 15:08:12 +00007524
Douglas Gregor399ad972010-12-15 23:55:21 +00007525 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7526 return 0;
7527
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007528 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7529 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00007530
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007531 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00007532 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00007533}
Sebastian Redl50de12f2009-03-24 22:27:57 +00007534
Douglas Gregor1d869352010-04-07 16:53:43 +00007535/// \brief Perform semantic analysis of the given friend type declaration.
7536///
7537/// \returns A friend declaration that.
7538FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7539 TypeSourceInfo *TSInfo) {
7540 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7541
7542 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00007543 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00007544
Douglas Gregor06245bf2010-04-07 17:57:12 +00007545 if (!getLangOptions().CPlusPlus0x) {
7546 // C++03 [class.friend]p2:
7547 // An elaborated-type-specifier shall be used in a friend declaration
7548 // for a class.*
7549 //
7550 // * The class-key of the elaborated-type-specifier is required.
7551 if (!ActiveTemplateInstantiations.empty()) {
7552 // Do not complain about the form of friend template types during
7553 // template instantiation; we will already have complained when the
7554 // template was declared.
7555 } else if (!T->isElaboratedTypeSpecifier()) {
7556 // If we evaluated the type to a record type, suggest putting
7557 // a tag in front.
7558 if (const RecordType *RT = T->getAs<RecordType>()) {
7559 RecordDecl *RD = RT->getDecl();
7560
7561 std::string InsertionText = std::string(" ") + RD->getKindName();
7562
7563 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7564 << (unsigned) RD->getTagKind()
7565 << T
7566 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7567 InsertionText);
7568 } else {
7569 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7570 << T
7571 << SourceRange(FriendLoc, TypeRange.getEnd());
7572 }
7573 } else if (T->getAs<EnumType>()) {
7574 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00007575 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00007576 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00007577 }
7578 }
7579
Douglas Gregor06245bf2010-04-07 17:57:12 +00007580 // C++0x [class.friend]p3:
7581 // If the type specifier in a friend declaration designates a (possibly
7582 // cv-qualified) class type, that class is declared as a friend; otherwise,
7583 // the friend declaration is ignored.
7584
7585 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7586 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00007587
7588 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7589}
7590
John McCall9a34edb2010-10-19 01:40:49 +00007591/// Handle a friend tag declaration where the scope specifier was
7592/// templated.
7593Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7594 unsigned TagSpec, SourceLocation TagLoc,
7595 CXXScopeSpec &SS,
7596 IdentifierInfo *Name, SourceLocation NameLoc,
7597 AttributeList *Attr,
7598 MultiTemplateParamsArg TempParamLists) {
7599 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7600
7601 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00007602 bool Invalid = false;
7603
7604 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00007605 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00007606 TempParamLists.get(),
7607 TempParamLists.size(),
7608 /*friend*/ true,
7609 isExplicitSpecialization,
7610 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00007611 if (TemplateParams->size() > 0) {
7612 // This is a declaration of a class template.
7613 if (Invalid)
7614 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007615
John McCall9a34edb2010-10-19 01:40:49 +00007616 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7617 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007618 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007619 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007620 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00007621 } else {
7622 // The "template<>" header is extraneous.
7623 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7624 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7625 isExplicitSpecialization = true;
7626 }
7627 }
7628
7629 if (Invalid) return 0;
7630
7631 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7632
7633 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007634 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00007635 if (TempParamLists.get()[I]->size()) {
7636 isAllExplicitSpecializations = false;
7637 break;
7638 }
7639 }
7640
7641 // FIXME: don't ignore attributes.
7642
7643 // If it's explicit specializations all the way down, just forget
7644 // about the template header and build an appropriate non-templated
7645 // friend. TODO: for source fidelity, remember the headers.
7646 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00007647 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00007648 ElaboratedTypeKeyword Keyword
7649 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007650 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00007651 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007652 if (T.isNull())
7653 return 0;
7654
7655 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7656 if (isa<DependentNameType>(T)) {
7657 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7658 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007659 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007660 TL.setNameLoc(NameLoc);
7661 } else {
7662 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7663 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007664 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007665 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7666 }
7667
7668 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7669 TSI, FriendLoc);
7670 Friend->setAccess(AS_public);
7671 CurContext->addDecl(Friend);
7672 return Friend;
7673 }
7674
7675 // Handle the case of a templated-scope friend class. e.g.
7676 // template <class T> class A<T>::B;
7677 // FIXME: we don't support these right now.
7678 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7679 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7680 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7681 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7682 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007683 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00007684 TL.setNameLoc(NameLoc);
7685
7686 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7687 TSI, FriendLoc);
7688 Friend->setAccess(AS_public);
7689 Friend->setUnsupportedFriend(true);
7690 CurContext->addDecl(Friend);
7691 return Friend;
7692}
7693
7694
John McCalldd4a3b02009-09-16 22:47:08 +00007695/// Handle a friend type declaration. This works in tandem with
7696/// ActOnTag.
7697///
7698/// Notes on friend class templates:
7699///
7700/// We generally treat friend class declarations as if they were
7701/// declaring a class. So, for example, the elaborated type specifier
7702/// in a friend declaration is required to obey the restrictions of a
7703/// class-head (i.e. no typedefs in the scope chain), template
7704/// parameters are required to match up with simple template-ids, &c.
7705/// However, unlike when declaring a template specialization, it's
7706/// okay to refer to a template specialization without an empty
7707/// template parameter declaration, e.g.
7708/// friend class A<T>::B<unsigned>;
7709/// We permit this as a special case; if there are any template
7710/// parameters present at all, require proper matching, i.e.
7711/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00007712Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00007713 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00007714 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00007715
7716 assert(DS.isFriendSpecified());
7717 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7718
John McCalldd4a3b02009-09-16 22:47:08 +00007719 // Try to convert the decl specifier to a type. This works for
7720 // friend templates because ActOnTag never produces a ClassTemplateDecl
7721 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00007722 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00007723 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7724 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00007725 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00007726 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007727
Douglas Gregor6ccab972010-12-16 01:14:37 +00007728 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7729 return 0;
7730
John McCalldd4a3b02009-09-16 22:47:08 +00007731 // This is definitely an error in C++98. It's probably meant to
7732 // be forbidden in C++0x, too, but the specification is just
7733 // poorly written.
7734 //
7735 // The problem is with declarations like the following:
7736 // template <T> friend A<T>::foo;
7737 // where deciding whether a class C is a friend or not now hinges
7738 // on whether there exists an instantiation of A that causes
7739 // 'foo' to equal C. There are restrictions on class-heads
7740 // (which we declare (by fiat) elaborated friend declarations to
7741 // be) that makes this tractable.
7742 //
7743 // FIXME: handle "template <> friend class A<T>;", which
7744 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00007745 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00007746 Diag(Loc, diag::err_tagless_friend_type_template)
7747 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007748 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00007749 }
Douglas Gregor1d869352010-04-07 16:53:43 +00007750
John McCall02cace72009-08-28 07:59:38 +00007751 // C++98 [class.friend]p1: A friend of a class is a function
7752 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00007753 // This is fixed in DR77, which just barely didn't make the C++03
7754 // deadline. It's also a very silly restriction that seriously
7755 // affects inner classes and which nobody else seems to implement;
7756 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00007757 //
7758 // But note that we could warn about it: it's always useless to
7759 // friend one of your own members (it's not, however, worthless to
7760 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00007761
John McCalldd4a3b02009-09-16 22:47:08 +00007762 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00007763 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00007764 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00007765 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00007766 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00007767 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00007768 DS.getFriendSpecLoc());
7769 else
Douglas Gregor1d869352010-04-07 16:53:43 +00007770 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7771
7772 if (!D)
John McCalld226f652010-08-21 09:40:31 +00007773 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00007774
John McCalldd4a3b02009-09-16 22:47:08 +00007775 D->setAccess(AS_public);
7776 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00007777
John McCalld226f652010-08-21 09:40:31 +00007778 return D;
John McCall02cace72009-08-28 07:59:38 +00007779}
7780
John McCall337ec3d2010-10-12 23:13:28 +00007781Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7782 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00007783 const DeclSpec &DS = D.getDeclSpec();
7784
7785 assert(DS.isFriendSpecified());
7786 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7787
7788 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00007789 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7790 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00007791
7792 // C++ [class.friend]p1
7793 // A friend of a class is a function or class....
7794 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00007795 // It *doesn't* see through dependent types, which is correct
7796 // according to [temp.arg.type]p3:
7797 // If a declaration acquires a function type through a
7798 // type dependent on a template-parameter and this causes
7799 // a declaration that does not use the syntactic form of a
7800 // function declarator to have a function type, the program
7801 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00007802 if (!T->isFunctionType()) {
7803 Diag(Loc, diag::err_unexpected_friend);
7804
7805 // It might be worthwhile to try to recover by creating an
7806 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00007807 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007808 }
7809
7810 // C++ [namespace.memdef]p3
7811 // - If a friend declaration in a non-local class first declares a
7812 // class or function, the friend class or function is a member
7813 // of the innermost enclosing namespace.
7814 // - The name of the friend is not found by simple name lookup
7815 // until a matching declaration is provided in that namespace
7816 // scope (either before or after the class declaration granting
7817 // friendship).
7818 // - If a friend function is called, its name may be found by the
7819 // name lookup that considers functions from namespaces and
7820 // classes associated with the types of the function arguments.
7821 // - When looking for a prior declaration of a class or a function
7822 // declared as a friend, scopes outside the innermost enclosing
7823 // namespace scope are not considered.
7824
John McCall337ec3d2010-10-12 23:13:28 +00007825 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007826 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7827 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007828 assert(Name);
7829
Douglas Gregor6ccab972010-12-16 01:14:37 +00007830 // Check for unexpanded parameter packs.
7831 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7832 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7833 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7834 return 0;
7835
John McCall67d1a672009-08-06 02:15:43 +00007836 // The context we found the declaration in, or in which we should
7837 // create the declaration.
7838 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007839 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007840 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007841 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007842
John McCall337ec3d2010-10-12 23:13:28 +00007843 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007844
John McCall337ec3d2010-10-12 23:13:28 +00007845 // There are four cases here.
7846 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007847 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007848 // there as appropriate.
7849 // Recover from invalid scope qualifiers as if they just weren't there.
7850 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007851 // C++0x [namespace.memdef]p3:
7852 // If the name in a friend declaration is neither qualified nor
7853 // a template-id and the declaration is a function or an
7854 // elaborated-type-specifier, the lookup to determine whether
7855 // the entity has been previously declared shall not consider
7856 // any scopes outside the innermost enclosing namespace.
7857 // C++0x [class.friend]p11:
7858 // If a friend declaration appears in a local class and the name
7859 // specified is an unqualified name, a prior declaration is
7860 // looked up without considering scopes that are outside the
7861 // innermost enclosing non-class scope. For a friend function
7862 // declaration, if there is no prior declaration, the program is
7863 // ill-formed.
7864 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007865 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007866
John McCall29ae6e52010-10-13 05:45:15 +00007867 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007868 DC = CurContext;
7869 while (true) {
7870 // Skip class contexts. If someone can cite chapter and verse
7871 // for this behavior, that would be nice --- it's what GCC and
7872 // EDG do, and it seems like a reasonable intent, but the spec
7873 // really only says that checks for unqualified existing
7874 // declarations should stop at the nearest enclosing namespace,
7875 // not that they should only consider the nearest enclosing
7876 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007877 while (DC->isRecord())
7878 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007879
John McCall68263142009-11-18 22:49:29 +00007880 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007881
7882 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007883 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007884 break;
John McCall29ae6e52010-10-13 05:45:15 +00007885
John McCall8a407372010-10-14 22:22:28 +00007886 if (isTemplateId) {
7887 if (isa<TranslationUnitDecl>(DC)) break;
7888 } else {
7889 if (DC->isFileContext()) break;
7890 }
John McCall67d1a672009-08-06 02:15:43 +00007891 DC = DC->getParent();
7892 }
7893
7894 // C++ [class.friend]p1: A friend of a class is a function or
7895 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007896 // C++0x changes this for both friend types and functions.
7897 // Most C++ 98 compilers do seem to give an error here, so
7898 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007899 if (!Previous.empty() && DC->Equals(CurContext)
7900 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007901 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007902
John McCall380aaa42010-10-13 06:22:15 +00007903 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007904
John McCall337ec3d2010-10-12 23:13:28 +00007905 // - There's a non-dependent scope specifier, in which case we
7906 // compute it and do a previous lookup there for a function
7907 // or function template.
7908 } else if (!SS.getScopeRep()->isDependent()) {
7909 DC = computeDeclContext(SS);
7910 if (!DC) return 0;
7911
7912 if (RequireCompleteDeclContext(SS, DC)) return 0;
7913
7914 LookupQualifiedName(Previous, DC);
7915
7916 // Ignore things found implicitly in the wrong scope.
7917 // TODO: better diagnostics for this case. Suggesting the right
7918 // qualified scope would be nice...
7919 LookupResult::Filter F = Previous.makeFilter();
7920 while (F.hasNext()) {
7921 NamedDecl *D = F.next();
7922 if (!DC->InEnclosingNamespaceSetOf(
7923 D->getDeclContext()->getRedeclContext()))
7924 F.erase();
7925 }
7926 F.done();
7927
7928 if (Previous.empty()) {
7929 D.setInvalidType();
7930 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7931 return 0;
7932 }
7933
7934 // C++ [class.friend]p1: A friend of a class is a function or
7935 // class that is not a member of the class . . .
7936 if (DC->Equals(CurContext))
7937 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7938
7939 // - There's a scope specifier that does not match any template
7940 // parameter lists, in which case we use some arbitrary context,
7941 // create a method or method template, and wait for instantiation.
7942 // - There's a scope specifier that does match some template
7943 // parameter lists, which we don't handle right now.
7944 } else {
7945 DC = CurContext;
7946 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007947 }
7948
John McCall29ae6e52010-10-13 05:45:15 +00007949 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007950 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007951 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7952 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7953 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007954 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007955 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7956 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007957 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007958 }
John McCall67d1a672009-08-06 02:15:43 +00007959 }
7960
Douglas Gregor182ddf02009-09-28 00:08:27 +00007961 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007962 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007963 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007964 IsDefinition,
7965 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007966 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007967
Douglas Gregor182ddf02009-09-28 00:08:27 +00007968 assert(ND->getDeclContext() == DC);
7969 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007970
John McCallab88d972009-08-31 22:39:49 +00007971 // Add the function declaration to the appropriate lookup tables,
7972 // adjusting the redeclarations list as necessary. We don't
7973 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007974 //
John McCallab88d972009-08-31 22:39:49 +00007975 // Also update the scope-based lookup if the target context's
7976 // lookup context is in lexical scope.
7977 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007978 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007979 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007980 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007981 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007982 }
John McCall02cace72009-08-28 07:59:38 +00007983
7984 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007985 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007986 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007987 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007988 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007989
John McCall337ec3d2010-10-12 23:13:28 +00007990 if (ND->isInvalidDecl())
7991 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007992 else {
7993 FunctionDecl *FD;
7994 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7995 FD = FTD->getTemplatedDecl();
7996 else
7997 FD = cast<FunctionDecl>(ND);
7998
7999 // Mark templated-scope function declarations as unsupported.
8000 if (FD->getNumTemplateParameterLists())
8001 FrD->setUnsupportedFriend(true);
8002 }
John McCall337ec3d2010-10-12 23:13:28 +00008003
John McCalld226f652010-08-21 09:40:31 +00008004 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00008005}
8006
John McCalld226f652010-08-21 09:40:31 +00008007void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8008 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00008009
Sebastian Redl50de12f2009-03-24 22:27:57 +00008010 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8011 if (!Fn) {
8012 Diag(DelLoc, diag::err_deleted_non_function);
8013 return;
8014 }
8015 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8016 Diag(DelLoc, diag::err_deleted_decl_not_first);
8017 Diag(Prev->getLocation(), diag::note_previous_declaration);
8018 // If the declaration wasn't the first, we delete the function anyway for
8019 // recovery.
8020 }
Sean Hunt10620eb2011-05-06 20:44:56 +00008021 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00008022}
Sebastian Redl13e88542009-04-27 21:33:24 +00008023
Sean Hunte4246a62011-05-12 06:15:49 +00008024void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8025 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8026
8027 if (MD) {
8028 CXXSpecialMember Member = getSpecialMember(MD);
8029 if (Member == CXXInvalid) {
8030 Diag(DefaultLoc, diag::err_default_special_members);
8031 return;
8032 }
8033
8034 MD->setDefaulted();
8035 MD->setExplicitlyDefaulted();
8036
8037 // We'll check it when the record is done
8038 if (MD == MD->getCanonicalDecl())
8039 return;
8040
8041 switch (Member) {
8042 case CXXDefaultConstructor: {
8043 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8044 CheckExplicitlyDefaultedDefaultConstructor(CD);
8045 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8046 break;
8047 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00008048
8049 case CXXDestructor: {
8050 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8051 CheckExplicitlyDefaultedDestructor(DD);
8052 DefineImplicitDestructor(DefaultLoc, DD);
8053 break;
8054 }
8055
Sean Hunte4246a62011-05-12 06:15:49 +00008056 default:
8057 // FIXME: Do the rest once we have functions
8058 break;
8059 }
8060 } else {
8061 Diag(DefaultLoc, diag::err_default_special_members);
8062 }
8063}
8064
Sebastian Redl13e88542009-04-27 21:33:24 +00008065static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00008066 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00008067 Stmt *SubStmt = *CI;
8068 if (!SubStmt)
8069 continue;
8070 if (isa<ReturnStmt>(SubStmt))
8071 Self.Diag(SubStmt->getSourceRange().getBegin(),
8072 diag::err_return_in_constructor_handler);
8073 if (!isa<Expr>(SubStmt))
8074 SearchForReturnInStmt(Self, SubStmt);
8075 }
8076}
8077
8078void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8079 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8080 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8081 SearchForReturnInStmt(*this, Handler);
8082 }
8083}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008084
Mike Stump1eb44332009-09-09 15:08:12 +00008085bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008086 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00008087 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8088 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008089
Chandler Carruth73857792010-02-15 11:53:20 +00008090 if (Context.hasSameType(NewTy, OldTy) ||
8091 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008092 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00008093
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008094 // Check if the return types are covariant
8095 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00008096
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008097 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008098 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8099 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008100 NewClassTy = NewPT->getPointeeType();
8101 OldClassTy = OldPT->getPointeeType();
8102 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008103 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8104 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8105 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8106 NewClassTy = NewRT->getPointeeType();
8107 OldClassTy = OldRT->getPointeeType();
8108 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008109 }
8110 }
Mike Stump1eb44332009-09-09 15:08:12 +00008111
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008112 // The return types aren't either both pointers or references to a class type.
8113 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00008114 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008115 diag::err_different_return_type_for_overriding_virtual_function)
8116 << New->getDeclName() << NewTy << OldTy;
8117 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00008118
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008119 return true;
8120 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008121
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008122 // C++ [class.virtual]p6:
8123 // If the return type of D::f differs from the return type of B::f, the
8124 // class type in the return type of D::f shall be complete at the point of
8125 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00008126 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8127 if (!RT->isBeingDefined() &&
8128 RequireCompleteType(New->getLocation(), NewClassTy,
8129 PDiag(diag::err_covariant_return_incomplete)
8130 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008131 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00008132 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008133
Douglas Gregora4923eb2009-11-16 21:35:15 +00008134 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008135 // Check if the new class derives from the old class.
8136 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8137 Diag(New->getLocation(),
8138 diag::err_covariant_return_not_derived)
8139 << New->getDeclName() << NewTy << OldTy;
8140 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8141 return true;
8142 }
Mike Stump1eb44332009-09-09 15:08:12 +00008143
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008144 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00008145 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00008146 diag::err_covariant_return_inaccessible_base,
8147 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8148 // FIXME: Should this point to the return type?
8149 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00008150 // FIXME: this note won't trigger for delayed access control
8151 // diagnostics, and it's impossible to get an undelayed error
8152 // here from access control during the original parse because
8153 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008154 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8155 return true;
8156 }
8157 }
Mike Stump1eb44332009-09-09 15:08:12 +00008158
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008159 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008160 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008161 Diag(New->getLocation(),
8162 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008163 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008164 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8165 return true;
8166 };
Mike Stump1eb44332009-09-09 15:08:12 +00008167
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008168
8169 // The new class type must have the same or less qualifiers as the old type.
8170 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8171 Diag(New->getLocation(),
8172 diag::err_covariant_return_type_class_type_more_qualified)
8173 << New->getDeclName() << NewTy << OldTy;
8174 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8175 return true;
8176 };
Mike Stump1eb44332009-09-09 15:08:12 +00008177
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008178 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008179}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008180
Douglas Gregor4ba31362009-12-01 17:24:26 +00008181/// \brief Mark the given method pure.
8182///
8183/// \param Method the method to be marked pure.
8184///
8185/// \param InitRange the source range that covers the "0" initializer.
8186bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00008187 SourceLocation EndLoc = InitRange.getEnd();
8188 if (EndLoc.isValid())
8189 Method->setRangeEnd(EndLoc);
8190
Douglas Gregor4ba31362009-12-01 17:24:26 +00008191 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8192 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00008193 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00008194 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00008195
8196 if (!Method->isInvalidDecl())
8197 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8198 << Method->getDeclName() << InitRange;
8199 return true;
8200}
8201
John McCall731ad842009-12-19 09:28:58 +00008202/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8203/// an initializer for the out-of-line declaration 'Dcl'. The scope
8204/// is a fresh scope pushed for just this purpose.
8205///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008206/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8207/// static data member of class X, names should be looked up in the scope of
8208/// class X.
John McCalld226f652010-08-21 09:40:31 +00008209void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008210 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008211 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008212
John McCall731ad842009-12-19 09:28:58 +00008213 // We should only get called for declarations with scope specifiers, like:
8214 // int foo::bar;
8215 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008216 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008217}
8218
8219/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00008220/// initializer for the out-of-line declaration 'D'.
8221void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008222 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008223 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008224
John McCall731ad842009-12-19 09:28:58 +00008225 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008226 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008227}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008228
8229/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8230/// C++ if/switch/while/for statement.
8231/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00008232DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008233 // C++ 6.4p2:
8234 // The declarator shall not specify a function or an array.
8235 // The type-specifier-seq shall not contain typedef and shall not declare a
8236 // new class or enumeration.
8237 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8238 "Parser allowed 'typedef' as storage class of condition decl.");
8239
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008240 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00008241 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
8242 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008243
8244 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
8245 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
8246 // would be created and CXXConditionDeclExpr wants a VarDecl.
8247 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
8248 << D.getSourceRange();
8249 return DeclResult();
8250 } else if (OwnedTag && OwnedTag->isDefinition()) {
8251 // The type-specifier-seq shall not declare a new class or enumeration.
8252 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
8253 }
8254
John McCalld226f652010-08-21 09:40:31 +00008255 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008256 if (!Dcl)
8257 return DeclResult();
8258
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008259 return Dcl;
8260}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008261
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008262void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8263 bool DefinitionRequired) {
8264 // Ignore any vtable uses in unevaluated operands or for classes that do
8265 // not have a vtable.
8266 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8267 CurContext->isDependentContext() ||
8268 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00008269 return;
8270
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008271 // Try to insert this class into the map.
8272 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8273 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8274 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8275 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00008276 // If we already had an entry, check to see if we are promoting this vtable
8277 // to required a definition. If so, we need to reappend to the VTableUses
8278 // list, since we may have already processed the first entry.
8279 if (DefinitionRequired && !Pos.first->second) {
8280 Pos.first->second = true;
8281 } else {
8282 // Otherwise, we can early exit.
8283 return;
8284 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008285 }
8286
8287 // Local classes need to have their virtual members marked
8288 // immediately. For all other classes, we mark their virtual members
8289 // at the end of the translation unit.
8290 if (Class->isLocalClass())
8291 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00008292 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008293 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00008294}
8295
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008296bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008297 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00008298 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00008299
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008300 // Note: The VTableUses vector could grow as a result of marking
8301 // the members of a class as "used", so we check the size each
8302 // time through the loop and prefer indices (with are stable) to
8303 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00008304 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008305 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00008306 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008307 if (!Class)
8308 continue;
8309
8310 SourceLocation Loc = VTableUses[I].second;
8311
8312 // If this class has a key function, but that key function is
8313 // defined in another translation unit, we don't need to emit the
8314 // vtable even though we're using it.
8315 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00008316 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008317 switch (KeyFunction->getTemplateSpecializationKind()) {
8318 case TSK_Undeclared:
8319 case TSK_ExplicitSpecialization:
8320 case TSK_ExplicitInstantiationDeclaration:
8321 // The key function is in another translation unit.
8322 continue;
8323
8324 case TSK_ExplicitInstantiationDefinition:
8325 case TSK_ImplicitInstantiation:
8326 // We will be instantiating the key function.
8327 break;
8328 }
8329 } else if (!KeyFunction) {
8330 // If we have a class with no key function that is the subject
8331 // of an explicit instantiation declaration, suppress the
8332 // vtable; it will live with the explicit instantiation
8333 // definition.
8334 bool IsExplicitInstantiationDeclaration
8335 = Class->getTemplateSpecializationKind()
8336 == TSK_ExplicitInstantiationDeclaration;
8337 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
8338 REnd = Class->redecls_end();
8339 R != REnd; ++R) {
8340 TemplateSpecializationKind TSK
8341 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
8342 if (TSK == TSK_ExplicitInstantiationDeclaration)
8343 IsExplicitInstantiationDeclaration = true;
8344 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8345 IsExplicitInstantiationDeclaration = false;
8346 break;
8347 }
8348 }
8349
8350 if (IsExplicitInstantiationDeclaration)
8351 continue;
8352 }
8353
8354 // Mark all of the virtual members of this class as referenced, so
8355 // that we can build a vtable. Then, tell the AST consumer that a
8356 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00008357 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008358 MarkVirtualMembersReferenced(Loc, Class);
8359 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8360 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
8361
8362 // Optionally warn if we're emitting a weak vtable.
8363 if (Class->getLinkage() == ExternalLinkage &&
8364 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00008365 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008366 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
8367 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008368 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008369 VTableUses.clear();
8370
Douglas Gregor78844032011-04-22 22:25:37 +00008371 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008372}
Anders Carlssond6a637f2009-12-07 08:24:59 +00008373
Rafael Espindola3e1ae932010-03-26 00:36:59 +00008374void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
8375 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00008376 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
8377 e = RD->method_end(); i != e; ++i) {
8378 CXXMethodDecl *MD = *i;
8379
8380 // C++ [basic.def.odr]p2:
8381 // [...] A virtual member function is used if it is not pure. [...]
8382 if (MD->isVirtual() && !MD->isPure())
8383 MarkDeclarationReferenced(Loc, MD);
8384 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00008385
8386 // Only classes that have virtual bases need a VTT.
8387 if (RD->getNumVBases() == 0)
8388 return;
8389
8390 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
8391 e = RD->bases_end(); i != e; ++i) {
8392 const CXXRecordDecl *Base =
8393 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00008394 if (Base->getNumVBases() == 0)
8395 continue;
8396 MarkVirtualMembersReferenced(Loc, Base);
8397 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00008398}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008399
8400/// SetIvarInitializers - This routine builds initialization ASTs for the
8401/// Objective-C implementation whose ivars need be initialized.
8402void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
8403 if (!getLangOptions().CPlusPlus)
8404 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00008405 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008406 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
8407 CollectIvarsToConstructOrDestruct(OID, ivars);
8408 if (ivars.empty())
8409 return;
Sean Huntcbb67482011-01-08 20:30:50 +00008410 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008411 for (unsigned i = 0; i < ivars.size(); i++) {
8412 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008413 if (Field->isInvalidDecl())
8414 continue;
8415
Sean Huntcbb67482011-01-08 20:30:50 +00008416 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008417 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
8418 InitializationKind InitKind =
8419 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
8420
8421 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008422 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00008423 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00008424 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008425 // Note, MemberInit could actually come back empty if no initialization
8426 // is required (e.g., because it would call a trivial default constructor)
8427 if (!MemberInit.get() || MemberInit.isInvalid())
8428 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00008429
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008430 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00008431 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
8432 SourceLocation(),
8433 MemberInit.takeAs<Expr>(),
8434 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008435 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008436
8437 // Be sure that the destructor is accessible and is marked as referenced.
8438 if (const RecordType *RecordTy
8439 = Context.getBaseElementType(Field->getType())
8440 ->getAs<RecordType>()) {
8441 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00008442 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00008443 MarkDeclarationReferenced(Field->getLocation(), Destructor);
8444 CheckDestructorAccess(Field->getLocation(), Destructor,
8445 PDiag(diag::err_access_dtor_ivar)
8446 << Context.getBaseElementType(Field->getType()));
8447 }
8448 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00008449 }
8450 ObjCImplementation->setIvarInitializers(Context,
8451 AllToInit.data(), AllToInit.size());
8452 }
8453}
Sean Huntfe57eef2011-05-04 05:57:24 +00008454
Sean Huntebcbe1d2011-05-04 23:29:54 +00008455static
8456void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
8457 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
8458 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
8459 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
8460 Sema &S) {
8461 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8462 CE = Current.end();
8463 if (Ctor->isInvalidDecl())
8464 return;
8465
8466 const FunctionDecl *FNTarget = 0;
8467 CXXConstructorDecl *Target;
8468
8469 // We ignore the result here since if we don't have a body, Target will be
8470 // null below.
8471 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
8472 Target
8473= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
8474
8475 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
8476 // Avoid dereferencing a null pointer here.
8477 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
8478
8479 if (!Current.insert(Canonical))
8480 return;
8481
8482 // We know that beyond here, we aren't chaining into a cycle.
8483 if (!Target || !Target->isDelegatingConstructor() ||
8484 Target->isInvalidDecl() || Valid.count(TCanonical)) {
8485 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8486 Valid.insert(*CI);
8487 Current.clear();
8488 // We've hit a cycle.
8489 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
8490 Current.count(TCanonical)) {
8491 // If we haven't diagnosed this cycle yet, do so now.
8492 if (!Invalid.count(TCanonical)) {
8493 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00008494 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00008495 << Ctor;
8496
8497 // Don't add a note for a function delegating directo to itself.
8498 if (TCanonical != Canonical)
8499 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
8500
8501 CXXConstructorDecl *C = Target;
8502 while (C->getCanonicalDecl() != Canonical) {
8503 (void)C->getTargetConstructor()->hasBody(FNTarget);
8504 assert(FNTarget && "Ctor cycle through bodiless function");
8505
8506 C
8507 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
8508 S.Diag(C->getLocation(), diag::note_which_delegates_to);
8509 }
8510 }
8511
8512 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8513 Invalid.insert(*CI);
8514 Current.clear();
8515 } else {
8516 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
8517 }
8518}
8519
8520
Sean Huntfe57eef2011-05-04 05:57:24 +00008521void Sema::CheckDelegatingCtorCycles() {
8522 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
8523
Sean Huntebcbe1d2011-05-04 23:29:54 +00008524 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8525 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00008526
8527 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Sean Huntebcbe1d2011-05-04 23:29:54 +00008528 I = DelegatingCtorDecls.begin(),
8529 E = DelegatingCtorDecls.end();
8530 I != E; ++I) {
8531 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00008532 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00008533
8534 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
8535 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00008536}