blob: b98777bad7952c2e0cccca75defb901991f3ffea [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000036#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000037#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner58258242008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattnerb0d38442008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000055
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 public:
Mike Stump11289f42009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 };
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000071 }
72
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 }
Chris Lattner58258242008-04-10 02:22:51 +000099
Douglas Gregor8e12c382008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000102
Douglas Gregor97a9c812008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111 }
Chris Lattner58258242008-04-10 02:22:51 +0000112}
113
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
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 Carlssonc80a1272009-08-25 02:29:20 +0000177bool
John McCallb268a282010-08-23 23:25:46 +0000178Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000179 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000192 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
193 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000194 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
195 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000196 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000197 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000198 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000199 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000200 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000201 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000202
John McCallacf0ee52010-10-08 02:01:28 +0000203 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000204 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000205
Anders Carlssonc80a1272009-08-25 02:29:20 +0000206 // Okay: add the default argument to the parameter
207 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000208
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000221 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000222}
223
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000227void
John McCall48871652010-08-21 09:40:31 +0000228Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000229 Expr *DefaultArg) {
230 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000231 return;
Mike Stump11289f42009-09-09 15:08:12 +0000232
John McCall48871652010-08-21 09:40:31 +0000233 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000234 UnparsedDefaultArgLocs.erase(Param);
235
Chris Lattner199abbc2008-04-08 05:04:30 +0000236 // Default arguments are only permitted in C++
237 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000238 Diag(EqualLoc, diag::err_param_default_argument)
239 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000240 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000241 return;
242 }
243
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000250 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000251 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
252 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000253 Param->setInvalidDecl();
254 return;
255 }
Mike Stump11289f42009-09-09 15:08:12 +0000256
John McCallb268a282010-08-23 23:25:46 +0000257 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000258}
259
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000264void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000265 SourceLocation EqualLoc,
266 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000267 if (!param)
268 return;
Mike Stump11289f42009-09-09 15:08:12 +0000269
John McCall48871652010-08-21 09:40:31 +0000270 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000271 if (Param)
272 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000273
Anders Carlsson84613c42009-06-12 16:51:40 +0000274 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000275}
276
Douglas Gregor4d87df52008-12-16 21:30:33 +0000277/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
278/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000279void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000280 if (!param)
281 return;
Mike Stump11289f42009-09-09 15:08:12 +0000282
John McCall48871652010-08-21 09:40:31 +0000283 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000284
Anders Carlsson84613c42009-06-12 16:51:40 +0000285 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000286
Anders Carlsson84613c42009-06-12 16:51:40 +0000287 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000288}
289
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000303 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000304 DeclaratorChunk &chunk = D.getTypeObject(i);
305 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000306 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
307 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000308 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000309 if (Param->hasUnparsedDefaultArg()) {
310 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000319 }
320 }
321 }
322 }
323}
324
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000332 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000354 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000355
Francois Pichet53fe2bb2011-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 Pichet8cb243a2011-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 Pichet93921652011-04-22 08:25:24 +0000372 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000373 Invalid = false;
374 }
375 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000376
Francois Pichet8cb243a2011-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 Gregor08dc5842010-01-13 00:12:48 +0000382 // int f(int);
383 // void g(int (*fp)(int) = f);
384 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000385 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000386 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor4f15f4d2009-09-17 19:51:30 +0000400 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000403 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000404 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000405 if (OldParam->hasUninstantiatedDefaultArg())
406 NewParam->setUninstantiatedDefaultArg(
407 OldParam->getUninstantiatedDefaultArg());
408 else
John McCalle61b02b2010-05-04 01:53:42 +0000409 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000460 }
461 }
462
Douglas Gregorf40863c2010-02-12 07:32:17 +0000463 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000464 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000465
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000466 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000467}
468
Sebastian Redlfa453cf2011-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 Lattner199abbc2008-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 Carlsson5a532382009-08-25 01:23:32 +0000521 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000532 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000533 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000534 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000535 if (Param->isInvalidDecl())
536 /* We already complained about this parameter. */;
537 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000538 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000539 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000540 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000541 else
Mike Stump11289f42009-09-09 15:08:12 +0000542 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000543 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000544
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000556 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000557 Param->setDefaultArg(0);
558 }
559 }
560 }
561}
Douglas Gregor556877c2008-04-13 21:30:24 +0000562
Douglas Gregor61956c42008-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 Kyrtzidis32a03792008-11-08 16:45:02 +0000567bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
568 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000569 assert(getLangOptions().CPlusPlus && "No class names in C!");
570
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000571 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000572 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000573 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-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 Gregor1aa3edb2010-02-05 06:12:42 +0000578 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000579 return &II == CurDecl->getIdentifier();
580 else
581 return false;
582}
583
Mike Stump11289f42009-09-09 15:08:12 +0000584/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-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 Gregor752a5952011-01-03 22:36:02 +0000592 TypeSourceInfo *TInfo,
593 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000594 QualType BaseType = TInfo->getType();
595
Douglas Gregor463421d2009-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 Gregor752a5952011-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 Gregor463421d2009-03-03 04:44:36 +0000611 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000612 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000613 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000614 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000615
616 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000634 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000635 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000636 << SpecifierRange)) {
637 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000639 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000640
Eli Friedmanc96d4962009-08-15 21:55:26 +0000641 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000642 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000643 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000644 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000645 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000646 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
647 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000648
Anders Carlsson65c76d32011-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 Carlsson1eb95962011-01-24 16:26:15 +0000652 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-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 McCall3696dcb2010-08-17 07:23:57 +0000660 if (BaseDecl->isInvalidDecl())
661 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000662
663 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000664 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000665 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000666 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000667}
668
Douglas Gregor556877c2008-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 Stump11289f42009-09-09 15:08:12 +0000671/// example:
672/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000673/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000674BaseResult
John McCall48871652010-08-21 09:40:31 +0000675Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000676 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000677 ParsedType basetype, SourceLocation BaseLoc,
678 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000679 if (!classdecl)
680 return true;
681
Douglas Gregorc40290e2009-03-09 23:48:35 +0000682 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000683 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000684 if (!Class)
685 return true;
686
Nick Lewycky19b9f952010-07-26 16:56:01 +0000687 TypeSourceInfo *TInfo = 0;
688 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000689
Douglas Gregor752a5952011-01-03 22:36:02 +0000690 if (EllipsisLoc.isInvalid() &&
691 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000692 UPPC_BaseType))
693 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000694
Douglas Gregor463421d2009-03-03 04:44:36 +0000695 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000696 Virtual, Access, TInfo,
697 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000698 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000699
Douglas Gregor463421d2009-03-03 04:44:36 +0000700 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000701}
Douglas Gregor556877c2008-04-13 21:30:24 +0000702
Douglas Gregor463421d2009-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 Gregor29a92472008-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 Gregor9d6290b2008-10-23 18:13:27 +0000712 // that the key is always the unqualified canonical type of the base
713 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000714 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
715
716 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000717 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000718 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000719 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000720 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000721 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000722 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-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 Gregor29a92472008-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 Gregor463421d2009-03-03 04:44:36 +0000734 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000735 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000736 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000737 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000738
739 // Delete the duplicate base class specifier; we're going to
740 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000741 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000742
743 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000744 } else {
745 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000746 KnownBaseTypes[NewBaseType] = Bases[idx];
747 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000748 }
749 }
750
751 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000752 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-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 Gregorb77af8f2009-07-22 20:55:49 +0000757 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-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 McCall48871652010-08-21 09:40:31 +0000765void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000766 unsigned NumBases) {
767 if (!ClassDecl || !Bases || !NumBases)
768 return;
769
770 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000771 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000772 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000773}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000774
John McCalle78aac42010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000789
790 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
791 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000792 return false;
793
John McCalle78aac42010-03-10 03:28:59 +0000794 CXXRecordDecl *BaseRD = GetClassForType(Base);
795 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000796 return false;
797
John McCall67da35c2010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000808 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
809 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000810 return false;
811
John McCalle78aac42010-03-10 03:28:59 +0000812 CXXRecordDecl *BaseRD = GetClassForType(Base);
813 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000814 return false;
815
Douglas Gregor36d1b142009-10-06 17:59:45 +0000816 return DerivedRD->isDerivedFrom(BaseRD, Paths);
817}
818
Anders Carlssona70cff62010-04-24 19:06:50 +0000819void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000820 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-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 McCallcf142162010-08-07 06:22:56 +0000839 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000840}
841
Douglas Gregor88d292c2010-05-13 16:44:06 +0000842/// \brief Determine whether the given base path includes a virtual
843/// base class.
John McCallcf142162010-08-07 06:22:56 +0000844bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
845 for (CXXCastPath::const_iterator B = BasePath.begin(),
846 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000847 B != BEnd; ++B)
848 if ((*B)->isVirtual())
849 return true;
850
851 return false;
852}
853
Douglas Gregor36d1b142009-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 McCall1064d7e2010-03-16 05:22:47 +0000864 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000865 unsigned AmbigiousBaseConvID,
866 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000867 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000868 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-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 Carlssona70cff62010-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 Carlsson7afe4242010-04-24 17:11:09 +0000891 }
John McCall5b0829a2010-02-10 09:31:12 +0000892 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000893
894 // Build a base path if necessary.
895 if (BasePath)
896 BuildBasePathArray(Paths, *BasePath);
897 return false;
Douglas Gregor36d1b142009-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 Redl7c353682009-11-14 21:15:49 +0000925 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000926 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000927 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000928 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000929 IgnoreAccess ? 0
930 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000931 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000932 Loc, Range, DeclarationName(),
933 BasePath);
Douglas Gregor36d1b142009-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 Kyrtzidised983422008-07-01 10:37:29 +0000968//===----------------------------------------------------------------------===//
969// C++ class member Handling
970//===----------------------------------------------------------------------===//
971
Abramo Bagnarad7340582010-06-05 05:09:32 +0000972/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000973Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
974 SourceLocation ASLoc,
975 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000976 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000977 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000978 ASLoc, ColonLoc);
979 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000980 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000981}
982
Anders Carlssonfd835532011-01-20 05:57:14 +0000983/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000984void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000985 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
986 if (!MD || !MD->isVirtual())
987 return;
988
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000989 if (MD->isDependentContext())
990 return;
991
Anders Carlssonfd835532011-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 Carlsson1eb95962011-01-24 16:26:15 +0000998 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000999 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001000 diag::err_function_marked_override_not_overriding)
1001 << MD->getDeclName();
1002 return;
1003 }
1004}
1005
Anders Carlsson3f610c72011-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 Carlsson1eb95962011-01-24 16:26:15 +00001011 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-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 Carlsson3f610c72011-01-20 16:25:36 +00001018}
1019
Argyrios Kyrtzidised983422008-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 Lattnereb4373d2009-04-12 22:37:57 +00001023/// any.
John McCall48871652010-08-21 09:40:31 +00001024Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001025Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001026 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +00001027 ExprTy *BW, const VirtSpecifiers &VS,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001028 ExprTy *InitExpr, bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001029 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001030 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1031 DeclarationName Name = NameInfo.getName();
1032 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-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 Kyrtzidised983422008-07-01 10:37:29 +00001038 Expr *BitWidth = static_cast<Expr*>(BW);
1039 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001040
John McCallb1cd7da2010-06-04 08:34:12 +00001041 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001042 assert(!DS.isFriendSpecified());
1043
John McCallb1cd7da2010-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 McCallba7bf592010-08-24 05:47:05 +00001049 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +00001050 isFunc = TDType->isFunctionType();
1051 }
1052
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-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 Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +00001064 case DeclSpec::SCS_mutable:
1065 if (isFunc) {
1066 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001067 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001068 else
Chris Lattner3b054132008-11-19 05:08:23 +00001069 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001070
Sebastian Redl8071edb2008-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 Redlccdfaba2008-11-14 23:42:31 +00001073 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001074 }
1075 break;
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +00001085 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1086 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001087 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001088
1089 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001090 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001091 CXXScopeSpec &SS = D.getCXXScopeSpec();
1092
Douglas Gregora007d362010-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 Gregor3447e762009-08-20 22:52:58 +00001111 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001112 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001113 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1114 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001115 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001116 } else {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001117 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001118 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001119 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001120 }
Chris Lattnerd26760a2009-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 Gregor212cab32009-03-11 20:22:50 +00001126 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-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 Stump11289f42009-09-09 15:08:12 +00001139 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001140 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001141 }
Mike Stump11289f42009-09-09 15:08:12 +00001142
Chris Lattnerd26760a2009-03-05 23:01:03 +00001143 BitWidth = 0;
1144 Member->setInvalidDecl();
1145 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001146
1147 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001148
Douglas Gregor3447e762009-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 Lattner73bf7b42009-03-05 22:45:59 +00001153 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001154
Anders Carlsson13a69102011-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 Carlssonfd835532011-01-20 05:57:14 +00001161 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001162 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-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 Carlssonfd835532011-01-20 05:57:14 +00001170 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001171 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001172 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001173
Douglas Gregorf2f08062011-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 Carlssonc87f8612011-01-20 06:29:02 +00001180 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001181
Douglas Gregor92751d42008-11-17 22:58:34 +00001182 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001183
Douglas Gregor0c880302009-03-11 23:00:04 +00001184 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001185 AddInitializerToDecl(Member, Init, false,
1186 DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001187
Richard Smithb2bc2e62011-02-21 20:05:19 +00001188 FinalizeDeclaration(Member);
1189
John McCall25849ca2011-02-15 07:12:36 +00001190 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001191 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001192 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001193}
1194
Douglas Gregor15e77a22009-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 Gregore8381c02008-11-05 04:29:56 +00001240/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001241MemInitResult
John McCall48871652010-08-21 09:40:31 +00001242Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001243 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001244 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001245 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001246 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001247 SourceLocation IdLoc,
1248 SourceLocation LParenLoc,
1249 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001250 SourceLocation RParenLoc,
1251 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001252 if (!ConstructorD)
1253 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001254
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001255 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001256
1257 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001258 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-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 Lewycky9331ed82010-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 Gregore8381c02008-11-05 04:29:56 +00001277 // mem-initializer-id for the hidden base class may be specified
1278 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001279 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001280 // Look for a member, first.
1281 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001282 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001283 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001284 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001285 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001286
Douglas Gregor44e7df62011-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 Pichetd583da02010-12-04 09:14:42 +00001292 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001293 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001294 }
1295
Francois Pichetd583da02010-12-04 09:14:42 +00001296 // Handle anonymous union case.
1297 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-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 Pichetd583da02010-12-04 09:14:42 +00001303 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1304 NumArgs, IdLoc,
1305 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001306 }
Francois Pichetd583da02010-12-04 09:14:42 +00001307 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001308 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001309 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001310 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001311 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001312
1313 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001314 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-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 McCallda6841b2010-04-09 19:01:14 +00001323 // We don't want access-control diagnostics here.
1324 R.suppressDiagnostics();
1325
Douglas Gregora3b624a2010-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 Gregor9cbc22b2011-02-28 22:42:13 +00001335 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1336 SS.getWithLocInContext(Context),
1337 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001338 if (BaseType.isNull())
1339 return true;
1340
Douglas Gregora3b624a2010-01-19 06:46:48 +00001341 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001342 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001343 }
1344 }
1345
Douglas Gregor15e77a22009-12-31 09:10:24 +00001346 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001347 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001348 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1349 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001350 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001351 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001357 << FixItHint::CreateReplacement(R.getNameLoc(),
1358 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001359 Diag(Member->getLocation(), diag::note_previous_decl)
1360 << Member->getDeclName();
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001376 << FixItHint::CreateReplacement(R.getNameLoc(),
1377 R.getLookupName().getAsString());
Douglas Gregor43a08572010-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 Gregor15e77a22009-12-31 09:10:24 +00001386 TyD = Type;
1387 }
1388 }
1389 }
1390
Douglas Gregora3b624a2010-01-19 06:46:48 +00001391 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-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 McCallb5a0d312009-12-21 10:41:20 +00001396 }
1397
Douglas Gregora3b624a2010-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 McCallb5a0d312009-12-21 10:41:20 +00001403
Douglas Gregora3b624a2010-01-19 06:46:48 +00001404 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001405 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001406 }
John McCallb5a0d312009-12-21 10:41:20 +00001407 }
1408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
John McCallbcd03502009-12-07 02:54:59 +00001410 if (!TInfo)
1411 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001412
John McCallbcd03502009-12-07 02:54:59 +00001413 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001414 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001415}
1416
John McCalle22a04a2009-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 Lewyckya2fb98b2010-06-15 07:32:55 +00001421static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001422 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001423 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001424 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1425
Nick Lewyckya2fb98b2010-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 Carlsson0f7e94f2010-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 Lewycky300524242010-10-06 18:37:39 +00001441 (void)VD;
Anders Carlsson0f7e94f2010-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 McCalle22a04a2009-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 Lewyckya2fb98b2010-06-15 07:32:55 +00001455 const Expr *base = ME->getBase();
John McCalle22a04a2009-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 Collingbournee190dee2011-03-11 19:24:49 +00001465 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-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 McCalle22a04a2009-11-04 23:02:40 +00001473 }
John McCall8322c3a2011-02-13 04:07:26 +00001474 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001475 if (!*it) {
1476 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001477 continue;
1478 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001479 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1480 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001481 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001482 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001483}
1484
John McCallfaf5fb42010-08-26 23:41:50 +00001485MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001486Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001487 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001488 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001489 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001490 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1491 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1492 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001493 "Member must be a FieldDecl or IndirectFieldDecl");
1494
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001495 if (Member->isInvalidDecl())
1496 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001497
John McCalle22a04a2009-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 McCallc90f6d72009-11-04 23:13:52 +00001501 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-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 Friedman8e1433b2009-07-29 19:44:27 +00001515 bool HasDependentArg = false;
1516 for (unsigned i = 0; i < NumArgs; i++)
1517 HasDependentArg |= Args[i]->isTypeDependent();
1518
Chandler Carruthd44c3102010-12-06 09:23:57 +00001519 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001520 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-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 Carruthd44c3102010-12-06 09:23:57 +00001523 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1524 RParenLoc);
Douglas Gregor7ae2d772010-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 Carruthd44c3102010-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 McCallacf0ee52010-10-08 02:01:28 +00001539
Chandler Carruthd44c3102010-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 Gregora40433a2010-12-07 00:41:46 +00001553 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-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 Gregor7ae2d772010-01-31 09:12:51 +00001569 }
1570
Chandler Carruthd44c3102010-12-06 09:23:57 +00001571 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001572 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001573 IdLoc, LParenLoc, Init,
1574 RParenLoc);
1575 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001576 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001577 IdLoc, LParenLoc, Init,
1578 RParenLoc);
1579 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001580}
1581
John McCallfaf5fb42010-08-26 23:41:50 +00001582MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001583Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1584 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001585 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001586 SourceLocation LParenLoc,
1587 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001588 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-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 Redl9cb4be22011-03-12 13:53:51 +00001593
Alexis Huntc5575cc2011-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());
Alexis Hunt6118d662011-05-04 05:57:24 +00001609 CXXConstructorDecl *Constructor
1610 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-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);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001641}
1642
1643MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001644Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001645 Expr **Args, unsigned NumArgs,
1646 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001647 CXXRecordDecl *ClassDecl,
1648 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001649 bool HasDependentArg = false;
1650 for (unsigned i = 0; i < NumArgs; i++)
1651 HasDependentArg |= Args[i]->isTypeDependent();
1652
Douglas Gregor1c69bf02010-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 Lewycky9331ed82010-11-20 01:29:55 +00001662 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-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 Gregor44e7df62011-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 Gregor1c69bf02010-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) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001690 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1691 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001692 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1693 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001694
Douglas Gregor1c69bf02010-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 Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001720 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001721 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1722 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001723
Douglas Gregor7ae2d772010-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 Stump11289f42009-09-09 15:08:12 +00001730
Alexis Hunt1d792652011-01-08 20:30:50 +00001731 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001732 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001733 LParenLoc,
1734 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001735 RParenLoc,
1736 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001737 }
Douglas Gregor7ae2d772010-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 Bagnara1108e7b2010-05-20 10:00:11 +00001745 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-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 Carlsson43c64af2010-04-21 19:52:01 +00001754 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001760 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001761 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001762 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001763 if (BaseInit.isInvalid())
1764 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001765
1766 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-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 Gregora40433a2010-12-07 00:41:46 +00001771 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-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 McCalldadc5752010-08-24 06:29:42 +00001783 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001784 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1785 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001786 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001787 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001788 LParenLoc,
1789 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001790 RParenLoc,
1791 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001792 }
1793
Alexis Hunt1d792652011-01-08 20:30:50 +00001794 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001795 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001796 LParenLoc,
1797 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001798 RParenLoc,
1799 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001800}
1801
Anders Carlsson1b00e242010-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 Carlsson6bd91c32010-04-23 02:00:02 +00001810static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001811BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001812 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001813 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001814 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001815 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001816 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001817 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1818 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001819
John McCalldadc5752010-08-24 06:29:42 +00001820 ExprResult BaseInit;
Anders Carlsson1b00e242010-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 McCallfaf5fb42010-08-26 23:41:50 +00001828 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001829 break;
1830 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001831
Anders Carlsson1b00e242010-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 Gregorea972d32011-02-28 21:54:11 +00001837 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001838 Constructor->getLocation(), ParamType,
1839 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001840
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001841 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001842 QualType ArgTy =
1843 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1844 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001845
1846 CXXCastPath BasePath;
1847 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001848 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1849 CK_UncheckedDerivedToBase,
1850 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001851
Anders Carlsson1b00e242010-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 McCallfaf5fb42010-08-26 23:41:50 +00001858 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001859 break;
1860 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001861
Anders Carlsson1b00e242010-04-23 03:10:23 +00001862 case IIK_Move:
1863 assert(false && "Unhandled initializer kind!");
1864 }
John McCallb268a282010-08-23 23:25:46 +00001865
Douglas Gregora40433a2010-12-07 00:41:46 +00001866 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001867 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001868 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001869
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001870 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001871 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001872 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1873 SourceLocation()),
1874 BaseSpec->isVirtual(),
1875 SourceLocation(),
1876 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001877 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001878 SourceLocation());
1879
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001880 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001881}
1882
Anders Carlsson3c1db572010-04-23 02:15:47 +00001883static bool
1884BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001885 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001886 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001887 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001888 if (Field->isInvalidDecl())
1889 return true;
1890
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001891 SourceLocation Loc = Constructor->getLocation();
1892
Anders Carlsson423f5d82010-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 Gregorea972d32011-02-28 21:54:11 +00001898 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001899 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-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 McCalldadc5752010-08-24 06:29:42 +00001907 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001908 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-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 Carlsson423f5d82010-04-23 16:04:08 +00001916 return true;
1917
Douglas Gregor94f9a482010-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 Bagnaradff19302011-03-08 08:55:46 +00001936 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001937 IterationVarName, SizeType,
1938 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001939 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001940 IndexVariables.push_back(IterationVar);
1941
1942 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001943 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001944 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-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 McCallb268a282010-08-23 23:25:46 +00001949 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001950 Loc,
John McCallb268a282010-08-23 23:25:46 +00001951 IterationVarRef.take(),
Douglas Gregor94f9a482010-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 McCalldadc5752010-08-24 06:29:42 +00001978 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001979 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001980 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001981 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001982 if (MemberInit.isInvalid())
1983 return true;
1984
1985 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001986 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001987 MemberInit.takeAs<Expr>(), Loc,
1988 IndexVariables.data(),
1989 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001990 return false;
1991 }
1992
Anders Carlsson423f5d82010-04-23 16:04:08 +00001993 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1994
Anders Carlsson3c1db572010-04-23 02:15:47 +00001995 QualType FieldBaseElementType =
1996 SemaRef.Context.getBaseElementType(Field->getType());
1997
Anders Carlsson3c1db572010-04-23 02:15:47 +00001998 if (FieldBaseElementType->isRecordType()) {
1999 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002000 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002001 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002002
2003 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002004 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002005 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002006
Douglas Gregora40433a2010-12-07 00:41:46 +00002007 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002008 if (MemberInit.isInvalid())
2009 return true;
2010
2011 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002012 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002013 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002014 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002015 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002016 return false;
2017 }
Anders Carlssondca6be02010-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 Carlsson3c1db572010-04-23 02:15:47 +00002038
2039 // Nothing to initialize.
2040 CXXMemberInit = 0;
2041 return false;
2042}
John McCallbc83b3f2010-05-20 23:23:51 +00002043
2044namespace {
2045struct BaseAndFieldInfo {
2046 Sema &S;
2047 CXXConstructorDecl *Ctor;
2048 bool AnyErrorsInInits;
2049 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002050 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2051 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-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 Carruth139e9622010-06-30 02:59:29 +00002067 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002068 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002069 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-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 McCallbc83b3f2010-05-20 23:23:51 +00002076 CXXRecordDecl *FieldClassDecl
2077 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-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++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002088 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002089 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-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 Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002094 } else if ((*FA)->isAnonymousStructOrUnion()) {
2095 if (CollectFieldInitializer(Info, Top, *FA))
2096 return true;
Chandler Carruth139e9622010-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 McCallbc83b3f2010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00002122 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002123 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2124 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002125
Francois Pichetd583da02010-12-04 09:14:42 +00002126 if (Init)
2127 Info.AllToInit.push_back(Init);
2128
John McCallbc83b3f2010-05-20 23:23:51 +00002129 return false;
2130}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002131
2132bool
2133Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2134 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002135 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-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
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002142 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2143 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2144 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2145 }
2146
Alexis Hunte2622992011-05-05 00:05:47 +00002147 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002148
Alexis Hunt61bc1732011-05-01 07:04:31 +00002149 return false;
2150}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002151
Eli Friedman9cf6b592009-11-09 19:20:36 +00002152bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002153Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2154 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002155 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002156 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002157 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002158 // Just store the initializers as written, they will be checked during
2159 // instantiation.
2160 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002161 Constructor->setNumCtorInitializers(NumInitializers);
2162 CXXCtorInitializer **baseOrMemberInitializers =
2163 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002164 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002165 NumInitializers * sizeof(CXXCtorInitializer*));
2166 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002167 }
2168
2169 return false;
2170 }
2171
John McCallbc83b3f2010-05-20 23:23:51 +00002172 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002173
Fariborz Jahanian3501bce2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00002176 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002177 if (!ClassDecl)
2178 return true;
2179
Eli Friedman9cf6b592009-11-09 19:20:36 +00002180 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002181
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002182 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002183 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002184
2185 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002186 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002187 else
Francois Pichetd583da02010-12-04 09:14:42 +00002188 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002189 }
2190
Anders Carlsson43c64af2010-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 Carlssondb0a9652010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00002203 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002204 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2205 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002206 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002207 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002208 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002209 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002210 VBase, IsInheritedVirtualBase,
2211 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002212 HadError = true;
2213 continue;
2214 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002215
John McCallbc83b3f2010-05-20 23:23:51 +00002216 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002217 }
2218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
John McCallbc83b3f2010-05-20 23:23:51 +00002220 // Non-virtual bases.
Anders Carlssondb0a9652010-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 Stump11289f42009-09-09 15:08:12 +00002226
Alexis Hunt1d792652011-01-08 20:30:50 +00002227 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002228 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2229 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002230 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002231 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002232 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002233 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002234 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002235 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002236 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002237 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002238
John McCallbc83b3f2010-05-20 23:23:51 +00002239 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002240 }
2241 }
Mike Stump11289f42009-09-09 15:08:12 +00002242
John McCallbc83b3f2010-05-20 23:23:51 +00002243 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002244 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-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 McCallbc83b3f2010-05-20 23:23:51 +00002251 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002252 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002253 }
Mike Stump11289f42009-09-09 15:08:12 +00002254
John McCallbc83b3f2010-05-20 23:23:51 +00002255 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002256 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002257 Constructor->setNumCtorInitializers(NumInitializers);
2258 CXXCtorInitializer **baseOrMemberInitializers =
2259 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002260 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002261 NumInitializers * sizeof(CXXCtorInitializer*));
2262 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002263
John McCalla6309952010-03-16 21:39:52 +00002264 // Constructors implicitly reference the base and member
2265 // destructors.
2266 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2267 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002268 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002269
2270 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002271}
2272
Eli Friedman952c15d2009-07-21 19:28:10 +00002273static void *GetKeyForTopLevelField(FieldDecl *Field) {
2274 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002275 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00002282static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002283 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002284}
2285
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002286static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002287 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002288 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002289 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002290
Eli Friedman952c15d2009-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 Pichetd583da02010-12-04 09:14:42 +00002293 FieldDecl *Field = Member->getAnyMember();
2294
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00002297 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00002307 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002308 }
Mike Stump11289f42009-09-09 15:08:12 +00002309
Anders Carlssona942dcd2010-03-30 15:39:27 +00002310 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002311}
2312
Anders Carlssone857b292010-04-02 03:37:03 +00002313static void
2314DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002315 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002316 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002317 unsigned NumInits) {
2318 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002319 return;
Mike Stump11289f42009-09-09 15:08:12 +00002320
Argyrios Kyrtzidis1cb0de12010-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) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002325 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-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 Carlssone0eebb32009-08-27 05:45:01 +00002334 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002335
John McCallbb7b6582010-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 Stump11289f42009-09-09 15:08:12 +00002340
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002341 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2342
John McCallbb7b6582010-04-10 07:37:23 +00002343 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002344 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002345 ClassDecl->vbases_begin(),
2346 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002347 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002348
John McCallbb7b6582010-04-10 07:37:23 +00002349 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002350 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002351 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002352 if (Base->isVirtual())
2353 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002354 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
John McCallbb7b6582010-04-10 07:37:23 +00002357 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002358 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2359 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002360 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002361
John McCallbb7b6582010-04-10 07:37:23 +00002362 unsigned NumIdealInits = IdealInitKeys.size();
2363 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002364
Alexis Hunt1d792652011-01-08 20:30:50 +00002365 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002366 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002367 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002368 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00002374 break;
John McCallbb7b6582010-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 Gregoraabdfcb2010-05-20 23:49:34 +00002379 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002380 Sema::SemaDiagnosticBuilder D =
2381 SemaRef.Diag(PrevInit->getSourceLocation(),
2382 diag::warn_initializer_out_of_order);
2383
Francois Pichetd583da02010-12-04 09:14:42 +00002384 if (PrevInit->isAnyMemberInitializer())
2385 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002386 else
2387 D << 1 << PrevInit->getBaseClassInfo()->getType();
2388
Francois Pichetd583da02010-12-04 09:14:42 +00002389 if (Init->isAnyMemberInitializer())
2390 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00002397 break;
John McCallbb7b6582010-04-10 07:37:23 +00002398
2399 assert(IdealIndex != NumIdealInits &&
2400 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002401 }
John McCallbb7b6582010-04-10 07:37:23 +00002402
2403 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002404 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002405}
2406
John McCall23eebd92010-04-10 09:28:51 +00002407namespace {
2408bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002409 CXXCtorInitializer *Init,
2410 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-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 McCall424cec92011-01-19 06:33:43 +00002422 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-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
Alexis Hunt1d792652011-01-08 20:30:50 +00002435typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002436typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2437
2438bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002439 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002440 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002441 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-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 Carlssone857b292010-04-02 03:37:03 +00002472/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002473void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-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 McCall48871652010-08-21 09:40:31 +00002483 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002484
2485 if (!Constructor) {
2486 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2487 return;
2488 }
2489
Alexis Hunt1d792652011-01-08 20:30:50 +00002490 CXXCtorInitializer **MemInits =
2491 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-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*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002496 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002497
2498 // Mapping for the inconsistent anonymous-union initializers check.
2499 RedundantUnionMap MemberUnions;
2500
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002501 bool HadError = false;
2502 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002503 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002504
Abramo Bagnara341d7832010-05-26 18:09:23 +00002505 // Set the source order index.
2506 Init->setSourceOrder(i);
2507
Francois Pichetd583da02010-12-04 09:14:42 +00002508 if (Init->isAnyMemberInitializer()) {
2509 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002510 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2511 CheckRedundantUnionInit(*this, Init, MemberUnions))
2512 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002513 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002514 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2515 if (CheckRedundantInit(*this, Init, Members[Key]))
2516 HadError = true;
Alexis Huntc5575cc2011-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;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002525 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002526 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002527 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002528 // Return immediately as the initializer is set.
2529 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002530 }
Anders Carlssone857b292010-04-02 03:37:03 +00002531 }
2532
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002533 if (HadError)
2534 return;
2535
Anders Carlssone857b292010-04-02 03:37:03 +00002536 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002537
Alexis Hunt1d792652011-01-08 20:30:50 +00002538 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002539}
2540
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002541void
John McCalla6309952010-03-16 21:39:52 +00002542Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2543 CXXRecordDecl *ClassDecl) {
2544 // Ignore dependent contexts.
2545 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002546 return;
John McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002552
Anders Carlssondee9a302009-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 Jahanian16f94c62010-05-17 18:15:18 +00002557 if (Field->isInvalidDecl())
2558 continue;
Anders Carlssondee9a302009-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-Gay93615d92011-03-28 01:39:13 +00002566 if (FieldClassDecl->isInvalidDecl())
2567 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002568 if (FieldClassDecl->hasTrivialDestructor())
2569 continue;
2570
Douglas Gregore71edda2010-07-01 22:47:18 +00002571 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002572 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002573 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002574 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002575 << Field->getDeclName()
2576 << FieldType);
2577
John McCalla6309952010-03-16 21:39:52 +00002578 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002579 }
2580
John McCall1064d7e2010-03-16 05:22:47 +00002581 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2582
Anders Carlssondee9a302009-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 McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002590 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002591 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002592
John McCall1064d7e2010-03-16 05:22:47 +00002593 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-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 Carlssondee9a302009-11-17 04:44:12 +00002598 if (BaseClassDecl->hasTrivialDestructor())
2599 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002600
Douglas Gregore71edda2010-07-01 22:47:18 +00002601 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002602 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-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 Gregor89336232010-03-29 23:34:08 +00002606 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002607 << Base->getType()
2608 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002609
John McCalla6309952010-03-16 21:39:52 +00002610 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002611 }
2612
2613 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002614 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2615 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-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 McCall1064d7e2010-03-16 05:22:47 +00002624 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-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 Jahanian37d06562009-09-03 23:18:17 +00002629 if (BaseClassDecl->hasTrivialDestructor())
2630 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002631
Douglas Gregore71edda2010-07-01 22:47:18 +00002632 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002633 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002634 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002635 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002636 << VBase->getType());
2637
John McCalla6309952010-03-16 21:39:52 +00002638 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002639 }
2640}
2641
John McCall48871652010-08-21 09:40:31 +00002642void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002643 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002644 return;
Mike Stump11289f42009-09-09 15:08:12 +00002645
Mike Stump11289f42009-09-09 15:08:12 +00002646 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002647 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002648 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002649}
2650
Mike Stump11289f42009-09-09 15:08:12 +00002651bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002652 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002653 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002654 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002655 else
John McCall02db245d2010-08-18 09:41:07 +00002656 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002657}
2658
Anders Carlssoneabf7702009-08-27 00:13:57 +00002659bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002660 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002661 if (!getLangOptions().CPlusPlus)
2662 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002663
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002664 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002665 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002666
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002667 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002668 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002669 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002670 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002671
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002672 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002673 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002674 }
Mike Stump11289f42009-09-09 15:08:12 +00002675
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002676 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002677 if (!RT)
2678 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002679
John McCall67da35c2010-02-04 22:26:26 +00002680 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002681
John McCall02db245d2010-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 McCall67da35c2010-02-04 22:26:26 +00002687 return false;
2688
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002689 if (!RD->isAbstract())
2690 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002691
Anders Carlssoneabf7702009-08-27 00:13:57 +00002692 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002693 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002694
John McCall02db245d2010-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 Carlsson576cc6f2009-03-22 20:18:17 +00002701 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002702 return;
Mike Stump11289f42009-09-09 15:08:12 +00002703
Douglas Gregor4165bd62010-03-23 23:47:56 +00002704 CXXFinalOverriderMap FinalOverriders;
2705 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002706
Anders Carlssona2f74f32010-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 Gregor4165bd62010-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 Stump11289f42009-09-09 15:08:12 +00002722
Douglas Gregor4165bd62010-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 Carlssona2f74f32010-06-03 01:00:02 +00002730 if (!SeenPureMethods.insert(SO->second.front().Method))
2731 continue;
2732
Douglas Gregor4165bd62010-03-23 23:47:56 +00002733 Diag(SO->second.front().Method->getLocation(),
2734 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002735 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002736 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002737 }
2738
2739 if (!PureVirtualClassDiagSet)
2740 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2741 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002742}
2743
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002744namespace {
John McCall02db245d2010-08-18 09:41:07 +00002745struct AbstractUsageInfo {
2746 Sema &S;
2747 CXXRecordDecl *Record;
2748 CanQualType AbstractType;
2749 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002750
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002756
John McCall02db245d2010-08-18 09:41:07 +00002757 void DiagnoseAbstractType() {
2758 if (Invalid) return;
2759 S.DiagnoseAbstractType(Record);
2760 Invalid = true;
2761 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002762
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002779 }
John McCall02db245d2010-08-18 09:41:07 +00002780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
John McCall02db245d2010-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 Gregor385d3fd2011-02-22 23:21:06 +00002785 if (!TL.getArg(I))
2786 continue;
2787
John McCall02db245d2010-08-18 09:41:07 +00002788 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2789 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002790 }
John McCall02db245d2010-08-18 09:41:07 +00002791 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002792
John McCall02db245d2010-08-18 09:41:07 +00002793 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2794 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2795 }
Mike Stump11289f42009-09-09 15:08:12 +00002796
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002805 }
John McCall02db245d2010-08-18 09:41:07 +00002806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
John McCall02db245d2010-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 Stump11289f42009-09-09 15:08:12 +00002817
John McCall02db245d2010-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 Carlssonb57738b2009-03-24 17:23:42 +00002836 }
John McCall02db245d2010-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.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002864 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-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 Carlssonb5a27b42009-03-24 01:19:16 +00002907}
2908
Douglas Gregorc99f1552009-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 Gregor0be31a22010-07-02 17:43:08 +00002912void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002913 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002914 return;
2915
John McCall02db245d2010-08-18 09:41:07 +00002916 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2917 AbstractUsageInfo Info(*this, Record);
2918 CheckAbstractClassUsage(Info, Record);
2919 }
Douglas Gregor454a5b62010-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 Kramer659d7fc2010-04-16 17:43:15 +00002931 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-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 Gregor88d292c2010-05-13 16:44:06 +00002944
Anders Carlssone771e762011-01-25 18:08:22 +00002945 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002946 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-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 Pichet783dd6e2010-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 Gregor36c22a22010-10-15 13:21:21 +00002964 break;
2965 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002966 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002967 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002968
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002969 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002970 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002971 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002972 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002973 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2974 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2975 }
Argyrios Kyrtzidis7272d9c2011-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 Kyrtzidis7a1778e2011-03-03 22:58:57 +00002983 if (!(*M)->isStatic())
2984 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002985 }
2986 }
Sebastian Redl08905022011-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 Redlc1f8e492011-03-12 13:44:32 +00002995 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002996
2997 CheckExplicitlyDefaultedMethods(Record);
2998}
2999
3000void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3001 for (CXXRecordDecl::ctor_iterator CI = Record->ctor_begin(),
3002 CE = Record->ctor_end();
3003 CI != CE; ++CI) {
3004 if (!CI->isInvalidDecl() && CI->isExplicitlyDefaulted()) {
3005 if (CI->isDefaultConstructor()) {
3006 CheckExplicitlyDefaultedDefaultConstructor(*CI);
3007 }
3008
3009 // FIXME: Do copy and move constructors
3010 }
3011 }
3012
3013 // FIXME: Do copy and move assignment and destructors
3014}
3015
3016void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3017 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3018
3019 // Whether this was the first-declared instance of the constructor.
3020 // This affects whether we implicitly add an exception spec (and, eventually,
3021 // constexpr). It is also ill-formed to explicitly default a constructor such
3022 // that it would be deleted. (C++0x [decl.fct.def.default])
3023 bool First = CD == CD->getCanonicalDecl();
3024
3025 if (CD->getNumParams() != 0) {
3026 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3027 << CD->getSourceRange();
3028 CD->setInvalidDecl();
3029 return;
3030 }
3031
3032 ImplicitExceptionSpecification Spec
3033 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3034 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3035 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3036 *ExceptionType = Context.getFunctionType(
3037 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3038
3039 if (CtorType->hasExceptionSpec()) {
3040 if (CheckEquivalentExceptionSpec(
3041 PDiag(diag::err_incorrect_defaulted_exception_spec),
3042 PDiag(),
3043 ExceptionType, SourceLocation(),
3044 CtorType, CD->getLocation())) {
3045 CD->setInvalidDecl();
3046 return;
3047 }
3048 } else if (First) {
3049 // We set the declaration to have the computed exception spec here.
3050 // We know there are no parameters.
3051 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3052 }
Alexis Huntb3153022011-05-12 03:51:48 +00003053
3054 if (ShouldDeleteDefaultConstructor(CD)) {
3055 if (First)
3056 CD->setDeletedAsWritten();
3057 else
3058 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3059 << getSpecialMember(CD);
3060 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003061}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003062
Alexis Huntea6f0322011-05-11 22:34:38 +00003063bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3064 CXXRecordDecl *RD = CD->getParent();
3065 assert(!RD->isDependentType() && "do deletion after instantiation");
3066 if (!LangOpts.CPlusPlus0x)
3067 return false;
3068
3069 // Do access control from the constructor
3070 ContextRAII CtorContext(*this, CD);
3071
3072 bool Union = RD->isUnion();
3073 bool AllConst = true;
3074
3075 DiagnosticErrorTrap Trap(Diags);
3076
3077 // We do this because we should never actually use an anonymous
3078 // union's constructor.
3079 if (Union && RD->isAnonymousStructOrUnion())
3080 return false;
3081
3082 // FIXME: We should put some diagnostic logic right into this function.
3083
3084 // C++0x [class.ctor]/5
3085 // A defaulted default constructor for class X is defined as delete if:
3086
3087 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3088 BE = RD->bases_end();
3089 BI != BE; ++BI) {
3090 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3091 assert(BaseDecl && "base isn't a CXXRecordDecl");
3092
3093 // -- any [direct base class] has a type with a destructor that is
3094 // delete or inaccessible from the defaulted default constructor
3095 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3096 if (BaseDtor->isDeleted())
3097 return true;
3098 if (CheckDestructorAccess(SourceLocation(), BaseDtor, PDiag()) !=
3099 AR_accessible)
3100 return true;
3101
3102 // We'll handle this one later
3103 if (BI->isVirtual())
3104 continue;
3105
3106 // -- any [direct base class either] has no default constructor or
3107 // overload resolution as applied to [its] default constructor
3108 // results in an ambiguity or in a function that is deleted or
3109 // inaccessible from the defaulted default constructor
3110 InitializedEntity BaseEntity =
3111 InitializedEntity::InitializeBase(Context, BI, 0);
3112 InitializationKind Kind =
3113 InitializationKind::CreateDirect(SourceLocation(), SourceLocation(),
3114 SourceLocation());
3115
3116 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3117
3118 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3119 return true;
3120 }
3121
3122 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3123 BE = RD->vbases_end();
3124 BI != BE; ++BI) {
3125 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3126 assert(BaseDecl && "base isn't a CXXRecordDecl");
3127
3128 // -- any [virtual base class] has a type with a destructor that is
3129 // delete or inaccessible from the defaulted default constructor
3130 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3131 if (BaseDtor->isDeleted())
3132 return true;
3133 if (CheckDestructorAccess(SourceLocation(), BaseDtor, PDiag()) !=
3134 AR_accessible)
3135 return true;
3136
3137 // -- any [virtual base class either] has no default constructor or
3138 // overload resolution as applied to [its] default constructor
3139 // results in an ambiguity or in a function that is deleted or
3140 // inaccessible from the defaulted default constructor
3141 InitializedEntity BaseEntity =
3142 InitializedEntity::InitializeBase(Context, BI, BI);
3143 InitializationKind Kind =
3144 InitializationKind::CreateDirect(SourceLocation(), SourceLocation(),
3145 SourceLocation());
3146
3147 InitializationSequence InitSeq(*this, BaseEntity, Kind, 0, 0);
3148
3149 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3150 return true;
3151 }
3152
3153 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3154 FE = RD->field_end();
3155 FI != FE; ++FI) {
3156 QualType FieldType = Context.getBaseElementType(FI->getType());
3157 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3158
3159 // -- any non-static data member with no brace-or-equal-initializer is of
3160 // reference type
3161 if (FieldType->isReferenceType())
3162 return true;
3163
3164 // -- X is a union and all its variant members are of const-qualified type
3165 // (or array thereof)
3166 if (Union && !FieldType.isConstQualified())
3167 AllConst = false;
3168
3169 if (FieldRecord) {
3170 // -- X is a union-like class that has a variant member with a non-trivial
3171 // default constructor
3172 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3173 return true;
3174
3175 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3176 if (FieldDtor->isDeleted())
3177 return true;
3178 if (CheckDestructorAccess(SourceLocation(), FieldDtor, PDiag()) !=
3179 AR_accessible)
3180 return true;
3181
3182 // -- any non-variant non-static data member of const-qualified type (or
3183 // array thereof) with no brace-or-equal-initializer does not have a
3184 // user-provided default constructor
3185 if (FieldType.isConstQualified() &&
3186 !FieldRecord->hasUserProvidedDefaultConstructor())
3187 return true;
3188
3189 if (!Union && FieldRecord->isUnion() &&
3190 FieldRecord->isAnonymousStructOrUnion()) {
3191 // We're okay to reuse AllConst here since we only care about the
3192 // value otherwise if we're in a union.
3193 AllConst = true;
3194
3195 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3196 UE = FieldRecord->field_end();
3197 UI != UE; ++UI) {
3198 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3199 CXXRecordDecl *UnionFieldRecord =
3200 UnionFieldType->getAsCXXRecordDecl();
3201
3202 if (!UnionFieldType.isConstQualified())
3203 AllConst = false;
3204
3205 if (UnionFieldRecord &&
3206 !UnionFieldRecord->hasTrivialDefaultConstructor())
3207 return true;
3208 }
3209
3210 if (AllConst)
3211 return true;
3212
3213 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003214 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003215 continue;
3216 }
3217 }
3218
3219 InitializedEntity MemberEntity =
3220 InitializedEntity::InitializeMember(*FI, 0);
3221 InitializationKind Kind =
3222 InitializationKind::CreateDirect(SourceLocation(), SourceLocation(),
3223 SourceLocation());
3224
3225 InitializationSequence InitSeq(*this, MemberEntity, Kind, 0, 0);
3226
3227 if (InitSeq.getKind() == InitializationSequence::FailedSequence)
3228 return true;
3229 }
3230
3231 if (Union && AllConst)
3232 return true;
3233
3234 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003235}
3236
3237/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00003238namespace {
3239 struct FindHiddenVirtualMethodData {
3240 Sema *S;
3241 CXXMethodDecl *Method;
3242 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3243 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3244 };
3245}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003246
3247/// \brief Member lookup function that determines whether a given C++
3248/// method overloads virtual methods in a base class without overriding any,
3249/// to be used with CXXRecordDecl::lookupInBases().
3250static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3251 CXXBasePath &Path,
3252 void *UserData) {
3253 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3254
3255 FindHiddenVirtualMethodData &Data
3256 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3257
3258 DeclarationName Name = Data.Method->getDeclName();
3259 assert(Name.getNameKind() == DeclarationName::Identifier);
3260
3261 bool foundSameNameMethod = false;
3262 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3263 for (Path.Decls = BaseRecord->lookup(Name);
3264 Path.Decls.first != Path.Decls.second;
3265 ++Path.Decls.first) {
3266 NamedDecl *D = *Path.Decls.first;
3267 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003268 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003269 foundSameNameMethod = true;
3270 // Interested only in hidden virtual methods.
3271 if (!MD->isVirtual())
3272 continue;
3273 // If the method we are checking overrides a method from its base
3274 // don't warn about the other overloaded methods.
3275 if (!Data.S->IsOverload(Data.Method, MD, false))
3276 return true;
3277 // Collect the overload only if its hidden.
3278 if (!Data.OverridenAndUsingBaseMethods.count(MD))
3279 overloadedMethods.push_back(MD);
3280 }
3281 }
3282
3283 if (foundSameNameMethod)
3284 Data.OverloadedMethods.append(overloadedMethods.begin(),
3285 overloadedMethods.end());
3286 return foundSameNameMethod;
3287}
3288
3289/// \brief See if a method overloads virtual methods in a base class without
3290/// overriding any.
3291void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
3292 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
3293 MD->getLocation()) == Diagnostic::Ignored)
3294 return;
3295 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
3296 return;
3297
3298 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
3299 /*bool RecordPaths=*/false,
3300 /*bool DetectVirtual=*/false);
3301 FindHiddenVirtualMethodData Data;
3302 Data.Method = MD;
3303 Data.S = this;
3304
3305 // Keep the base methods that were overriden or introduced in the subclass
3306 // by 'using' in a set. A base method not in this set is hidden.
3307 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
3308 res.first != res.second; ++res.first) {
3309 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
3310 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
3311 E = MD->end_overridden_methods();
3312 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003313 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003314 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
3315 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003316 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003317 }
3318
3319 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
3320 !Data.OverloadedMethods.empty()) {
3321 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
3322 << MD << (Data.OverloadedMethods.size() > 1);
3323
3324 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3325 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3326 Diag(overloadedMD->getLocation(),
3327 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3328 }
3329 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00003330}
3331
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003332void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00003333 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003334 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003335 SourceLocation RBrac,
3336 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003337 if (!TagDecl)
3338 return;
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003340 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00003341
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003342 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00003343 // strict aliasing violation!
3344 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003345 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00003346
Douglas Gregor0be31a22010-07-02 17:43:08 +00003347 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00003348 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003349}
3350
Douglas Gregor05379422008-11-03 17:51:48 +00003351/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3352/// special functions, such as the default constructor, copy
3353/// constructor, or destructor, to the given C++ class (C++
3354/// [special]p1). This routine can only be executed just before the
3355/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003356void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00003357 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003358 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003359
Douglas Gregor54be3392010-07-01 17:57:27 +00003360 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00003361 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003362
Douglas Gregor330b9cf2010-07-02 21:50:04 +00003363 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3364 ++ASTContext::NumImplicitCopyAssignmentOperators;
3365
3366 // If we have a dynamic class, then the copy assignment operator may be
3367 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3368 // it shows up in the right place in the vtable and that we diagnose
3369 // problems with the implicit exception specification.
3370 if (ClassDecl->isDynamicClass())
3371 DeclareImplicitCopyAssignment(ClassDecl);
3372 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003373
Douglas Gregor7454c562010-07-02 20:37:36 +00003374 if (!ClassDecl->hasUserDeclaredDestructor()) {
3375 ++ASTContext::NumImplicitDestructors;
3376
3377 // If we have a dynamic class, then the destructor may be virtual, so we
3378 // have to declare the destructor immediately. This ensures that, e.g., it
3379 // shows up in the right place in the vtable and that we diagnose problems
3380 // with the implicit exception specification.
3381 if (ClassDecl->isDynamicClass())
3382 DeclareImplicitDestructor(ClassDecl);
3383 }
Douglas Gregor05379422008-11-03 17:51:48 +00003384}
3385
Francois Pichet1c229c02011-04-22 22:18:13 +00003386void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3387 if (!D)
3388 return;
3389
3390 int NumParamList = D->getNumTemplateParameterLists();
3391 for (int i = 0; i < NumParamList; i++) {
3392 TemplateParameterList* Params = D->getTemplateParameterList(i);
3393 for (TemplateParameterList::iterator Param = Params->begin(),
3394 ParamEnd = Params->end();
3395 Param != ParamEnd; ++Param) {
3396 NamedDecl *Named = cast<NamedDecl>(*Param);
3397 if (Named->getDeclName()) {
3398 S->AddDecl(Named);
3399 IdResolver.AddDecl(Named);
3400 }
3401 }
3402 }
3403}
3404
John McCall48871652010-08-21 09:40:31 +00003405void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00003406 if (!D)
3407 return;
3408
3409 TemplateParameterList *Params = 0;
3410 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3411 Params = Template->getTemplateParameters();
3412 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3413 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3414 Params = PartialSpec->getTemplateParameters();
3415 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003416 return;
3417
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003418 for (TemplateParameterList::iterator Param = Params->begin(),
3419 ParamEnd = Params->end();
3420 Param != ParamEnd; ++Param) {
3421 NamedDecl *Named = cast<NamedDecl>(*Param);
3422 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003423 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003424 IdResolver.AddDecl(Named);
3425 }
3426 }
3427}
3428
John McCall48871652010-08-21 09:40:31 +00003429void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003430 if (!RecordD) return;
3431 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003432 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003433 PushDeclContext(S, Record);
3434}
3435
John McCall48871652010-08-21 09:40:31 +00003436void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003437 if (!RecordD) return;
3438 PopDeclContext();
3439}
3440
Douglas Gregor4d87df52008-12-16 21:30:33 +00003441/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3442/// parsing a top-level (non-nested) C++ class, and we are now
3443/// parsing those parts of the given Method declaration that could
3444/// not be parsed earlier (C++ [class.mem]p2), such as default
3445/// arguments. This action should enter the scope of the given
3446/// Method declaration as if we had just parsed the qualified method
3447/// name. However, it should not bring the parameters into scope;
3448/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003449void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003450}
3451
3452/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3453/// C++ method declaration. We're (re-)introducing the given
3454/// function parameter into scope for use in parsing later parts of
3455/// the method declaration. For example, we could see an
3456/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003457void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003458 if (!ParamD)
3459 return;
Mike Stump11289f42009-09-09 15:08:12 +00003460
John McCall48871652010-08-21 09:40:31 +00003461 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003462
3463 // If this parameter has an unparsed default argument, clear it out
3464 // to make way for the parsed default argument.
3465 if (Param->hasUnparsedDefaultArg())
3466 Param->setDefaultArg(0);
3467
John McCall48871652010-08-21 09:40:31 +00003468 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003469 if (Param->getDeclName())
3470 IdResolver.AddDecl(Param);
3471}
3472
3473/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3474/// processing the delayed method declaration for Method. The method
3475/// declaration is now considered finished. There may be a separate
3476/// ActOnStartOfFunctionDef action later (not necessarily
3477/// immediately!) for this method, if it was also defined inside the
3478/// class body.
John McCall48871652010-08-21 09:40:31 +00003479void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003480 if (!MethodD)
3481 return;
Mike Stump11289f42009-09-09 15:08:12 +00003482
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003483 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003484
John McCall48871652010-08-21 09:40:31 +00003485 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003486
3487 // Now that we have our default arguments, check the constructor
3488 // again. It could produce additional diagnostics or affect whether
3489 // the class has implicitly-declared destructors, among other
3490 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3492 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003493
3494 // Check the default arguments, which we may have added.
3495 if (!Method->isInvalidDecl())
3496 CheckCXXDefaultArguments(Method);
3497}
3498
Douglas Gregor831c93f2008-11-05 20:51:48 +00003499/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003500/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003501/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003502/// emit diagnostics and set the invalid bit to true. In any case, the type
3503/// will be updated to reflect a well-formed type for the constructor and
3504/// returned.
3505QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003506 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003507 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003508
3509 // C++ [class.ctor]p3:
3510 // A constructor shall not be virtual (10.3) or static (9.4). A
3511 // constructor can be invoked for a const, volatile or const
3512 // volatile object. A constructor shall not be declared const,
3513 // volatile, or const volatile (9.3.2).
3514 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003515 if (!D.isInvalidType())
3516 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3517 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3518 << SourceRange(D.getIdentifierLoc());
3519 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003520 }
John McCall8e7d6562010-08-26 03:08:43 +00003521 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003522 if (!D.isInvalidType())
3523 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3524 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3525 << SourceRange(D.getIdentifierLoc());
3526 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003527 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003528 }
Mike Stump11289f42009-09-09 15:08:12 +00003529
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003530 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003531 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003532 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003533 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3534 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003535 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003536 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3537 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003538 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003539 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3540 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003541 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003542 }
Mike Stump11289f42009-09-09 15:08:12 +00003543
Douglas Gregordb9d6642011-01-26 05:01:58 +00003544 // C++0x [class.ctor]p4:
3545 // A constructor shall not be declared with a ref-qualifier.
3546 if (FTI.hasRefQualifier()) {
3547 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3548 << FTI.RefQualifierIsLValueRef
3549 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3550 D.setInvalidType();
3551 }
3552
Douglas Gregor831c93f2008-11-05 20:51:48 +00003553 // Rebuild the function type "R" without any type qualifiers (in
3554 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003555 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003556 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003557 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3558 return R;
3559
3560 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3561 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003562 EPI.RefQualifier = RQ_None;
3563
Chris Lattner38378bf2009-04-25 08:28:21 +00003564 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003565 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003566}
3567
Douglas Gregor4d87df52008-12-16 21:30:33 +00003568/// CheckConstructor - Checks a fully-formed constructor for
3569/// well-formedness, issuing any diagnostics required. Returns true if
3570/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003571void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003572 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003573 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3574 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003575 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003576
3577 // C++ [class.copy]p3:
3578 // A declaration of a constructor for a class X is ill-formed if
3579 // its first parameter is of type (optionally cv-qualified) X and
3580 // either there are no other parameters or else all other
3581 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003582 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003583 ((Constructor->getNumParams() == 1) ||
3584 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003585 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3586 Constructor->getTemplateSpecializationKind()
3587 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003588 QualType ParamType = Constructor->getParamDecl(0)->getType();
3589 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3590 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003591 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003592 const char *ConstRef
3593 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3594 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003595 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003596 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003597
3598 // FIXME: Rather that making the constructor invalid, we should endeavor
3599 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003600 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003601 }
3602 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003603}
3604
John McCalldeb646e2010-08-04 01:04:25 +00003605/// CheckDestructor - Checks a fully-formed destructor definition for
3606/// well-formedness, issuing any diagnostics required. Returns true
3607/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003608bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003609 CXXRecordDecl *RD = Destructor->getParent();
3610
3611 if (Destructor->isVirtual()) {
3612 SourceLocation Loc;
3613
3614 if (!Destructor->isImplicit())
3615 Loc = Destructor->getLocation();
3616 else
3617 Loc = RD->getLocation();
3618
3619 // If we have a virtual destructor, look up the deallocation function
3620 FunctionDecl *OperatorDelete = 0;
3621 DeclarationName Name =
3622 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003623 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003624 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003625
3626 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003627
3628 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003629 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003630
3631 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003632}
3633
Mike Stump11289f42009-09-09 15:08:12 +00003634static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003635FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3636 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3637 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003638 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003639}
3640
Douglas Gregor831c93f2008-11-05 20:51:48 +00003641/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3642/// the well-formednes of the destructor declarator @p D with type @p
3643/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003644/// emit diagnostics and set the declarator to invalid. Even if this happens,
3645/// will be updated to reflect a well-formed type for the destructor and
3646/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003647QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003648 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003649 // C++ [class.dtor]p1:
3650 // [...] A typedef-name that names a class is a class-name
3651 // (7.1.3); however, a typedef-name that names a class shall not
3652 // be used as the identifier in the declarator for a destructor
3653 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003654 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00003655 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00003656 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00003657 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003658 else if (const TemplateSpecializationType *TST =
3659 DeclaratorType->getAs<TemplateSpecializationType>())
3660 if (TST->isTypeAlias())
3661 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
3662 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003663
3664 // C++ [class.dtor]p2:
3665 // A destructor is used to destroy objects of its class type. A
3666 // destructor takes no parameters, and no return type can be
3667 // specified for it (not even void). The address of a destructor
3668 // shall not be taken. A destructor shall not be static. A
3669 // destructor can be invoked for a const, volatile or const
3670 // volatile object. A destructor shall not be declared const,
3671 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003672 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003673 if (!D.isInvalidType())
3674 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3675 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003676 << SourceRange(D.getIdentifierLoc())
3677 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3678
John McCall8e7d6562010-08-26 03:08:43 +00003679 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003680 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003681 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003682 // Destructors don't have return types, but the parser will
3683 // happily parse something like:
3684 //
3685 // class X {
3686 // float ~X();
3687 // };
3688 //
3689 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003690 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3691 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3692 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003693 }
Mike Stump11289f42009-09-09 15:08:12 +00003694
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003695 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003696 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003697 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003698 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3699 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003700 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003701 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3702 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003703 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003704 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3705 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003706 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003707 }
3708
Douglas Gregordb9d6642011-01-26 05:01:58 +00003709 // C++0x [class.dtor]p2:
3710 // A destructor shall not be declared with a ref-qualifier.
3711 if (FTI.hasRefQualifier()) {
3712 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3713 << FTI.RefQualifierIsLValueRef
3714 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3715 D.setInvalidType();
3716 }
3717
Douglas Gregor831c93f2008-11-05 20:51:48 +00003718 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003719 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003720 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3721
3722 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003723 FTI.freeArgs();
3724 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003725 }
3726
Mike Stump11289f42009-09-09 15:08:12 +00003727 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003728 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003729 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003730 D.setInvalidType();
3731 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003732
3733 // Rebuild the function type "R" without any type qualifiers or
3734 // parameters (in case any of the errors above fired) and with
3735 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003736 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003737 if (!D.isInvalidType())
3738 return R;
3739
Douglas Gregor95755162010-07-01 05:10:53 +00003740 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003741 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3742 EPI.Variadic = false;
3743 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003744 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003745 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003746}
3747
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003748/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3749/// well-formednes of the conversion function declarator @p D with
3750/// type @p R. If there are any errors in the declarator, this routine
3751/// will emit diagnostics and return true. Otherwise, it will return
3752/// false. Either way, the type @p R will be updated to reflect a
3753/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003754void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003755 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003756 // C++ [class.conv.fct]p1:
3757 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003758 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003759 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003760 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003761 if (!D.isInvalidType())
3762 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3763 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3764 << SourceRange(D.getIdentifierLoc());
3765 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003766 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003767 }
John McCall212fa2e2010-04-13 00:04:31 +00003768
3769 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3770
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003771 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003772 // Conversion functions don't have return types, but the parser will
3773 // happily parse something like:
3774 //
3775 // class X {
3776 // float operator bool();
3777 // };
3778 //
3779 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003780 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3781 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3782 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003783 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003784 }
3785
John McCall212fa2e2010-04-13 00:04:31 +00003786 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3787
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003788 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003789 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003790 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3791
3792 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003793 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003794 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003795 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003796 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003797 D.setInvalidType();
3798 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003799
John McCall212fa2e2010-04-13 00:04:31 +00003800 // Diagnose "&operator bool()" and other such nonsense. This
3801 // is actually a gcc extension which we don't support.
3802 if (Proto->getResultType() != ConvType) {
3803 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3804 << Proto->getResultType();
3805 D.setInvalidType();
3806 ConvType = Proto->getResultType();
3807 }
3808
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003809 // C++ [class.conv.fct]p4:
3810 // The conversion-type-id shall not represent a function type nor
3811 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003812 if (ConvType->isArrayType()) {
3813 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3814 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003815 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003816 } else if (ConvType->isFunctionType()) {
3817 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3818 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003819 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003820 }
3821
3822 // Rebuild the function type "R" without any parameters (in case any
3823 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003824 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003825 if (D.isInvalidType())
3826 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003827
Douglas Gregor5fb53972009-01-14 15:45:31 +00003828 // C++0x explicit conversion operators.
3829 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003830 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003831 diag::warn_explicit_conversion_functions)
3832 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003833}
3834
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003835/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3836/// the declaration of the given C++ conversion function. This routine
3837/// is responsible for recording the conversion function in the C++
3838/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003839Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003840 assert(Conversion && "Expected to receive a conversion function declaration");
3841
Douglas Gregor4287b372008-12-12 08:25:50 +00003842 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003843
3844 // Make sure we aren't redeclaring the conversion function.
3845 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003846
3847 // C++ [class.conv.fct]p1:
3848 // [...] A conversion function is never used to convert a
3849 // (possibly cv-qualified) object to the (possibly cv-qualified)
3850 // same object type (or a reference to it), to a (possibly
3851 // cv-qualified) base class of that type (or a reference to it),
3852 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003853 // FIXME: Suppress this warning if the conversion function ends up being a
3854 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003855 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003856 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003857 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003858 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003859 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3860 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003861 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003862 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003863 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3864 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003865 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003866 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003867 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003868 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003869 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003870 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003871 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003872 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003873 }
3874
Douglas Gregor457104e2010-09-29 04:25:11 +00003875 if (FunctionTemplateDecl *ConversionTemplate
3876 = Conversion->getDescribedFunctionTemplate())
3877 return ConversionTemplate;
3878
John McCall48871652010-08-21 09:40:31 +00003879 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003880}
3881
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003882//===----------------------------------------------------------------------===//
3883// Namespace Handling
3884//===----------------------------------------------------------------------===//
3885
John McCallb1be5232010-08-26 09:15:37 +00003886
3887
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003888/// ActOnStartNamespaceDef - This is called at the start of a namespace
3889/// definition.
John McCall48871652010-08-21 09:40:31 +00003890Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003891 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003892 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00003893 SourceLocation IdentLoc,
3894 IdentifierInfo *II,
3895 SourceLocation LBrace,
3896 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003897 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3898 // For anonymous namespace, take the location of the left brace.
3899 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00003900 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003901 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003902 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003903
3904 Scope *DeclRegionScope = NamespcScope->getParent();
3905
Anders Carlssona7bcade2010-02-07 01:09:23 +00003906 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3907
John McCall2faf32c2010-12-10 02:59:44 +00003908 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3909 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003910
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003911 if (II) {
3912 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003913 // The identifier in an original-namespace-definition shall not
3914 // have been previously defined in the declarative region in
3915 // which the original-namespace-definition appears. The
3916 // identifier in an original-namespace-definition is the name of
3917 // the namespace. Subsequently in that declarative region, it is
3918 // treated as an original-namespace-name.
3919 //
3920 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00003921 // look through using directives, just look for any ordinary names.
3922
3923 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
3924 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
3925 Decl::IDNS_Namespace;
3926 NamedDecl *PrevDecl = 0;
3927 for (DeclContext::lookup_result R
3928 = CurContext->getRedeclContext()->lookup(II);
3929 R.first != R.second; ++R.first) {
3930 if ((*R.first)->getIdentifierNamespace() & IDNS) {
3931 PrevDecl = *R.first;
3932 break;
3933 }
3934 }
3935
Douglas Gregor91f84212008-12-11 16:49:14 +00003936 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3937 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003938 if (Namespc->isInline() != OrigNS->isInline()) {
3939 // inline-ness must match
3940 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3941 << Namespc->isInline();
3942 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3943 Namespc->setInvalidDecl();
3944 // Recover by ignoring the new namespace's inline status.
3945 Namespc->setInline(OrigNS->isInline());
3946 }
3947
Douglas Gregor91f84212008-12-11 16:49:14 +00003948 // Attach this namespace decl to the chain of extended namespace
3949 // definitions.
3950 OrigNS->setNextNamespace(Namespc);
3951 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003952
Mike Stump11289f42009-09-09 15:08:12 +00003953 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003954 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003955 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003956 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003957 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003958 } else if (PrevDecl) {
3959 // This is an invalid name redefinition.
3960 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3961 << Namespc->getDeclName();
3962 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3963 Namespc->setInvalidDecl();
3964 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003965 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003966 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003967 // This is the first "real" definition of the namespace "std", so update
3968 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003969 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003970 // We had already defined a dummy namespace "std". Link this new
3971 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003972 StdNS->setNextNamespace(Namespc);
3973 StdNS->setLocation(IdentLoc);
3974 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003975 }
3976
3977 // Make our StdNamespace cache point at the first real definition of the
3978 // "std" namespace.
3979 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003980 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003981
3982 PushOnScopeChains(Namespc, DeclRegionScope);
3983 } else {
John McCall4fa53422009-10-01 00:25:31 +00003984 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003985 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003986
3987 // Link the anonymous namespace into its parent.
3988 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003989 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003990 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3991 PrevDecl = TU->getAnonymousNamespace();
3992 TU->setAnonymousNamespace(Namespc);
3993 } else {
3994 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3995 PrevDecl = ND->getAnonymousNamespace();
3996 ND->setAnonymousNamespace(Namespc);
3997 }
3998
3999 // Link the anonymous namespace with its previous declaration.
4000 if (PrevDecl) {
4001 assert(PrevDecl->isAnonymousNamespace());
4002 assert(!PrevDecl->getNextNamespace());
4003 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4004 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004005
4006 if (Namespc->isInline() != PrevDecl->isInline()) {
4007 // inline-ness must match
4008 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4009 << Namespc->isInline();
4010 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4011 Namespc->setInvalidDecl();
4012 // Recover by ignoring the new namespace's inline status.
4013 Namespc->setInline(PrevDecl->isInline());
4014 }
John McCall0db42252009-12-16 02:06:49 +00004015 }
John McCall4fa53422009-10-01 00:25:31 +00004016
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00004017 CurContext->addDecl(Namespc);
4018
John McCall4fa53422009-10-01 00:25:31 +00004019 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4020 // behaves as if it were replaced by
4021 // namespace unique { /* empty body */ }
4022 // using namespace unique;
4023 // namespace unique { namespace-body }
4024 // where all occurrences of 'unique' in a translation unit are
4025 // replaced by the same identifier and this identifier differs
4026 // from all other identifiers in the entire program.
4027
4028 // We just create the namespace with an empty name and then add an
4029 // implicit using declaration, just like the standard suggests.
4030 //
4031 // CodeGen enforces the "universally unique" aspect by giving all
4032 // declarations semantically contained within an anonymous
4033 // namespace internal linkage.
4034
John McCall0db42252009-12-16 02:06:49 +00004035 if (!PrevDecl) {
4036 UsingDirectiveDecl* UD
4037 = UsingDirectiveDecl::Create(Context, CurContext,
4038 /* 'using' */ LBrace,
4039 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00004040 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00004041 /* identifier */ SourceLocation(),
4042 Namespc,
4043 /* Ancestor */ CurContext);
4044 UD->setImplicit();
4045 CurContext->addDecl(UD);
4046 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004047 }
4048
4049 // Although we could have an invalid decl (i.e. the namespace name is a
4050 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00004051 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4052 // for the namespace has the declarations that showed up in that particular
4053 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00004054 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00004055 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004056}
4057
Sebastian Redla6602e92009-11-23 15:34:23 +00004058/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4059/// is a namespace alias, returns the namespace it points to.
4060static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4061 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4062 return AD->getNamespace();
4063 return dyn_cast_or_null<NamespaceDecl>(D);
4064}
4065
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004066/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4067/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00004068void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004069 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4070 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004071 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004072 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00004073 if (Namespc->hasAttr<VisibilityAttr>())
4074 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004075}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004076
John McCall28a0cf72010-08-25 07:42:41 +00004077CXXRecordDecl *Sema::getStdBadAlloc() const {
4078 return cast_or_null<CXXRecordDecl>(
4079 StdBadAlloc.get(Context.getExternalSource()));
4080}
4081
4082NamespaceDecl *Sema::getStdNamespace() const {
4083 return cast_or_null<NamespaceDecl>(
4084 StdNamespace.get(Context.getExternalSource()));
4085}
4086
Douglas Gregorcdf87022010-06-29 17:53:46 +00004087/// \brief Retrieve the special "std" namespace, which may require us to
4088/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004089NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00004090 if (!StdNamespace) {
4091 // The "std" namespace has not yet been defined, so build one implicitly.
4092 StdNamespace = NamespaceDecl::Create(Context,
4093 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004094 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00004095 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004096 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004097 }
4098
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004099 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004100}
4101
Douglas Gregora172e082011-03-26 22:25:30 +00004102/// \brief Determine whether a using statement is in a context where it will be
4103/// apply in all contexts.
4104static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4105 switch (CurContext->getDeclKind()) {
4106 case Decl::TranslationUnit:
4107 return true;
4108 case Decl::LinkageSpec:
4109 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4110 default:
4111 return false;
4112 }
4113}
4114
John McCall48871652010-08-21 09:40:31 +00004115Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00004116 SourceLocation UsingLoc,
4117 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004118 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004119 SourceLocation IdentLoc,
4120 IdentifierInfo *NamespcName,
4121 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00004122 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4123 assert(NamespcName && "Invalid NamespcName.");
4124 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00004125
4126 // This can only happen along a recovery path.
4127 while (S->getFlags() & Scope::TemplateParamScope)
4128 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00004129 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00004130
Douglas Gregor889ceb72009-02-03 19:21:40 +00004131 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00004132 NestedNameSpecifier *Qualifier = 0;
4133 if (SS.isSet())
4134 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4135
Douglas Gregor34074322009-01-14 22:20:51 +00004136 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004137 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4138 LookupParsedName(R, S, &SS);
4139 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004140 return 0;
John McCall27b18f82009-11-17 02:14:36 +00004141
Douglas Gregorcdf87022010-06-29 17:53:46 +00004142 if (R.empty()) {
4143 // Allow "using namespace std;" or "using namespace ::std;" even if
4144 // "std" hasn't been defined yet, for GCC compatibility.
4145 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4146 NamespcName->isStr("std")) {
4147 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004148 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00004149 R.resolveKind();
4150 }
4151 // Otherwise, attempt typo correction.
4152 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4153 CTC_NoKeywords, 0)) {
4154 if (R.getAsSingle<NamespaceDecl>() ||
4155 R.getAsSingle<NamespaceAliasDecl>()) {
4156 if (DeclContext *DC = computeDeclContext(SS, false))
4157 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4158 << NamespcName << DC << Corrected << SS.getRange()
4159 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4160 else
4161 Diag(IdentLoc, diag::err_using_directive_suggest)
4162 << NamespcName << Corrected
4163 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4164 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4165 << Corrected;
4166
4167 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004168 } else {
4169 R.clear();
4170 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004171 }
4172 }
4173 }
4174
John McCall9f3059a2009-10-09 21:13:30 +00004175 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00004176 NamedDecl *Named = R.getFoundDecl();
4177 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4178 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00004179 // C++ [namespace.udir]p1:
4180 // A using-directive specifies that the names in the nominated
4181 // namespace can be used in the scope in which the
4182 // using-directive appears after the using-directive. During
4183 // unqualified name lookup (3.4.1), the names appear as if they
4184 // were declared in the nearest enclosing namespace which
4185 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00004186 // namespace. [Note: in this context, "contains" means "contains
4187 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00004188
4189 // Find enclosing context containing both using-directive and
4190 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00004191 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004192 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4193 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4194 CommonAncestor = CommonAncestor->getParent();
4195
Sebastian Redla6602e92009-11-23 15:34:23 +00004196 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00004197 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00004198 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004199
Douglas Gregora172e082011-03-26 22:25:30 +00004200 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00004201 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004202 Diag(IdentLoc, diag::warn_using_directive_in_header);
4203 }
4204
Douglas Gregor889ceb72009-02-03 19:21:40 +00004205 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004206 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00004207 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00004208 }
4209
Douglas Gregor889ceb72009-02-03 19:21:40 +00004210 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00004211 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00004212}
4213
4214void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4215 // If scope has associated entity, then using directive is at namespace
4216 // or translation unit scope. We add UsingDirectiveDecls, into
4217 // it's lookup structure.
4218 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004219 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004220 else
4221 // Otherwise it is block-sope. using-directives will affect lookup
4222 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00004223 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004224}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004225
Douglas Gregorfec52632009-06-20 00:51:54 +00004226
John McCall48871652010-08-21 09:40:31 +00004227Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00004228 AccessSpecifier AS,
4229 bool HasUsingKeyword,
4230 SourceLocation UsingLoc,
4231 CXXScopeSpec &SS,
4232 UnqualifiedId &Name,
4233 AttributeList *AttrList,
4234 bool IsTypeName,
4235 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004236 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004237
Douglas Gregor220f4272009-11-04 16:30:06 +00004238 switch (Name.getKind()) {
4239 case UnqualifiedId::IK_Identifier:
4240 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004241 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004242 case UnqualifiedId::IK_ConversionFunctionId:
4243 break;
4244
4245 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004246 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004247 // C++0x inherited constructors.
4248 if (getLangOptions().CPlusPlus0x) break;
4249
Douglas Gregor220f4272009-11-04 16:30:06 +00004250 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4251 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004252 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004253
4254 case UnqualifiedId::IK_DestructorName:
4255 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4256 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004257 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004258
4259 case UnqualifiedId::IK_TemplateId:
4260 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4261 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00004262 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004263 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004264
4265 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4266 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00004267 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00004268 return 0;
John McCall3969e302009-12-08 07:46:18 +00004269
John McCalla0097262009-12-11 02:10:03 +00004270 // Warn about using declarations.
4271 // TODO: store that the declaration was written without 'using' and
4272 // talk about access decls instead of using decls in the
4273 // diagnostics.
4274 if (!HasUsingKeyword) {
4275 UsingLoc = Name.getSourceRange().getBegin();
4276
4277 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00004278 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00004279 }
4280
Douglas Gregorc4356532010-12-16 00:46:58 +00004281 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4282 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4283 return 0;
4284
John McCall3f746822009-11-17 05:59:44 +00004285 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004286 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004287 /* IsInstantiation */ false,
4288 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00004289 if (UD)
4290 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00004291
John McCall48871652010-08-21 09:40:31 +00004292 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00004293}
4294
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004295/// \brief Determine whether a using declaration considers the given
4296/// declarations as "equivalent", e.g., if they are redeclarations of
4297/// the same entity or are both typedefs of the same type.
4298static bool
4299IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4300 bool &SuppressRedeclaration) {
4301 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4302 SuppressRedeclaration = false;
4303 return true;
4304 }
4305
Richard Smithdda56e42011-04-15 14:24:37 +00004306 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4307 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004308 SuppressRedeclaration = true;
4309 return Context.hasSameType(TD1->getUnderlyingType(),
4310 TD2->getUnderlyingType());
4311 }
4312
4313 return false;
4314}
4315
4316
John McCall84d87672009-12-10 09:41:52 +00004317/// Determines whether to create a using shadow decl for a particular
4318/// decl, given the set of decls existing prior to this using lookup.
4319bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4320 const LookupResult &Previous) {
4321 // Diagnose finding a decl which is not from a base class of the
4322 // current class. We do this now because there are cases where this
4323 // function will silently decide not to build a shadow decl, which
4324 // will pre-empt further diagnostics.
4325 //
4326 // We don't need to do this in C++0x because we do the check once on
4327 // the qualifier.
4328 //
4329 // FIXME: diagnose the following if we care enough:
4330 // struct A { int foo; };
4331 // struct B : A { using A::foo; };
4332 // template <class T> struct C : A {};
4333 // template <class T> struct D : C<T> { using B::foo; } // <---
4334 // This is invalid (during instantiation) in C++03 because B::foo
4335 // resolves to the using decl in B, which is not a base class of D<T>.
4336 // We can't diagnose it immediately because C<T> is an unknown
4337 // specialization. The UsingShadowDecl in D<T> then points directly
4338 // to A::foo, which will look well-formed when we instantiate.
4339 // The right solution is to not collapse the shadow-decl chain.
4340 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4341 DeclContext *OrigDC = Orig->getDeclContext();
4342
4343 // Handle enums and anonymous structs.
4344 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4345 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4346 while (OrigRec->isAnonymousStructOrUnion())
4347 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4348
4349 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4350 if (OrigDC == CurContext) {
4351 Diag(Using->getLocation(),
4352 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004353 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004354 Diag(Orig->getLocation(), diag::note_using_decl_target);
4355 return true;
4356 }
4357
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004358 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00004359 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004360 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00004361 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004362 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004363 Diag(Orig->getLocation(), diag::note_using_decl_target);
4364 return true;
4365 }
4366 }
4367
4368 if (Previous.empty()) return false;
4369
4370 NamedDecl *Target = Orig;
4371 if (isa<UsingShadowDecl>(Target))
4372 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4373
John McCalla17e83e2009-12-11 02:33:26 +00004374 // If the target happens to be one of the previous declarations, we
4375 // don't have a conflict.
4376 //
4377 // FIXME: but we might be increasing its access, in which case we
4378 // should redeclare it.
4379 NamedDecl *NonTag = 0, *Tag = 0;
4380 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4381 I != E; ++I) {
4382 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004383 bool Result;
4384 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4385 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00004386
4387 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4388 }
4389
John McCall84d87672009-12-10 09:41:52 +00004390 if (Target->isFunctionOrFunctionTemplate()) {
4391 FunctionDecl *FD;
4392 if (isa<FunctionTemplateDecl>(Target))
4393 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4394 else
4395 FD = cast<FunctionDecl>(Target);
4396
4397 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00004398 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00004399 case Ovl_Overload:
4400 return false;
4401
4402 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00004403 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004404 break;
4405
4406 // We found a decl with the exact signature.
4407 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004408 // If we're in a record, we want to hide the target, so we
4409 // return true (without a diagnostic) to tell the caller not to
4410 // build a shadow decl.
4411 if (CurContext->isRecord())
4412 return true;
4413
4414 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00004415 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004416 break;
4417 }
4418
4419 Diag(Target->getLocation(), diag::note_using_decl_target);
4420 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4421 return true;
4422 }
4423
4424 // Target is not a function.
4425
John McCall84d87672009-12-10 09:41:52 +00004426 if (isa<TagDecl>(Target)) {
4427 // No conflict between a tag and a non-tag.
4428 if (!Tag) return false;
4429
John McCalle29c5cd2009-12-10 19:51:03 +00004430 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004431 Diag(Target->getLocation(), diag::note_using_decl_target);
4432 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4433 return true;
4434 }
4435
4436 // No conflict between a tag and a non-tag.
4437 if (!NonTag) return false;
4438
John McCalle29c5cd2009-12-10 19:51:03 +00004439 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004440 Diag(Target->getLocation(), diag::note_using_decl_target);
4441 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4442 return true;
4443}
4444
John McCall3f746822009-11-17 05:59:44 +00004445/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004446UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004447 UsingDecl *UD,
4448 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004449
4450 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004451 NamedDecl *Target = Orig;
4452 if (isa<UsingShadowDecl>(Target)) {
4453 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4454 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004455 }
4456
4457 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004458 = UsingShadowDecl::Create(Context, CurContext,
4459 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004460 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004461
4462 Shadow->setAccess(UD->getAccess());
4463 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4464 Shadow->setInvalidDecl();
4465
John McCall3f746822009-11-17 05:59:44 +00004466 if (S)
John McCall3969e302009-12-08 07:46:18 +00004467 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004468 else
John McCall3969e302009-12-08 07:46:18 +00004469 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004470
John McCall3969e302009-12-08 07:46:18 +00004471
John McCall84d87672009-12-10 09:41:52 +00004472 return Shadow;
4473}
John McCall3969e302009-12-08 07:46:18 +00004474
John McCall84d87672009-12-10 09:41:52 +00004475/// Hides a using shadow declaration. This is required by the current
4476/// using-decl implementation when a resolvable using declaration in a
4477/// class is followed by a declaration which would hide or override
4478/// one or more of the using decl's targets; for example:
4479///
4480/// struct Base { void foo(int); };
4481/// struct Derived : Base {
4482/// using Base::foo;
4483/// void foo(int);
4484/// };
4485///
4486/// The governing language is C++03 [namespace.udecl]p12:
4487///
4488/// When a using-declaration brings names from a base class into a
4489/// derived class scope, member functions in the derived class
4490/// override and/or hide member functions with the same name and
4491/// parameter types in a base class (rather than conflicting).
4492///
4493/// There are two ways to implement this:
4494/// (1) optimistically create shadow decls when they're not hidden
4495/// by existing declarations, or
4496/// (2) don't create any shadow decls (or at least don't make them
4497/// visible) until we've fully parsed/instantiated the class.
4498/// The problem with (1) is that we might have to retroactively remove
4499/// a shadow decl, which requires several O(n) operations because the
4500/// decl structures are (very reasonably) not designed for removal.
4501/// (2) avoids this but is very fiddly and phase-dependent.
4502void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004503 if (Shadow->getDeclName().getNameKind() ==
4504 DeclarationName::CXXConversionFunctionName)
4505 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4506
John McCall84d87672009-12-10 09:41:52 +00004507 // Remove it from the DeclContext...
4508 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004509
John McCall84d87672009-12-10 09:41:52 +00004510 // ...and the scope, if applicable...
4511 if (S) {
John McCall48871652010-08-21 09:40:31 +00004512 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004513 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004514 }
4515
John McCall84d87672009-12-10 09:41:52 +00004516 // ...and the using decl.
4517 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4518
4519 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004520 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004521}
4522
John McCalle61f2ba2009-11-18 02:36:19 +00004523/// Builds a using declaration.
4524///
4525/// \param IsInstantiation - Whether this call arises from an
4526/// instantiation of an unresolved using declaration. We treat
4527/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004528NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4529 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004530 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004531 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004532 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004533 bool IsInstantiation,
4534 bool IsTypeName,
4535 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004536 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004537 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004538 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004539
Anders Carlssonf038fc22009-08-28 05:49:21 +00004540 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004541
Anders Carlsson59140b32009-08-28 03:16:11 +00004542 if (SS.isEmpty()) {
4543 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004544 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004545 }
Mike Stump11289f42009-09-09 15:08:12 +00004546
John McCall84d87672009-12-10 09:41:52 +00004547 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004548 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004549 ForRedeclaration);
4550 Previous.setHideTags(false);
4551 if (S) {
4552 LookupName(Previous, S);
4553
4554 // It is really dumb that we have to do this.
4555 LookupResult::Filter F = Previous.makeFilter();
4556 while (F.hasNext()) {
4557 NamedDecl *D = F.next();
4558 if (!isDeclInScope(D, CurContext, S))
4559 F.erase();
4560 }
4561 F.done();
4562 } else {
4563 assert(IsInstantiation && "no scope in non-instantiation");
4564 assert(CurContext->isRecord() && "scope not record in instantiation");
4565 LookupQualifiedName(Previous, CurContext);
4566 }
4567
John McCall84d87672009-12-10 09:41:52 +00004568 // Check for invalid redeclarations.
4569 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4570 return 0;
4571
4572 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004573 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4574 return 0;
4575
John McCall84c16cf2009-11-12 03:15:40 +00004576 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004577 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004578 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00004579 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004580 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004581 // FIXME: not all declaration name kinds are legal here
4582 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4583 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004584 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004585 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004586 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004587 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4588 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004589 }
John McCallb96ec562009-12-04 22:46:56 +00004590 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004591 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4592 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004593 }
John McCallb96ec562009-12-04 22:46:56 +00004594 D->setAccess(AS);
4595 CurContext->addDecl(D);
4596
4597 if (!LookupContext) return D;
4598 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004599
John McCall0b66eb32010-05-01 00:40:08 +00004600 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004601 UD->setInvalidDecl();
4602 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004603 }
4604
Sebastian Redl08905022011-02-05 19:23:19 +00004605 // Constructor inheriting using decls get special treatment.
4606 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00004607 if (CheckInheritedConstructorUsingDecl(UD))
4608 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00004609 return UD;
4610 }
4611
4612 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00004613
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004614 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004615
John McCall3969e302009-12-08 07:46:18 +00004616 // Unlike most lookups, we don't always want to hide tag
4617 // declarations: tag names are visible through the using declaration
4618 // even if hidden by ordinary names, *except* in a dependent context
4619 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004620 if (!IsInstantiation)
4621 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004622
John McCall27b18f82009-11-17 02:14:36 +00004623 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004624
John McCall9f3059a2009-10-09 21:13:30 +00004625 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004626 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004627 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004628 UD->setInvalidDecl();
4629 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004630 }
4631
John McCallb96ec562009-12-04 22:46:56 +00004632 if (R.isAmbiguous()) {
4633 UD->setInvalidDecl();
4634 return UD;
4635 }
Mike Stump11289f42009-09-09 15:08:12 +00004636
John McCalle61f2ba2009-11-18 02:36:19 +00004637 if (IsTypeName) {
4638 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004639 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004640 Diag(IdentLoc, diag::err_using_typename_non_type);
4641 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4642 Diag((*I)->getUnderlyingDecl()->getLocation(),
4643 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004644 UD->setInvalidDecl();
4645 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004646 }
4647 } else {
4648 // If we asked for a non-typename and we got a type, error out,
4649 // but only if this is an instantiation of an unresolved using
4650 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004651 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004652 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4653 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004654 UD->setInvalidDecl();
4655 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004656 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004657 }
4658
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004659 // C++0x N2914 [namespace.udecl]p6:
4660 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004661 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004662 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4663 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004664 UD->setInvalidDecl();
4665 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004666 }
Mike Stump11289f42009-09-09 15:08:12 +00004667
John McCall84d87672009-12-10 09:41:52 +00004668 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4669 if (!CheckUsingShadowDecl(UD, *I, Previous))
4670 BuildUsingShadowDecl(S, UD, *I);
4671 }
John McCall3f746822009-11-17 05:59:44 +00004672
4673 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004674}
4675
Sebastian Redl08905022011-02-05 19:23:19 +00004676/// Additional checks for a using declaration referring to a constructor name.
4677bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4678 if (UD->isTypeName()) {
4679 // FIXME: Cannot specify typename when specifying constructor
4680 return true;
4681 }
4682
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004683 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00004684 assert(SourceType &&
4685 "Using decl naming constructor doesn't have type in scope spec.");
4686 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4687
4688 // Check whether the named type is a direct base class.
4689 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4690 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4691 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4692 BaseIt != BaseE; ++BaseIt) {
4693 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4694 if (CanonicalSourceType == BaseType)
4695 break;
4696 }
4697
4698 if (BaseIt == BaseE) {
4699 // Did not find SourceType in the bases.
4700 Diag(UD->getUsingLocation(),
4701 diag::err_using_decl_constructor_not_in_direct_base)
4702 << UD->getNameInfo().getSourceRange()
4703 << QualType(SourceType, 0) << TargetClass;
4704 return true;
4705 }
4706
4707 BaseIt->setInheritConstructors();
4708
4709 return false;
4710}
4711
John McCall84d87672009-12-10 09:41:52 +00004712/// Checks that the given using declaration is not an invalid
4713/// redeclaration. Note that this is checking only for the using decl
4714/// itself, not for any ill-formedness among the UsingShadowDecls.
4715bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4716 bool isTypeName,
4717 const CXXScopeSpec &SS,
4718 SourceLocation NameLoc,
4719 const LookupResult &Prev) {
4720 // C++03 [namespace.udecl]p8:
4721 // C++0x [namespace.udecl]p10:
4722 // A using-declaration is a declaration and can therefore be used
4723 // repeatedly where (and only where) multiple declarations are
4724 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004725 //
John McCall032092f2010-11-29 18:01:58 +00004726 // That's in non-member contexts.
4727 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004728 return false;
4729
4730 NestedNameSpecifier *Qual
4731 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4732
4733 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4734 NamedDecl *D = *I;
4735
4736 bool DTypename;
4737 NestedNameSpecifier *DQual;
4738 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4739 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004740 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004741 } else if (UnresolvedUsingValueDecl *UD
4742 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4743 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004744 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004745 } else if (UnresolvedUsingTypenameDecl *UD
4746 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4747 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004748 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004749 } else continue;
4750
4751 // using decls differ if one says 'typename' and the other doesn't.
4752 // FIXME: non-dependent using decls?
4753 if (isTypeName != DTypename) continue;
4754
4755 // using decls differ if they name different scopes (but note that
4756 // template instantiation can cause this check to trigger when it
4757 // didn't before instantiation).
4758 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4759 Context.getCanonicalNestedNameSpecifier(DQual))
4760 continue;
4761
4762 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004763 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004764 return true;
4765 }
4766
4767 return false;
4768}
4769
John McCall3969e302009-12-08 07:46:18 +00004770
John McCallb96ec562009-12-04 22:46:56 +00004771/// Checks that the given nested-name qualifier used in a using decl
4772/// in the current context is appropriately related to the current
4773/// scope. If an error is found, diagnoses it and returns true.
4774bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4775 const CXXScopeSpec &SS,
4776 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004777 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004778
John McCall3969e302009-12-08 07:46:18 +00004779 if (!CurContext->isRecord()) {
4780 // C++03 [namespace.udecl]p3:
4781 // C++0x [namespace.udecl]p8:
4782 // A using-declaration for a class member shall be a member-declaration.
4783
4784 // If we weren't able to compute a valid scope, it must be a
4785 // dependent class scope.
4786 if (!NamedContext || NamedContext->isRecord()) {
4787 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4788 << SS.getRange();
4789 return true;
4790 }
4791
4792 // Otherwise, everything is known to be fine.
4793 return false;
4794 }
4795
4796 // The current scope is a record.
4797
4798 // If the named context is dependent, we can't decide much.
4799 if (!NamedContext) {
4800 // FIXME: in C++0x, we can diagnose if we can prove that the
4801 // nested-name-specifier does not refer to a base class, which is
4802 // still possible in some cases.
4803
4804 // Otherwise we have to conservatively report that things might be
4805 // okay.
4806 return false;
4807 }
4808
4809 if (!NamedContext->isRecord()) {
4810 // Ideally this would point at the last name in the specifier,
4811 // but we don't have that level of source info.
4812 Diag(SS.getRange().getBegin(),
4813 diag::err_using_decl_nested_name_specifier_is_not_class)
4814 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4815 return true;
4816 }
4817
Douglas Gregor7c842292010-12-21 07:41:49 +00004818 if (!NamedContext->isDependentContext() &&
4819 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4820 return true;
4821
John McCall3969e302009-12-08 07:46:18 +00004822 if (getLangOptions().CPlusPlus0x) {
4823 // C++0x [namespace.udecl]p3:
4824 // In a using-declaration used as a member-declaration, the
4825 // nested-name-specifier shall name a base class of the class
4826 // being defined.
4827
4828 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4829 cast<CXXRecordDecl>(NamedContext))) {
4830 if (CurContext == NamedContext) {
4831 Diag(NameLoc,
4832 diag::err_using_decl_nested_name_specifier_is_current_class)
4833 << SS.getRange();
4834 return true;
4835 }
4836
4837 Diag(SS.getRange().getBegin(),
4838 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4839 << (NestedNameSpecifier*) SS.getScopeRep()
4840 << cast<CXXRecordDecl>(CurContext)
4841 << SS.getRange();
4842 return true;
4843 }
4844
4845 return false;
4846 }
4847
4848 // C++03 [namespace.udecl]p4:
4849 // A using-declaration used as a member-declaration shall refer
4850 // to a member of a base class of the class being defined [etc.].
4851
4852 // Salient point: SS doesn't have to name a base class as long as
4853 // lookup only finds members from base classes. Therefore we can
4854 // diagnose here only if we can prove that that can't happen,
4855 // i.e. if the class hierarchies provably don't intersect.
4856
4857 // TODO: it would be nice if "definitely valid" results were cached
4858 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4859 // need to be repeated.
4860
4861 struct UserData {
4862 llvm::DenseSet<const CXXRecordDecl*> Bases;
4863
4864 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4865 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4866 Data->Bases.insert(Base);
4867 return true;
4868 }
4869
4870 bool hasDependentBases(const CXXRecordDecl *Class) {
4871 return !Class->forallBases(collect, this);
4872 }
4873
4874 /// Returns true if the base is dependent or is one of the
4875 /// accumulated base classes.
4876 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4877 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4878 return !Data->Bases.count(Base);
4879 }
4880
4881 bool mightShareBases(const CXXRecordDecl *Class) {
4882 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4883 }
4884 };
4885
4886 UserData Data;
4887
4888 // Returns false if we find a dependent base.
4889 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4890 return false;
4891
4892 // Returns false if the class has a dependent base or if it or one
4893 // of its bases is present in the base set of the current context.
4894 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4895 return false;
4896
4897 Diag(SS.getRange().getBegin(),
4898 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4899 << (NestedNameSpecifier*) SS.getScopeRep()
4900 << cast<CXXRecordDecl>(CurContext)
4901 << SS.getRange();
4902
4903 return true;
John McCallb96ec562009-12-04 22:46:56 +00004904}
4905
Richard Smithdda56e42011-04-15 14:24:37 +00004906Decl *Sema::ActOnAliasDeclaration(Scope *S,
4907 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004908 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00004909 SourceLocation UsingLoc,
4910 UnqualifiedId &Name,
4911 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00004912 // Skip up to the relevant declaration scope.
4913 while (S->getFlags() & Scope::TemplateParamScope)
4914 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00004915 assert((S->getFlags() & Scope::DeclScope) &&
4916 "got alias-declaration outside of declaration scope");
4917
4918 if (Type.isInvalid())
4919 return 0;
4920
4921 bool Invalid = false;
4922 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4923 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00004924 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004925
4926 if (DiagnoseClassNameShadow(CurContext, NameInfo))
4927 return 0;
4928
4929 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004930 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00004931 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00004932 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
4933 TInfo->getTypeLoc().getBeginLoc());
4934 }
Richard Smithdda56e42011-04-15 14:24:37 +00004935
4936 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4937 LookupName(Previous, S);
4938
4939 // Warn about shadowing the name of a template parameter.
4940 if (Previous.isSingleResult() &&
4941 Previous.getFoundDecl()->isTemplateParameter()) {
4942 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4943 Previous.getFoundDecl()))
4944 Invalid = true;
4945 Previous.clear();
4946 }
4947
4948 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4949 "name in alias declaration must be an identifier");
4950 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4951 Name.StartLocation,
4952 Name.Identifier, TInfo);
4953
4954 NewTD->setAccess(AS);
4955
4956 if (Invalid)
4957 NewTD->setInvalidDecl();
4958
Richard Smith3f1b5d02011-05-05 21:57:07 +00004959 CheckTypedefForVariablyModifiedType(S, NewTD);
4960 Invalid |= NewTD->isInvalidDecl();
4961
Richard Smithdda56e42011-04-15 14:24:37 +00004962 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00004963
4964 NamedDecl *NewND;
4965 if (TemplateParamLists.size()) {
4966 TypeAliasTemplateDecl *OldDecl = 0;
4967 TemplateParameterList *OldTemplateParams = 0;
4968
4969 if (TemplateParamLists.size() != 1) {
4970 Diag(UsingLoc, diag::err_alias_template_extra_headers)
4971 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
4972 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
4973 }
4974 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
4975
4976 // Only consider previous declarations in the same scope.
4977 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
4978 /*ExplicitInstantiationOrSpecialization*/false);
4979 if (!Previous.empty()) {
4980 Redeclaration = true;
4981
4982 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
4983 if (!OldDecl && !Invalid) {
4984 Diag(UsingLoc, diag::err_redefinition_different_kind)
4985 << Name.Identifier;
4986
4987 NamedDecl *OldD = Previous.getRepresentativeDecl();
4988 if (OldD->getLocation().isValid())
4989 Diag(OldD->getLocation(), diag::note_previous_definition);
4990
4991 Invalid = true;
4992 }
4993
4994 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
4995 if (TemplateParameterListsAreEqual(TemplateParams,
4996 OldDecl->getTemplateParameters(),
4997 /*Complain=*/true,
4998 TPL_TemplateMatch))
4999 OldTemplateParams = OldDecl->getTemplateParameters();
5000 else
5001 Invalid = true;
5002
5003 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5004 if (!Invalid &&
5005 !Context.hasSameType(OldTD->getUnderlyingType(),
5006 NewTD->getUnderlyingType())) {
5007 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5008 // but we can't reasonably accept it.
5009 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5010 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5011 if (OldTD->getLocation().isValid())
5012 Diag(OldTD->getLocation(), diag::note_previous_definition);
5013 Invalid = true;
5014 }
5015 }
5016 }
5017
5018 // Merge any previous default template arguments into our parameters,
5019 // and check the parameter list.
5020 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5021 TPC_TypeAliasTemplate))
5022 return 0;
5023
5024 TypeAliasTemplateDecl *NewDecl =
5025 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5026 Name.Identifier, TemplateParams,
5027 NewTD);
5028
5029 NewDecl->setAccess(AS);
5030
5031 if (Invalid)
5032 NewDecl->setInvalidDecl();
5033 else if (OldDecl)
5034 NewDecl->setPreviousDeclaration(OldDecl);
5035
5036 NewND = NewDecl;
5037 } else {
5038 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5039 NewND = NewTD;
5040 }
Richard Smithdda56e42011-04-15 14:24:37 +00005041
5042 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00005043 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00005044
Richard Smith3f1b5d02011-05-05 21:57:07 +00005045 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00005046}
5047
John McCall48871652010-08-21 09:40:31 +00005048Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005049 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005050 SourceLocation AliasLoc,
5051 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005052 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005053 SourceLocation IdentLoc,
5054 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00005055
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005056 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005057 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5058 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005059
Anders Carlssondca83c42009-03-28 06:23:46 +00005060 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00005061 NamedDecl *PrevDecl
5062 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5063 ForRedeclaration);
5064 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5065 PrevDecl = 0;
5066
5067 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005068 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00005069 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005070 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00005071 // FIXME: At some point, we'll want to create the (redundant)
5072 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00005073 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00005074 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00005075 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005076 }
Mike Stump11289f42009-09-09 15:08:12 +00005077
Anders Carlssondca83c42009-03-28 06:23:46 +00005078 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5079 diag::err_redefinition_different_kind;
5080 Diag(AliasLoc, DiagID) << Alias;
5081 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00005082 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00005083 }
5084
John McCall27b18f82009-11-17 02:14:36 +00005085 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005086 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005087
John McCall9f3059a2009-10-09 21:13:30 +00005088 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005089 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5090 CTC_NoKeywords, 0)) {
5091 if (R.getAsSingle<NamespaceDecl>() ||
5092 R.getAsSingle<NamespaceAliasDecl>()) {
5093 if (DeclContext *DC = computeDeclContext(SS, false))
5094 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5095 << Ident << DC << Corrected << SS.getRange()
5096 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5097 else
5098 Diag(IdentLoc, diag::err_using_directive_suggest)
5099 << Ident << Corrected
5100 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5101
5102 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5103 << Corrected;
5104
5105 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00005106 } else {
5107 R.clear();
5108 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005109 }
5110 }
5111
5112 if (R.empty()) {
5113 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005114 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005115 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00005116 }
Mike Stump11289f42009-09-09 15:08:12 +00005117
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005118 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00005119 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00005120 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00005121 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00005122
John McCalld8d0d432010-02-16 06:53:13 +00005123 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00005124 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00005125}
5126
Douglas Gregora57478e2010-05-01 15:04:51 +00005127namespace {
5128 /// \brief Scoped object used to handle the state changes required in Sema
5129 /// to implicitly define the body of a C++ member function;
5130 class ImplicitlyDefinedFunctionScope {
5131 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00005132 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00005133
5134 public:
5135 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00005136 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00005137 {
Douglas Gregora57478e2010-05-01 15:04:51 +00005138 S.PushFunctionScope();
5139 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5140 }
5141
5142 ~ImplicitlyDefinedFunctionScope() {
5143 S.PopExpressionEvaluationContext();
5144 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00005145 }
5146 };
5147}
5148
Sebastian Redlc15c3262010-09-13 22:02:47 +00005149static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
5150 CXXRecordDecl *D) {
5151 ASTContext &Context = Self.Context;
5152 QualType ClassType = Context.getTypeDeclType(D);
5153 DeclarationName ConstructorName
5154 = Context.DeclarationNames.getCXXConstructorName(
5155 Context.getCanonicalType(ClassType.getUnqualifiedType()));
5156
5157 DeclContext::lookup_const_iterator Con, ConEnd;
5158 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
5159 Con != ConEnd; ++Con) {
5160 // FIXME: In C++0x, a constructor template can be a default constructor.
5161 if (isa<FunctionTemplateDecl>(*Con))
5162 continue;
5163
5164 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
5165 if (Constructor->isDefaultConstructor())
5166 return Constructor;
5167 }
5168 return 0;
5169}
5170
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005171Sema::ImplicitExceptionSpecification
5172Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00005173 // C++ [except.spec]p14:
5174 // An implicitly declared special member function (Clause 12) shall have an
5175 // exception-specification. [...]
5176 ImplicitExceptionSpecification ExceptSpec(Context);
5177
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005178 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005179 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5180 BEnd = ClassDecl->bases_end();
5181 B != BEnd; ++B) {
5182 if (B->isVirtual()) // Handled below.
5183 continue;
5184
Douglas Gregor9672f922010-07-03 00:47:00 +00005185 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5186 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Huntea6f0322011-05-11 22:34:38 +00005187 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005188 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00005189 else if (CXXConstructorDecl *Constructor
5190 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005191 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005192 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005193 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005194
5195 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005196 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5197 BEnd = ClassDecl->vbases_end();
5198 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00005199 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5200 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Huntea6f0322011-05-11 22:34:38 +00005201 if (BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005202 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5203 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00005204 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005205 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005206 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005207 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005208
5209 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005210 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5211 FEnd = ClassDecl->field_end();
5212 F != FEnd; ++F) {
5213 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00005214 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5215 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Alexis Huntea6f0322011-05-11 22:34:38 +00005216 if (FieldClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005217 ExceptSpec.CalledDecl(
5218 DeclareImplicitDefaultConstructor(FieldClassDecl));
5219 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00005220 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005221 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005222 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005223 }
John McCalldb40c7f2010-12-14 08:05:40 +00005224
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005225 return ExceptSpec;
5226}
5227
5228CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5229 CXXRecordDecl *ClassDecl) {
5230 // C++ [class.ctor]p5:
5231 // A default constructor for a class X is a constructor of class X
5232 // that can be called without an argument. If there is no
5233 // user-declared constructor for class X, a default constructor is
5234 // implicitly declared. An implicitly-declared default constructor
5235 // is an inline public member of its class.
5236 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5237 "Should not build implicit default constructor!");
5238
5239 ImplicitExceptionSpecification Spec =
5240 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5241 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005242
Douglas Gregor6d880b12010-07-01 22:31:05 +00005243 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005244 CanQualType ClassType
5245 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005246 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005247 DeclarationName Name
5248 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005249 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005250 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00005251 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005252 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005253 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005254 /*TInfo=*/0,
5255 /*isExplicit=*/false,
5256 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005257 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005258 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00005259 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005260 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00005261 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00005262
5263 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00005264 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Alexis Huntea6f0322011-05-11 22:34:38 +00005265
5266 // Do not delete this yet if we're in a template
5267 if (!ClassDecl->isDependentType() &&
5268 ShouldDeleteDefaultConstructor(DefaultCon))
5269 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00005270
Douglas Gregor0be31a22010-07-02 17:43:08 +00005271 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00005272 PushOnScopeChains(DefaultCon, S, false);
5273 ClassDecl->addDecl(DefaultCon);
5274
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005275 return DefaultCon;
5276}
5277
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005278void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5279 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00005280 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00005281 !Constructor->isUsed(false) && !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00005282 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005283
Anders Carlsson423f5d82010-04-23 16:04:08 +00005284 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00005285 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00005286
Douglas Gregora57478e2010-05-01 15:04:51 +00005287 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005288 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00005289 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005290 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005291 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00005292 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00005293 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00005294 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00005295 }
Douglas Gregor73193272010-09-20 16:48:21 +00005296
5297 SourceLocation Loc = Constructor->getLocation();
5298 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5299
5300 Constructor->setUsed();
5301 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00005302
5303 if (ASTMutationListener *L = getASTMutationListener()) {
5304 L->CompletedImplicitDefinition(Constructor);
5305 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005306}
5307
Sebastian Redl08905022011-02-05 19:23:19 +00005308void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
5309 // We start with an initial pass over the base classes to collect those that
5310 // inherit constructors from. If there are none, we can forgo all further
5311 // processing.
5312 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
5313 BasesVector BasesToInheritFrom;
5314 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
5315 BaseE = ClassDecl->bases_end();
5316 BaseIt != BaseE; ++BaseIt) {
5317 if (BaseIt->getInheritConstructors()) {
5318 QualType Base = BaseIt->getType();
5319 if (Base->isDependentType()) {
5320 // If we inherit constructors from anything that is dependent, just
5321 // abort processing altogether. We'll get another chance for the
5322 // instantiations.
5323 return;
5324 }
5325 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
5326 }
5327 }
5328 if (BasesToInheritFrom.empty())
5329 return;
5330
5331 // Now collect the constructors that we already have in the current class.
5332 // Those take precedence over inherited constructors.
5333 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5334 // unless there is a user-declared constructor with the same signature in
5335 // the class where the using-declaration appears.
5336 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5337 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5338 CtorE = ClassDecl->ctor_end();
5339 CtorIt != CtorE; ++CtorIt) {
5340 ExistingConstructors.insert(
5341 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5342 }
5343
5344 Scope *S = getScopeForContext(ClassDecl);
5345 DeclarationName CreatedCtorName =
5346 Context.DeclarationNames.getCXXConstructorName(
5347 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5348
5349 // Now comes the true work.
5350 // First, we keep a map from constructor types to the base that introduced
5351 // them. Needed for finding conflicting constructors. We also keep the
5352 // actually inserted declarations in there, for pretty diagnostics.
5353 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5354 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5355 ConstructorToSourceMap InheritedConstructors;
5356 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5357 BaseE = BasesToInheritFrom.end();
5358 BaseIt != BaseE; ++BaseIt) {
5359 const RecordType *Base = *BaseIt;
5360 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5361 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5362 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5363 CtorE = BaseDecl->ctor_end();
5364 CtorIt != CtorE; ++CtorIt) {
5365 // Find the using declaration for inheriting this base's constructors.
5366 DeclarationName Name =
5367 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5368 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5369 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5370 SourceLocation UsingLoc = UD ? UD->getLocation() :
5371 ClassDecl->getLocation();
5372
5373 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5374 // from the class X named in the using-declaration consists of actual
5375 // constructors and notional constructors that result from the
5376 // transformation of defaulted parameters as follows:
5377 // - all non-template default constructors of X, and
5378 // - for each non-template constructor of X that has at least one
5379 // parameter with a default argument, the set of constructors that
5380 // results from omitting any ellipsis parameter specification and
5381 // successively omitting parameters with a default argument from the
5382 // end of the parameter-type-list.
5383 CXXConstructorDecl *BaseCtor = *CtorIt;
5384 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5385 const FunctionProtoType *BaseCtorType =
5386 BaseCtor->getType()->getAs<FunctionProtoType>();
5387
5388 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5389 maxParams = BaseCtor->getNumParams();
5390 params <= maxParams; ++params) {
5391 // Skip default constructors. They're never inherited.
5392 if (params == 0)
5393 continue;
5394 // Skip copy and move constructors for the same reason.
5395 if (CanBeCopyOrMove && params == 1)
5396 continue;
5397
5398 // Build up a function type for this particular constructor.
5399 // FIXME: The working paper does not consider that the exception spec
5400 // for the inheriting constructor might be larger than that of the
5401 // source. This code doesn't yet, either.
5402 const Type *NewCtorType;
5403 if (params == maxParams)
5404 NewCtorType = BaseCtorType;
5405 else {
5406 llvm::SmallVector<QualType, 16> Args;
5407 for (unsigned i = 0; i < params; ++i) {
5408 Args.push_back(BaseCtorType->getArgType(i));
5409 }
5410 FunctionProtoType::ExtProtoInfo ExtInfo =
5411 BaseCtorType->getExtProtoInfo();
5412 ExtInfo.Variadic = false;
5413 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5414 Args.data(), params, ExtInfo)
5415 .getTypePtr();
5416 }
5417 const Type *CanonicalNewCtorType =
5418 Context.getCanonicalType(NewCtorType);
5419
5420 // Now that we have the type, first check if the class already has a
5421 // constructor with this signature.
5422 if (ExistingConstructors.count(CanonicalNewCtorType))
5423 continue;
5424
5425 // Then we check if we have already declared an inherited constructor
5426 // with this signature.
5427 std::pair<ConstructorToSourceMap::iterator, bool> result =
5428 InheritedConstructors.insert(std::make_pair(
5429 CanonicalNewCtorType,
5430 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5431 if (!result.second) {
5432 // Already in the map. If it came from a different class, that's an
5433 // error. Not if it's from the same.
5434 CanQualType PreviousBase = result.first->second.first;
5435 if (CanonicalBase != PreviousBase) {
5436 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5437 const CXXConstructorDecl *PrevBaseCtor =
5438 PrevCtor->getInheritedConstructor();
5439 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5440
5441 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5442 Diag(BaseCtor->getLocation(),
5443 diag::note_using_decl_constructor_conflict_current_ctor);
5444 Diag(PrevBaseCtor->getLocation(),
5445 diag::note_using_decl_constructor_conflict_previous_ctor);
5446 Diag(PrevCtor->getLocation(),
5447 diag::note_using_decl_constructor_conflict_previous_using);
5448 }
5449 continue;
5450 }
5451
5452 // OK, we're there, now add the constructor.
5453 // C++0x [class.inhctor]p8: [...] that would be performed by a
5454 // user-writtern inline constructor [...]
5455 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5456 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00005457 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5458 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005459 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00005460 NewCtor->setAccess(BaseCtor->getAccess());
5461
5462 // Build up the parameter decls and add them.
5463 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5464 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005465 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5466 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00005467 /*IdentifierInfo=*/0,
5468 BaseCtorType->getArgType(i),
5469 /*TInfo=*/0, SC_None,
5470 SC_None, /*DefaultArg=*/0));
5471 }
5472 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5473 NewCtor->setInheritedConstructor(BaseCtor);
5474
5475 PushOnScopeChains(NewCtor, S, false);
5476 ClassDecl->addDecl(NewCtor);
5477 result.first->second.second = NewCtor;
5478 }
5479 }
5480 }
5481}
5482
Douglas Gregor0be31a22010-07-02 17:43:08 +00005483CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00005484 // C++ [class.dtor]p2:
5485 // If a class has no user-declared destructor, a destructor is
5486 // declared implicitly. An implicitly-declared destructor is an
5487 // inline public member of its class.
5488
5489 // C++ [except.spec]p14:
5490 // An implicitly declared special member function (Clause 12) shall have
5491 // an exception-specification.
5492 ImplicitExceptionSpecification ExceptSpec(Context);
5493
5494 // Direct base-class destructors.
5495 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5496 BEnd = ClassDecl->bases_end();
5497 B != BEnd; ++B) {
5498 if (B->isVirtual()) // Handled below.
5499 continue;
5500
5501 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5502 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005503 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005504 }
5505
5506 // Virtual base-class destructors.
5507 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5508 BEnd = ClassDecl->vbases_end();
5509 B != BEnd; ++B) {
5510 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5511 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005512 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005513 }
5514
5515 // Field destructors.
5516 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5517 FEnd = ClassDecl->field_end();
5518 F != FEnd; ++F) {
5519 if (const RecordType *RecordTy
5520 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5521 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005522 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005523 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005524
Douglas Gregor7454c562010-07-02 20:37:36 +00005525 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00005526 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005527 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005528 EPI.NumExceptions = ExceptSpec.size();
5529 EPI.Exceptions = ExceptSpec.data();
5530 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005531
Douglas Gregorf1203042010-07-01 19:09:28 +00005532 CanQualType ClassType
5533 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005534 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00005535 DeclarationName Name
5536 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005537 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00005538 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005539 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5540 /*isInline=*/true,
5541 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00005542 Destructor->setAccess(AS_public);
5543 Destructor->setImplicit();
5544 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00005545
5546 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00005547 ++ASTContext::NumImplicitDestructorsDeclared;
5548
5549 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005550 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00005551 PushOnScopeChains(Destructor, S, false);
5552 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00005553
5554 // This could be uniqued if it ever proves significant.
5555 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5556
5557 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00005558
Douglas Gregorf1203042010-07-01 19:09:28 +00005559 return Destructor;
5560}
5561
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005562void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00005563 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00005564 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005565 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00005566 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005567 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005568
Douglas Gregor54818f02010-05-12 16:39:35 +00005569 if (Destructor->isInvalidDecl())
5570 return;
5571
Douglas Gregora57478e2010-05-01 15:04:51 +00005572 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005573
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005574 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00005575 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5576 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00005577
Douglas Gregor54818f02010-05-12 16:39:35 +00005578 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005579 Diag(CurrentLocation, diag::note_member_synthesized_at)
5580 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5581
5582 Destructor->setInvalidDecl();
5583 return;
5584 }
5585
Douglas Gregor73193272010-09-20 16:48:21 +00005586 SourceLocation Loc = Destructor->getLocation();
5587 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5588
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005589 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00005590 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00005591
5592 if (ASTMutationListener *L = getASTMutationListener()) {
5593 L->CompletedImplicitDefinition(Destructor);
5594 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005595}
5596
Douglas Gregorb139cd52010-05-01 20:49:11 +00005597/// \brief Builds a statement that copies the given entity from \p From to
5598/// \c To.
5599///
5600/// This routine is used to copy the members of a class with an
5601/// implicitly-declared copy assignment operator. When the entities being
5602/// copied are arrays, this routine builds for loops to copy them.
5603///
5604/// \param S The Sema object used for type-checking.
5605///
5606/// \param Loc The location where the implicit copy is being generated.
5607///
5608/// \param T The type of the expressions being copied. Both expressions must
5609/// have this type.
5610///
5611/// \param To The expression we are copying to.
5612///
5613/// \param From The expression we are copying from.
5614///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005615/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5616/// Otherwise, it's a non-static member subobject.
5617///
Douglas Gregorb139cd52010-05-01 20:49:11 +00005618/// \param Depth Internal parameter recording the depth of the recursion.
5619///
5620/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00005621static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00005622BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00005623 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005624 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005625 // C++0x [class.copy]p30:
5626 // Each subobject is assigned in the manner appropriate to its type:
5627 //
5628 // - if the subobject is of class type, the copy assignment operator
5629 // for the class is used (as if by explicit qualification; that is,
5630 // ignoring any possible virtual overriding functions in more derived
5631 // classes);
5632 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5633 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5634
5635 // Look for operator=.
5636 DeclarationName Name
5637 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5638 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5639 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5640
5641 // Filter out any result that isn't a copy-assignment operator.
5642 LookupResult::Filter F = OpLookup.makeFilter();
5643 while (F.hasNext()) {
5644 NamedDecl *D = F.next();
5645 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5646 if (Method->isCopyAssignmentOperator())
5647 continue;
5648
5649 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00005650 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005651 F.done();
5652
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005653 // Suppress the protected check (C++ [class.protected]) for each of the
5654 // assignment operators we found. This strange dance is required when
5655 // we're assigning via a base classes's copy-assignment operator. To
5656 // ensure that we're getting the right base class subobject (without
5657 // ambiguities), we need to cast "this" to that subobject type; to
5658 // ensure that we don't go through the virtual call mechanism, we need
5659 // to qualify the operator= name with the base class (see below). However,
5660 // this means that if the base class has a protected copy assignment
5661 // operator, the protected member access check will fail. So, we
5662 // rewrite "protected" access to "public" access in this case, since we
5663 // know by construction that we're calling from a derived class.
5664 if (CopyingBaseSubobject) {
5665 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5666 L != LEnd; ++L) {
5667 if (L.getAccess() == AS_protected)
5668 L.setAccess(AS_public);
5669 }
5670 }
5671
Douglas Gregorb139cd52010-05-01 20:49:11 +00005672 // Create the nested-name-specifier that will be used to qualify the
5673 // reference to operator=; this is required to suppress the virtual
5674 // call mechanism.
5675 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005676 SS.MakeTrivial(S.Context,
5677 NestedNameSpecifier::Create(S.Context, 0, false,
5678 T.getTypePtr()),
5679 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005680
5681 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00005682 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00005683 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005684 /*FirstQualifierInScope=*/0, OpLookup,
5685 /*TemplateArgs=*/0,
5686 /*SuppressQualifierCheck=*/true);
5687 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005688 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005689
5690 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00005691
John McCalldadc5752010-08-24 06:29:42 +00005692 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005693 OpEqualRef.takeAs<Expr>(),
5694 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005695 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005696 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005697
5698 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005699 }
John McCallab8c2732010-03-16 06:11:48 +00005700
Douglas Gregorb139cd52010-05-01 20:49:11 +00005701 // - if the subobject is of scalar type, the built-in assignment
5702 // operator is used.
5703 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5704 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00005705 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005706 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005707 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005708
5709 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005710 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005711
5712 // - if the subobject is an array, each element is assigned, in the
5713 // manner appropriate to the element type;
5714
5715 // Construct a loop over the array bounds, e.g.,
5716 //
5717 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5718 //
5719 // that will copy each of the array elements.
5720 QualType SizeType = S.Context.getSizeType();
5721
5722 // Create the iteration variable.
5723 IdentifierInfo *IterationVarName = 0;
5724 {
5725 llvm::SmallString<8> Str;
5726 llvm::raw_svector_ostream OS(Str);
5727 OS << "__i" << Depth;
5728 IterationVarName = &S.Context.Idents.get(OS.str());
5729 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00005730 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005731 IterationVarName, SizeType,
5732 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005733 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005734
5735 // Initialize the iteration variable to zero.
5736 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005737 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005738
5739 // Create a reference to the iteration variable; we'll use this several
5740 // times throughout.
5741 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00005742 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005743 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5744
5745 // Create the DeclStmt that holds the iteration variable.
5746 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5747
5748 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005749 llvm::APInt Upper
5750 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00005751 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00005752 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00005753 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5754 BO_NE, S.Context.BoolTy,
5755 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005756
5757 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005758 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00005759 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5760 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005761
5762 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005763 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5764 IterationVarRef, Loc));
5765 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5766 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005767
5768 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00005769 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5770 To, From, CopyingBaseSubobject,
5771 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00005772 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005773 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005774
5775 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00005776 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005777 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00005778 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00005779 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005780}
5781
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005782/// \brief Determine whether the given class has a copy assignment operator
5783/// that accepts a const-qualified argument.
5784static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5785 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5786
5787 if (!Class->hasDeclaredCopyAssignment())
5788 S.DeclareImplicitCopyAssignment(Class);
5789
5790 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5791 DeclarationName OpName
5792 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5793
5794 DeclContext::lookup_const_iterator Op, OpEnd;
5795 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5796 // C++ [class.copy]p9:
5797 // A user-declared copy assignment operator is a non-static non-template
5798 // member function of class X with exactly one parameter of type X, X&,
5799 // const X&, volatile X& or const volatile X&.
5800 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5801 if (!Method)
5802 continue;
5803
5804 if (Method->isStatic())
5805 continue;
5806 if (Method->getPrimaryTemplate())
5807 continue;
5808 const FunctionProtoType *FnType =
5809 Method->getType()->getAs<FunctionProtoType>();
5810 assert(FnType && "Overloaded operator has no prototype.");
5811 // Don't assert on this; an invalid decl might have been left in the AST.
5812 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5813 continue;
5814 bool AcceptsConst = true;
5815 QualType ArgType = FnType->getArgType(0);
5816 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5817 ArgType = Ref->getPointeeType();
5818 // Is it a non-const lvalue reference?
5819 if (!ArgType.isConstQualified())
5820 AcceptsConst = false;
5821 }
5822 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5823 continue;
5824
5825 // We have a single argument of type cv X or cv X&, i.e. we've found the
5826 // copy assignment operator. Return whether it accepts const arguments.
5827 return AcceptsConst;
5828 }
5829 assert(Class->isInvalidDecl() &&
5830 "No copy assignment operator declared in valid code.");
5831 return false;
5832}
5833
Douglas Gregor0be31a22010-07-02 17:43:08 +00005834CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005835 // Note: The following rules are largely analoguous to the copy
5836 // constructor rules. Note that virtual bases are not taken into account
5837 // for determining the argument type of the operator. Note also that
5838 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005839
5840
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005841 // C++ [class.copy]p10:
5842 // If the class definition does not explicitly declare a copy
5843 // assignment operator, one is declared implicitly.
5844 // The implicitly-defined copy assignment operator for a class X
5845 // will have the form
5846 //
5847 // X& X::operator=(const X&)
5848 //
5849 // if
5850 bool HasConstCopyAssignment = true;
5851
5852 // -- each direct base class B of X has a copy assignment operator
5853 // whose parameter is of type const B&, const volatile B& or B,
5854 // and
5855 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5856 BaseEnd = ClassDecl->bases_end();
5857 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5858 assert(!Base->getType()->isDependentType() &&
5859 "Cannot generate implicit members for class with dependent bases.");
5860 const CXXRecordDecl *BaseClassDecl
5861 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005862 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005863 }
5864
5865 // -- for all the nonstatic data members of X that are of a class
5866 // type M (or array thereof), each such class type has a copy
5867 // assignment operator whose parameter is of type const M&,
5868 // const volatile M& or M.
5869 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5870 FieldEnd = ClassDecl->field_end();
5871 HasConstCopyAssignment && Field != FieldEnd;
5872 ++Field) {
5873 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5874 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5875 const CXXRecordDecl *FieldClassDecl
5876 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005877 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005878 }
5879 }
5880
5881 // Otherwise, the implicitly declared copy assignment operator will
5882 // have the form
5883 //
5884 // X& X::operator=(X&)
5885 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5886 QualType RetType = Context.getLValueReferenceType(ArgType);
5887 if (HasConstCopyAssignment)
5888 ArgType = ArgType.withConst();
5889 ArgType = Context.getLValueReferenceType(ArgType);
5890
Douglas Gregor68e11362010-07-01 17:48:08 +00005891 // C++ [except.spec]p14:
5892 // An implicitly declared special member function (Clause 12) shall have an
5893 // exception-specification. [...]
5894 ImplicitExceptionSpecification ExceptSpec(Context);
5895 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5896 BaseEnd = ClassDecl->bases_end();
5897 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005898 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005899 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005900
5901 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5902 DeclareImplicitCopyAssignment(BaseClassDecl);
5903
Douglas Gregor68e11362010-07-01 17:48:08 +00005904 if (CXXMethodDecl *CopyAssign
5905 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5906 ExceptSpec.CalledDecl(CopyAssign);
5907 }
5908 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5909 FieldEnd = ClassDecl->field_end();
5910 Field != FieldEnd;
5911 ++Field) {
5912 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5913 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005914 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005915 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005916
5917 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5918 DeclareImplicitCopyAssignment(FieldClassDecl);
5919
Douglas Gregor68e11362010-07-01 17:48:08 +00005920 if (CXXMethodDecl *CopyAssign
5921 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5922 ExceptSpec.CalledDecl(CopyAssign);
5923 }
5924 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005925
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005926 // An implicitly-declared copy assignment operator is an inline public
5927 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005928 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005929 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005930 EPI.NumExceptions = ExceptSpec.size();
5931 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005932 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005933 SourceLocation ClassLoc = ClassDecl->getLocation();
5934 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005935 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00005936 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005937 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005938 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005939 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00005940 /*isInline=*/true,
5941 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005942 CopyAssignment->setAccess(AS_public);
5943 CopyAssignment->setImplicit();
5944 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005945
5946 // Add the parameter to the operator.
5947 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005948 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005949 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005950 SC_None,
5951 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005952 CopyAssignment->setParams(&FromParam, 1);
5953
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005954 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005955 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5956
Douglas Gregor0be31a22010-07-02 17:43:08 +00005957 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005958 PushOnScopeChains(CopyAssignment, S, false);
5959 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005960
5961 AddOverriddenMethods(ClassDecl, CopyAssignment);
5962 return CopyAssignment;
5963}
5964
Douglas Gregorb139cd52010-05-01 20:49:11 +00005965void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5966 CXXMethodDecl *CopyAssignOperator) {
5967 assert((CopyAssignOperator->isImplicit() &&
5968 CopyAssignOperator->isOverloadedOperator() &&
5969 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005970 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005971 "DefineImplicitCopyAssignment called for wrong function");
5972
5973 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5974
5975 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5976 CopyAssignOperator->setInvalidDecl();
5977 return;
5978 }
5979
5980 CopyAssignOperator->setUsed();
5981
5982 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005983 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005984
5985 // C++0x [class.copy]p30:
5986 // The implicitly-defined or explicitly-defaulted copy assignment operator
5987 // for a non-union class X performs memberwise copy assignment of its
5988 // subobjects. The direct base classes of X are assigned first, in the
5989 // order of their declaration in the base-specifier-list, and then the
5990 // immediate non-static data members of X are assigned, in the order in
5991 // which they were declared in the class definition.
5992
5993 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005994 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005995
5996 // The parameter for the "other" object, which we are copying from.
5997 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5998 Qualifiers OtherQuals = Other->getType().getQualifiers();
5999 QualType OtherRefType = Other->getType();
6000 if (const LValueReferenceType *OtherRef
6001 = OtherRefType->getAs<LValueReferenceType>()) {
6002 OtherRefType = OtherRef->getPointeeType();
6003 OtherQuals = OtherRefType.getQualifiers();
6004 }
6005
6006 // Our location for everything implicitly-generated.
6007 SourceLocation Loc = CopyAssignOperator->getLocation();
6008
6009 // Construct a reference to the "other" object. We'll be using this
6010 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00006011 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006012 assert(OtherRef && "Reference to parameter cannot fail!");
6013
6014 // Construct the "this" pointer. We'll be using this throughout the generated
6015 // ASTs.
6016 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6017 assert(This && "Reference to this cannot fail!");
6018
6019 // Assign base classes.
6020 bool Invalid = false;
6021 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6022 E = ClassDecl->bases_end(); Base != E; ++Base) {
6023 // Form the assignment:
6024 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6025 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00006026 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006027 Invalid = true;
6028 continue;
6029 }
6030
John McCallcf142162010-08-07 06:22:56 +00006031 CXXCastPath BasePath;
6032 BasePath.push_back(Base);
6033
Douglas Gregorb139cd52010-05-01 20:49:11 +00006034 // Construct the "from" expression, which is an implicit cast to the
6035 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00006036 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00006037 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6038 CK_UncheckedDerivedToBase,
6039 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006040
6041 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00006042 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006043
6044 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00006045 To = ImpCastExprToType(To.take(),
6046 Context.getCVRQualifiedType(BaseType,
6047 CopyAssignOperator->getTypeQualifiers()),
6048 CK_UncheckedDerivedToBase,
6049 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006050
6051 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00006052 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00006053 To.get(), From,
6054 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006055 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006056 Diag(CurrentLocation, diag::note_member_synthesized_at)
6057 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6058 CopyAssignOperator->setInvalidDecl();
6059 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006060 }
6061
6062 // Success! Record the copy.
6063 Statements.push_back(Copy.takeAs<Expr>());
6064 }
6065
6066 // \brief Reference to the __builtin_memcpy function.
6067 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006068 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006069 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006070
6071 // Assign non-static members.
6072 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6073 FieldEnd = ClassDecl->field_end();
6074 Field != FieldEnd; ++Field) {
6075 // Check for members of reference type; we can't copy those.
6076 if (Field->getType()->isReferenceType()) {
6077 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6078 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6079 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006080 Diag(CurrentLocation, diag::note_member_synthesized_at)
6081 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006082 Invalid = true;
6083 continue;
6084 }
6085
6086 // Check for members of const-qualified, non-class type.
6087 QualType BaseType = Context.getBaseElementType(Field->getType());
6088 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6089 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6090 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6091 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006092 Diag(CurrentLocation, diag::note_member_synthesized_at)
6093 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006094 Invalid = true;
6095 continue;
6096 }
6097
6098 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00006099 if (FieldType->isIncompleteArrayType()) {
6100 assert(ClassDecl->hasFlexibleArrayMember() &&
6101 "Incomplete array type is not valid");
6102 continue;
6103 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006104
6105 // Build references to the field in the object we're copying from and to.
6106 CXXScopeSpec SS; // Intentionally empty
6107 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6108 LookupMemberName);
6109 MemberLookup.addDecl(*Field);
6110 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00006111 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00006112 Loc, /*IsArrow=*/false,
6113 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00006114 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00006115 Loc, /*IsArrow=*/true,
6116 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006117 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6118 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6119
6120 // If the field should be copied with __builtin_memcpy rather than via
6121 // explicit assignments, do so. This optimization only applies for arrays
6122 // of scalars and arrays of class type with trivial copy-assignment
6123 // operators.
6124 if (FieldType->isArrayType() &&
6125 (!BaseType->isRecordType() ||
6126 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
6127 ->hasTrivialCopyAssignment())) {
6128 // Compute the size of the memory buffer to be copied.
6129 QualType SizeType = Context.getSizeType();
6130 llvm::APInt Size(Context.getTypeSize(SizeType),
6131 Context.getTypeSizeInChars(BaseType).getQuantity());
6132 for (const ConstantArrayType *Array
6133 = Context.getAsConstantArrayType(FieldType);
6134 Array;
6135 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00006136 llvm::APInt ArraySize
6137 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006138 Size *= ArraySize;
6139 }
6140
6141 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00006142 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6143 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006144
6145 bool NeedsCollectableMemCpy =
6146 (BaseType->isRecordType() &&
6147 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6148
6149 if (NeedsCollectableMemCpy) {
6150 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006151 // Create a reference to the __builtin_objc_memmove_collectable function.
6152 LookupResult R(*this,
6153 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006154 Loc, LookupOrdinaryName);
6155 LookupName(R, TUScope, true);
6156
6157 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6158 if (!CollectableMemCpy) {
6159 // Something went horribly wrong earlier, and we will have
6160 // complained about it.
6161 Invalid = true;
6162 continue;
6163 }
6164
6165 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6166 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006167 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006168 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6169 }
6170 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006171 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006172 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006173 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6174 LookupOrdinaryName);
6175 LookupName(R, TUScope, true);
6176
6177 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6178 if (!BuiltinMemCpy) {
6179 // Something went horribly wrong earlier, and we will have complained
6180 // about it.
6181 Invalid = true;
6182 continue;
6183 }
6184
6185 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6186 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006187 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006188 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6189 }
6190
John McCall37ad5512010-08-23 06:44:23 +00006191 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006192 CallArgs.push_back(To.takeAs<Expr>());
6193 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006194 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00006195 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006196 if (NeedsCollectableMemCpy)
6197 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006198 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006199 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006200 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006201 else
6202 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006203 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006204 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006205 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006206
Douglas Gregorb139cd52010-05-01 20:49:11 +00006207 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
6208 Statements.push_back(Call.takeAs<Expr>());
6209 continue;
6210 }
6211
6212 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00006213 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00006214 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006215 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006216 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006217 Diag(CurrentLocation, diag::note_member_synthesized_at)
6218 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6219 CopyAssignOperator->setInvalidDecl();
6220 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006221 }
6222
6223 // Success! Record the copy.
6224 Statements.push_back(Copy.takeAs<Stmt>());
6225 }
6226
6227 if (!Invalid) {
6228 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00006229 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006230
John McCalldadc5752010-08-24 06:29:42 +00006231 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006232 if (Return.isInvalid())
6233 Invalid = true;
6234 else {
6235 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00006236
6237 if (Trap.hasErrorOccurred()) {
6238 Diag(CurrentLocation, diag::note_member_synthesized_at)
6239 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6240 Invalid = true;
6241 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006242 }
6243 }
6244
6245 if (Invalid) {
6246 CopyAssignOperator->setInvalidDecl();
6247 return;
6248 }
6249
John McCalldadc5752010-08-24 06:29:42 +00006250 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00006251 /*isStmtExpr=*/false);
6252 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
6253 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00006254
6255 if (ASTMutationListener *L = getASTMutationListener()) {
6256 L->CompletedImplicitDefinition(CopyAssignOperator);
6257 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006258}
6259
Douglas Gregor0be31a22010-07-02 17:43:08 +00006260CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
6261 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00006262 // C++ [class.copy]p4:
6263 // If the class definition does not explicitly declare a copy
6264 // constructor, one is declared implicitly.
6265
Douglas Gregor54be3392010-07-01 17:57:27 +00006266 // C++ [class.copy]p5:
6267 // The implicitly-declared copy constructor for a class X will
6268 // have the form
6269 //
6270 // X::X(const X&)
6271 //
6272 // if
6273 bool HasConstCopyConstructor = true;
6274
6275 // -- each direct or virtual base class B of X has a copy
6276 // constructor whose first parameter is of type const B& or
6277 // const volatile B&, and
6278 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6279 BaseEnd = ClassDecl->bases_end();
6280 HasConstCopyConstructor && Base != BaseEnd;
6281 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00006282 // Virtual bases are handled below.
6283 if (Base->isVirtual())
6284 continue;
6285
Douglas Gregora6d69502010-07-02 23:41:54 +00006286 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00006287 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006288 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6289 DeclareImplicitCopyConstructor(BaseClassDecl);
6290
Douglas Gregorcfe68222010-07-01 18:27:03 +00006291 HasConstCopyConstructor
6292 = BaseClassDecl->hasConstCopyConstructor(Context);
6293 }
6294
6295 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6296 BaseEnd = ClassDecl->vbases_end();
6297 HasConstCopyConstructor && Base != BaseEnd;
6298 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006299 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00006300 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006301 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6302 DeclareImplicitCopyConstructor(BaseClassDecl);
6303
Douglas Gregor54be3392010-07-01 17:57:27 +00006304 HasConstCopyConstructor
6305 = BaseClassDecl->hasConstCopyConstructor(Context);
6306 }
6307
6308 // -- for all the nonstatic data members of X that are of a
6309 // class type M (or array thereof), each such class type
6310 // has a copy constructor whose first parameter is of type
6311 // const M& or const volatile M&.
6312 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6313 FieldEnd = ClassDecl->field_end();
6314 HasConstCopyConstructor && Field != FieldEnd;
6315 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00006316 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00006317 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006318 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00006319 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006320 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6321 DeclareImplicitCopyConstructor(FieldClassDecl);
6322
Douglas Gregor54be3392010-07-01 17:57:27 +00006323 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00006324 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00006325 }
6326 }
6327
6328 // Otherwise, the implicitly declared copy constructor will have
6329 // the form
6330 //
6331 // X::X(X&)
6332 QualType ClassType = Context.getTypeDeclType(ClassDecl);
6333 QualType ArgType = ClassType;
6334 if (HasConstCopyConstructor)
6335 ArgType = ArgType.withConst();
6336 ArgType = Context.getLValueReferenceType(ArgType);
6337
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006338 // C++ [except.spec]p14:
6339 // An implicitly declared special member function (Clause 12) shall have an
6340 // exception-specification. [...]
6341 ImplicitExceptionSpecification ExceptSpec(Context);
6342 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6343 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6344 BaseEnd = ClassDecl->bases_end();
6345 Base != BaseEnd;
6346 ++Base) {
6347 // Virtual bases are handled below.
6348 if (Base->isVirtual())
6349 continue;
6350
Douglas Gregora6d69502010-07-02 23:41:54 +00006351 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006352 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006353 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6354 DeclareImplicitCopyConstructor(BaseClassDecl);
6355
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006356 if (CXXConstructorDecl *CopyConstructor
6357 = BaseClassDecl->getCopyConstructor(Context, Quals))
6358 ExceptSpec.CalledDecl(CopyConstructor);
6359 }
6360 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6361 BaseEnd = ClassDecl->vbases_end();
6362 Base != BaseEnd;
6363 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006364 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006365 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006366 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6367 DeclareImplicitCopyConstructor(BaseClassDecl);
6368
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006369 if (CXXConstructorDecl *CopyConstructor
6370 = BaseClassDecl->getCopyConstructor(Context, Quals))
6371 ExceptSpec.CalledDecl(CopyConstructor);
6372 }
6373 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6374 FieldEnd = ClassDecl->field_end();
6375 Field != FieldEnd;
6376 ++Field) {
6377 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6378 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006379 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006380 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006381 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6382 DeclareImplicitCopyConstructor(FieldClassDecl);
6383
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006384 if (CXXConstructorDecl *CopyConstructor
6385 = FieldClassDecl->getCopyConstructor(Context, Quals))
6386 ExceptSpec.CalledDecl(CopyConstructor);
6387 }
6388 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006389
Douglas Gregor54be3392010-07-01 17:57:27 +00006390 // An implicitly-declared copy constructor is an inline public
6391 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00006392 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006393 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00006394 EPI.NumExceptions = ExceptSpec.size();
6395 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00006396 DeclarationName Name
6397 = Context.DeclarationNames.getCXXConstructorName(
6398 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006399 SourceLocation ClassLoc = ClassDecl->getLocation();
6400 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor54be3392010-07-01 17:57:27 +00006401 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00006402 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00006403 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006404 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00006405 /*TInfo=*/0,
6406 /*isExplicit=*/false,
6407 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006408 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00006409 CopyConstructor->setAccess(AS_public);
Douglas Gregor54be3392010-07-01 17:57:27 +00006410 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6411
Douglas Gregora6d69502010-07-02 23:41:54 +00006412 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00006413 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6414
Douglas Gregor54be3392010-07-01 17:57:27 +00006415 // Add the parameter to the constructor.
6416 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006417 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00006418 /*IdentifierInfo=*/0,
6419 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006420 SC_None,
6421 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00006422 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00006423 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00006424 PushOnScopeChains(CopyConstructor, S, false);
6425 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00006426
6427 return CopyConstructor;
6428}
6429
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006430void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6431 CXXConstructorDecl *CopyConstructor,
6432 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00006433 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00006434 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00006435 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006436 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006437
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00006438 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006439 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006440
Douglas Gregora57478e2010-05-01 15:04:51 +00006441 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006442 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006443
Alexis Hunt1d792652011-01-08 20:30:50 +00006444 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006445 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00006446 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00006447 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00006448 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00006449 } else {
6450 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6451 CopyConstructor->getLocation(),
6452 MultiStmtArg(*this, 0, 0),
6453 /*isStmtExpr=*/false)
6454 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00006455 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00006456
6457 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00006458
6459 if (ASTMutationListener *L = getASTMutationListener()) {
6460 L->CompletedImplicitDefinition(CopyConstructor);
6461 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006462}
6463
John McCalldadc5752010-08-24 06:29:42 +00006464ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006465Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00006466 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006467 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006468 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006469 unsigned ConstructKind,
6470 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00006471 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00006472
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006473 // C++0x [class.copy]p34:
6474 // When certain criteria are met, an implementation is allowed to
6475 // omit the copy/move construction of a class object, even if the
6476 // copy/move constructor and/or destructor for the object have
6477 // side effects. [...]
6478 // - when a temporary class object that has not been bound to a
6479 // reference (12.2) would be copied/moved to a class object
6480 // with the same cv-unqualified type, the copy/move operation
6481 // can be omitted by constructing the temporary object
6482 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00006483 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00006484 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006485 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00006486 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00006487 }
Mike Stump11289f42009-09-09 15:08:12 +00006488
6489 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006490 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006491 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00006492}
6493
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006494/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6495/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00006496ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006497Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6498 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006499 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006500 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006501 unsigned ConstructKind,
6502 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006503 unsigned NumExprs = ExprArgs.size();
6504 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00006505
Nick Lewyckyd4693212011-03-25 01:44:32 +00006506 for (specific_attr_iterator<NonNullAttr>
6507 i = Constructor->specific_attr_begin<NonNullAttr>(),
6508 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6509 const NonNullAttr *NonNull = *i;
6510 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6511 }
6512
Douglas Gregor27381f32009-11-23 12:27:39 +00006513 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00006514 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006515 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00006516 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006517 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6518 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006519}
6520
Mike Stump11289f42009-09-09 15:08:12 +00006521bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006522 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006523 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00006524 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00006525 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00006526 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00006527 move(Exprs), false, CXXConstructExpr::CK_Complete,
6528 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006529 if (TempResult.isInvalid())
6530 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006531
Anders Carlsson6eb55572009-08-25 05:12:04 +00006532 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00006533 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00006534 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00006535 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00006536 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00006537
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006538 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00006539}
6540
John McCall03c48482010-02-02 09:10:11 +00006541void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00006542 if (VD->isInvalidDecl()) return;
6543
John McCall03c48482010-02-02 09:10:11 +00006544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00006545 if (ClassDecl->isInvalidDecl()) return;
6546 if (ClassDecl->hasTrivialDestructor()) return;
6547 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00006548
Chandler Carruth86d17d32011-03-27 21:26:48 +00006549 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6550 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6551 CheckDestructorAccess(VD->getLocation(), Destructor,
6552 PDiag(diag::err_access_dtor_var)
6553 << VD->getDeclName()
6554 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00006555
Chandler Carruth86d17d32011-03-27 21:26:48 +00006556 if (!VD->hasGlobalStorage()) return;
6557
6558 // Emit warning for non-trivial dtor in global scope (a real global,
6559 // class-static, function-static).
6560 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6561
6562 // TODO: this should be re-enabled for static locals by !CXAAtExit
6563 if (!VD->isStaticLocal())
6564 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006565}
6566
Mike Stump11289f42009-09-09 15:08:12 +00006567/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006568/// ActOnDeclarator, when a C++ direct initializer is present.
6569/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00006570void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00006571 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006572 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00006573 SourceLocation RParenLoc,
6574 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00006575 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006576
6577 // If there is no declaration, there was an error parsing it. Just ignore
6578 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00006579 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006580 return;
Mike Stump11289f42009-09-09 15:08:12 +00006581
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006582 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6583 if (!VDecl) {
6584 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6585 RealDecl->setInvalidDecl();
6586 return;
6587 }
6588
Richard Smith30482bc2011-02-20 03:19:35 +00006589 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6590 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00006591 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6592 if (Exprs.size() > 1) {
6593 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6594 diag::err_auto_var_init_multiple_expressions)
6595 << VDecl->getDeclName() << VDecl->getType()
6596 << VDecl->getSourceRange();
6597 RealDecl->setInvalidDecl();
6598 return;
6599 }
6600
6601 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00006602 TypeSourceInfo *DeducedType = 0;
6603 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00006604 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6605 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6606 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00006607 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00006608 RealDecl->setInvalidDecl();
6609 return;
6610 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006611 VDecl->setTypeSourceInfo(DeducedType);
6612 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00006613
6614 // If this is a redeclaration, check that the type we just deduced matches
6615 // the previously declared type.
6616 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6617 MergeVarDeclTypes(VDecl, Old);
6618 }
6619
Douglas Gregor402250f2009-08-26 21:14:46 +00006620 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006621 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006622 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6623 //
6624 // Clients that want to distinguish between the two forms, can check for
6625 // direct initializer using VarDecl::hasCXXDirectInitializer().
6626 // A major benefit is that clients that don't particularly care about which
6627 // exactly form was it (like the CodeGen) can handle both cases without
6628 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006629
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006630 // C++ 8.5p11:
6631 // The form of initialization (using parentheses or '=') is generally
6632 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006633 // class type.
6634
Douglas Gregor50dc2192010-02-11 22:55:30 +00006635 if (!VDecl->getType()->isDependentType() &&
6636 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00006637 diag::err_typecheck_decl_incomplete_type)) {
6638 VDecl->setInvalidDecl();
6639 return;
6640 }
6641
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006642 // The variable can not have an abstract class type.
6643 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6644 diag::err_abstract_type_in_decl,
6645 AbstractVariableType))
6646 VDecl->setInvalidDecl();
6647
Sebastian Redl5ca79842010-02-01 20:16:42 +00006648 const VarDecl *Def;
6649 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006650 Diag(VDecl->getLocation(), diag::err_redefinition)
6651 << VDecl->getDeclName();
6652 Diag(Def->getLocation(), diag::note_previous_definition);
6653 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006654 return;
6655 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00006656
Douglas Gregorf0f83692010-08-24 05:27:49 +00006657 // C++ [class.static.data]p4
6658 // If a static data member is of const integral or const
6659 // enumeration type, its declaration in the class definition can
6660 // specify a constant-initializer which shall be an integral
6661 // constant expression (5.19). In that case, the member can appear
6662 // in integral constant expressions. The member shall still be
6663 // defined in a namespace scope if it is used in the program and the
6664 // namespace scope definition shall not contain an initializer.
6665 //
6666 // We already performed a redefinition check above, but for static
6667 // data members we also need to check whether there was an in-class
6668 // declaration with an initializer.
6669 const VarDecl* PrevInit = 0;
6670 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6671 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6672 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6673 return;
6674 }
6675
Douglas Gregor71f39c92010-12-16 01:31:22 +00006676 bool IsDependent = false;
6677 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6678 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6679 VDecl->setInvalidDecl();
6680 return;
6681 }
6682
6683 if (Exprs.get()[I]->isTypeDependent())
6684 IsDependent = true;
6685 }
6686
Douglas Gregor50dc2192010-02-11 22:55:30 +00006687 // If either the declaration has a dependent type or if any of the
6688 // expressions is type-dependent, we represent the initialization
6689 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00006690 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00006691 // Let clients know that initialization was done with a direct initializer.
6692 VDecl->setCXXDirectInitializer(true);
6693
6694 // Store the initialization expressions as a ParenListExpr.
6695 unsigned NumExprs = Exprs.size();
6696 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6697 (Expr **)Exprs.release(),
6698 NumExprs, RParenLoc));
6699 return;
6700 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006701
6702 // Capture the variable that is being initialized and the style of
6703 // initialization.
6704 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6705
6706 // FIXME: Poor source location information.
6707 InitializationKind Kind
6708 = InitializationKind::CreateDirect(VDecl->getLocation(),
6709 LParenLoc, RParenLoc);
6710
6711 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00006712 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00006713 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006714 if (Result.isInvalid()) {
6715 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006716 return;
6717 }
John McCallacf0ee52010-10-08 02:01:28 +00006718
6719 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006720
Douglas Gregora40433a2010-12-07 00:41:46 +00006721 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00006722 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006723 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006724
John McCall8b7fd8f12011-01-19 11:48:09 +00006725 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006726}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006727
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006728/// \brief Given a constructor and the set of arguments provided for the
6729/// constructor, convert the arguments and add any required default arguments
6730/// to form a proper call to this constructor.
6731///
6732/// \returns true if an error occurred, false otherwise.
6733bool
6734Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6735 MultiExprArg ArgsPtr,
6736 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00006737 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006738 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6739 unsigned NumArgs = ArgsPtr.size();
6740 Expr **Args = (Expr **)ArgsPtr.get();
6741
6742 const FunctionProtoType *Proto
6743 = Constructor->getType()->getAs<FunctionProtoType>();
6744 assert(Proto && "Constructor without a prototype?");
6745 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006746
6747 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006748 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006749 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006750 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006751 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006752
6753 VariadicCallType CallType =
6754 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6755 llvm::SmallVector<Expr *, 8> AllArgs;
6756 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6757 Proto, 0, Args, NumArgs, AllArgs,
6758 CallType);
6759 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6760 ConvertedArgs.push_back(AllArgs[i]);
6761 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006762}
6763
Anders Carlssone363c8e2009-12-12 00:32:00 +00006764static inline bool
6765CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6766 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006767 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00006768 if (isa<NamespaceDecl>(DC)) {
6769 return SemaRef.Diag(FnDecl->getLocation(),
6770 diag::err_operator_new_delete_declared_in_namespace)
6771 << FnDecl->getDeclName();
6772 }
6773
6774 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00006775 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006776 return SemaRef.Diag(FnDecl->getLocation(),
6777 diag::err_operator_new_delete_declared_static)
6778 << FnDecl->getDeclName();
6779 }
6780
Anders Carlsson60659a82009-12-12 02:43:16 +00006781 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00006782}
6783
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006784static inline bool
6785CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6786 CanQualType ExpectedResultType,
6787 CanQualType ExpectedFirstParamType,
6788 unsigned DependentParamTypeDiag,
6789 unsigned InvalidParamTypeDiag) {
6790 QualType ResultType =
6791 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6792
6793 // Check that the result type is not dependent.
6794 if (ResultType->isDependentType())
6795 return SemaRef.Diag(FnDecl->getLocation(),
6796 diag::err_operator_new_delete_dependent_result_type)
6797 << FnDecl->getDeclName() << ExpectedResultType;
6798
6799 // Check that the result type is what we expect.
6800 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6801 return SemaRef.Diag(FnDecl->getLocation(),
6802 diag::err_operator_new_delete_invalid_result_type)
6803 << FnDecl->getDeclName() << ExpectedResultType;
6804
6805 // A function template must have at least 2 parameters.
6806 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6807 return SemaRef.Diag(FnDecl->getLocation(),
6808 diag::err_operator_new_delete_template_too_few_parameters)
6809 << FnDecl->getDeclName();
6810
6811 // The function decl must have at least 1 parameter.
6812 if (FnDecl->getNumParams() == 0)
6813 return SemaRef.Diag(FnDecl->getLocation(),
6814 diag::err_operator_new_delete_too_few_parameters)
6815 << FnDecl->getDeclName();
6816
6817 // Check the the first parameter type is not dependent.
6818 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6819 if (FirstParamType->isDependentType())
6820 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6821 << FnDecl->getDeclName() << ExpectedFirstParamType;
6822
6823 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00006824 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006825 ExpectedFirstParamType)
6826 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6827 << FnDecl->getDeclName() << ExpectedFirstParamType;
6828
6829 return false;
6830}
6831
Anders Carlsson12308f42009-12-11 23:23:22 +00006832static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006833CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006834 // C++ [basic.stc.dynamic.allocation]p1:
6835 // A program is ill-formed if an allocation function is declared in a
6836 // namespace scope other than global scope or declared static in global
6837 // scope.
6838 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6839 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006840
6841 CanQualType SizeTy =
6842 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6843
6844 // C++ [basic.stc.dynamic.allocation]p1:
6845 // The return type shall be void*. The first parameter shall have type
6846 // std::size_t.
6847 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6848 SizeTy,
6849 diag::err_operator_new_dependent_param_type,
6850 diag::err_operator_new_param_type))
6851 return true;
6852
6853 // C++ [basic.stc.dynamic.allocation]p1:
6854 // The first parameter shall not have an associated default argument.
6855 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00006856 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006857 diag::err_operator_new_default_arg)
6858 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6859
6860 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00006861}
6862
6863static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00006864CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6865 // C++ [basic.stc.dynamic.deallocation]p1:
6866 // A program is ill-formed if deallocation functions are declared in a
6867 // namespace scope other than global scope or declared static in global
6868 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006869 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6870 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006871
6872 // C++ [basic.stc.dynamic.deallocation]p2:
6873 // Each deallocation function shall return void and its first parameter
6874 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006875 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6876 SemaRef.Context.VoidPtrTy,
6877 diag::err_operator_delete_dependent_param_type,
6878 diag::err_operator_delete_param_type))
6879 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006880
Anders Carlsson12308f42009-12-11 23:23:22 +00006881 return false;
6882}
6883
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006884/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6885/// of this overloaded operator is well-formed. If so, returns false;
6886/// otherwise, emits appropriate diagnostics and returns true.
6887bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006888 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006889 "Expected an overloaded operator declaration");
6890
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006891 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6892
Mike Stump11289f42009-09-09 15:08:12 +00006893 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006894 // The allocation and deallocation functions, operator new,
6895 // operator new[], operator delete and operator delete[], are
6896 // described completely in 3.7.3. The attributes and restrictions
6897 // found in the rest of this subclause do not apply to them unless
6898 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006899 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006900 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006901
Anders Carlsson22f443f2009-12-12 00:26:23 +00006902 if (Op == OO_New || Op == OO_Array_New)
6903 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006904
6905 // C++ [over.oper]p6:
6906 // An operator function shall either be a non-static member
6907 // function or be a non-member function and have at least one
6908 // parameter whose type is a class, a reference to a class, an
6909 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006910 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6911 if (MethodDecl->isStatic())
6912 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006913 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006914 } else {
6915 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006916 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6917 ParamEnd = FnDecl->param_end();
6918 Param != ParamEnd; ++Param) {
6919 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006920 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6921 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006922 ClassOrEnumParam = true;
6923 break;
6924 }
6925 }
6926
Douglas Gregord69246b2008-11-17 16:14:12 +00006927 if (!ClassOrEnumParam)
6928 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006929 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006930 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006931 }
6932
6933 // C++ [over.oper]p8:
6934 // An operator function cannot have default arguments (8.3.6),
6935 // except where explicitly stated below.
6936 //
Mike Stump11289f42009-09-09 15:08:12 +00006937 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006938 // (C++ [over.call]p1).
6939 if (Op != OO_Call) {
6940 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6941 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006942 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006943 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006944 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006945 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006946 }
6947 }
6948
Douglas Gregor6cf08062008-11-10 13:38:07 +00006949 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6950 { false, false, false }
6951#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6952 , { Unary, Binary, MemberOnly }
6953#include "clang/Basic/OperatorKinds.def"
6954 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006955
Douglas Gregor6cf08062008-11-10 13:38:07 +00006956 bool CanBeUnaryOperator = OperatorUses[Op][0];
6957 bool CanBeBinaryOperator = OperatorUses[Op][1];
6958 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006959
6960 // C++ [over.oper]p8:
6961 // [...] Operator functions cannot have more or fewer parameters
6962 // than the number required for the corresponding operator, as
6963 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006964 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006965 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006966 if (Op != OO_Call &&
6967 ((NumParams == 1 && !CanBeUnaryOperator) ||
6968 (NumParams == 2 && !CanBeBinaryOperator) ||
6969 (NumParams < 1) || (NumParams > 2))) {
6970 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006971 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006972 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006973 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006974 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006975 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006976 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006977 assert(CanBeBinaryOperator &&
6978 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006979 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006980 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006981
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006982 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006983 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006984 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006985
Douglas Gregord69246b2008-11-17 16:14:12 +00006986 // Overloaded operators other than operator() cannot be variadic.
6987 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006988 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006989 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006990 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006991 }
6992
6993 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006994 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6995 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006996 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006997 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006998 }
6999
7000 // C++ [over.inc]p1:
7001 // The user-defined function called operator++ implements the
7002 // prefix and postfix ++ operator. If this function is a member
7003 // function with no parameters, or a non-member function with one
7004 // parameter of class or enumeration type, it defines the prefix
7005 // increment operator ++ for objects of that type. If the function
7006 // is a member function with one parameter (which shall be of type
7007 // int) or a non-member function with two parameters (the second
7008 // of which shall be of type int), it defines the postfix
7009 // increment operator ++ for objects of that type.
7010 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7011 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7012 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00007013 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007014 ParamIsInt = BT->getKind() == BuiltinType::Int;
7015
Chris Lattner2b786902008-11-21 07:50:02 +00007016 if (!ParamIsInt)
7017 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00007018 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007019 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007020 }
7021
Douglas Gregord69246b2008-11-17 16:14:12 +00007022 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007023}
Chris Lattner3b024a32008-12-17 07:09:26 +00007024
Alexis Huntc88db062010-01-13 09:01:02 +00007025/// CheckLiteralOperatorDeclaration - Check whether the declaration
7026/// of this literal operator function is well-formed. If so, returns
7027/// false; otherwise, emits appropriate diagnostics and returns true.
7028bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7029 DeclContext *DC = FnDecl->getDeclContext();
7030 Decl::Kind Kind = DC->getDeclKind();
7031 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7032 Kind != Decl::LinkageSpec) {
7033 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7034 << FnDecl->getDeclName();
7035 return true;
7036 }
7037
7038 bool Valid = false;
7039
Alexis Hunt7dd26172010-04-07 23:11:06 +00007040 // template <char...> type operator "" name() is the only valid template
7041 // signature, and the only valid signature with no parameters.
7042 if (FnDecl->param_size() == 0) {
7043 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7044 // Must have only one template parameter
7045 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7046 if (Params->size() == 1) {
7047 NonTypeTemplateParmDecl *PmDecl =
7048 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00007049
Alexis Hunt7dd26172010-04-07 23:11:06 +00007050 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00007051 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7052 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7053 Valid = true;
7054 }
7055 }
7056 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00007057 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00007058 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7059
Alexis Huntc88db062010-01-13 09:01:02 +00007060 QualType T = (*Param)->getType();
7061
Alexis Hunt079a6f72010-04-07 22:57:35 +00007062 // unsigned long long int, long double, and any character type are allowed
7063 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00007064 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7065 Context.hasSameType(T, Context.LongDoubleTy) ||
7066 Context.hasSameType(T, Context.CharTy) ||
7067 Context.hasSameType(T, Context.WCharTy) ||
7068 Context.hasSameType(T, Context.Char16Ty) ||
7069 Context.hasSameType(T, Context.Char32Ty)) {
7070 if (++Param == FnDecl->param_end())
7071 Valid = true;
7072 goto FinishedParams;
7073 }
7074
Alexis Hunt079a6f72010-04-07 22:57:35 +00007075 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00007076 const PointerType *PT = T->getAs<PointerType>();
7077 if (!PT)
7078 goto FinishedParams;
7079 T = PT->getPointeeType();
7080 if (!T.isConstQualified())
7081 goto FinishedParams;
7082 T = T.getUnqualifiedType();
7083
7084 // Move on to the second parameter;
7085 ++Param;
7086
7087 // If there is no second parameter, the first must be a const char *
7088 if (Param == FnDecl->param_end()) {
7089 if (Context.hasSameType(T, Context.CharTy))
7090 Valid = true;
7091 goto FinishedParams;
7092 }
7093
7094 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7095 // are allowed as the first parameter to a two-parameter function
7096 if (!(Context.hasSameType(T, Context.CharTy) ||
7097 Context.hasSameType(T, Context.WCharTy) ||
7098 Context.hasSameType(T, Context.Char16Ty) ||
7099 Context.hasSameType(T, Context.Char32Ty)))
7100 goto FinishedParams;
7101
7102 // The second and final parameter must be an std::size_t
7103 T = (*Param)->getType().getUnqualifiedType();
7104 if (Context.hasSameType(T, Context.getSizeType()) &&
7105 ++Param == FnDecl->param_end())
7106 Valid = true;
7107 }
7108
7109 // FIXME: This diagnostic is absolutely terrible.
7110FinishedParams:
7111 if (!Valid) {
7112 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7113 << FnDecl->getDeclName();
7114 return true;
7115 }
7116
7117 return false;
7118}
7119
Douglas Gregor07665a62009-01-05 19:45:36 +00007120/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7121/// linkage specification, including the language and (if present)
7122/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7123/// the location of the language string literal, which is provided
7124/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7125/// the '{' brace. Otherwise, this linkage specification does not
7126/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00007127Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7128 SourceLocation LangLoc,
7129 llvm::StringRef Lang,
7130 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00007131 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007132 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007133 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007134 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007135 Language = LinkageSpecDecl::lang_cxx;
7136 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00007137 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00007138 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00007139 }
Mike Stump11289f42009-09-09 15:08:12 +00007140
Chris Lattner438e5012008-12-17 07:13:27 +00007141 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00007142
Douglas Gregor07665a62009-01-05 19:45:36 +00007143 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007144 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007145 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00007146 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00007147 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00007148}
7149
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00007150/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00007151/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7152/// valid, it's the position of the closing '}' brace in a linkage
7153/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00007154Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007155 Decl *LinkageSpec,
7156 SourceLocation RBraceLoc) {
7157 if (LinkageSpec) {
7158 if (RBraceLoc.isValid()) {
7159 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7160 LSDecl->setRBraceLoc(RBraceLoc);
7161 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007162 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007163 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007164 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00007165}
7166
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007167/// \brief Perform semantic analysis for the variable declaration that
7168/// occurs within a C++ catch clause, returning the newly-created
7169/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007170VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00007171 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007172 SourceLocation StartLoc,
7173 SourceLocation Loc,
7174 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007175 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007176 QualType ExDeclType = TInfo->getType();
7177
Sebastian Redl54c04d42008-12-22 19:15:10 +00007178 // Arrays and functions decay.
7179 if (ExDeclType->isArrayType())
7180 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7181 else if (ExDeclType->isFunctionType())
7182 ExDeclType = Context.getPointerType(ExDeclType);
7183
7184 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7185 // The exception-declaration shall not denote a pointer or reference to an
7186 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00007187 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00007188 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007189 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00007190 Invalid = true;
7191 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007192
Douglas Gregor104ee002010-03-08 01:47:36 +00007193 // GCC allows catching pointers and references to incomplete types
7194 // as an extension; so do we, but we warn by default.
7195
Sebastian Redl54c04d42008-12-22 19:15:10 +00007196 QualType BaseType = ExDeclType;
7197 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00007198 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00007199 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007200 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007201 BaseType = Ptr->getPointeeType();
7202 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00007203 DK = diag::ext_catch_incomplete_ptr;
7204 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00007205 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00007206 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00007207 BaseType = Ref->getPointeeType();
7208 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00007209 DK = diag::ext_catch_incomplete_ref;
7210 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007211 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00007212 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00007213 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
7214 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00007215 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007216
Mike Stump11289f42009-09-09 15:08:12 +00007217 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007218 RequireNonAbstractType(Loc, ExDeclType,
7219 diag::err_abstract_type_in_decl,
7220 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00007221 Invalid = true;
7222
John McCall2ca705e2010-07-24 00:37:23 +00007223 // Only the non-fragile NeXT runtime currently supports C++ catches
7224 // of ObjC types, and no runtime supports catching ObjC types by value.
7225 if (!Invalid && getLangOptions().ObjC1) {
7226 QualType T = ExDeclType;
7227 if (const ReferenceType *RT = T->getAs<ReferenceType>())
7228 T = RT->getPointeeType();
7229
7230 if (T->isObjCObjectType()) {
7231 Diag(Loc, diag::err_objc_object_catch);
7232 Invalid = true;
7233 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00007234 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00007235 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
7236 Invalid = true;
7237 }
7238 }
7239 }
7240
Abramo Bagnaradff19302011-03-08 08:55:46 +00007241 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
7242 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00007243 ExDecl->setExceptionVariable(true);
7244
Douglas Gregor6de584c2010-03-05 23:38:39 +00007245 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00007246 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00007247 // C++ [except.handle]p16:
7248 // The object declared in an exception-declaration or, if the
7249 // exception-declaration does not specify a name, a temporary (12.2) is
7250 // copy-initialized (8.5) from the exception object. [...]
7251 // The object is destroyed when the handler exits, after the destruction
7252 // of any automatic objects initialized within the handler.
7253 //
7254 // We just pretend to initialize the object with itself, then make sure
7255 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00007256 QualType initType = ExDeclType;
7257
7258 InitializedEntity entity =
7259 InitializedEntity::InitializeVariable(ExDecl);
7260 InitializationKind initKind =
7261 InitializationKind::CreateCopy(Loc, SourceLocation());
7262
7263 Expr *opaqueValue =
7264 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
7265 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
7266 ExprResult result = sequence.Perform(*this, entity, initKind,
7267 MultiExprArg(&opaqueValue, 1));
7268 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00007269 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00007270 else {
7271 // If the constructor used was non-trivial, set this as the
7272 // "initializer".
7273 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
7274 if (!construct->getConstructor()->isTrivial()) {
7275 Expr *init = MaybeCreateExprWithCleanups(construct);
7276 ExDecl->setInit(init);
7277 }
7278
7279 // And make sure it's destructable.
7280 FinalizeVarWithDestructor(ExDecl, recordType);
7281 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00007282 }
7283 }
7284
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007285 if (Invalid)
7286 ExDecl->setInvalidDecl();
7287
7288 return ExDecl;
7289}
7290
7291/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
7292/// handler.
John McCall48871652010-08-21 09:40:31 +00007293Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00007294 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00007295 bool Invalid = D.isInvalidType();
7296
7297 // Check for unexpanded parameter packs.
7298 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7299 UPPC_ExceptionType)) {
7300 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7301 D.getIdentifierLoc());
7302 Invalid = true;
7303 }
7304
Sebastian Redl54c04d42008-12-22 19:15:10 +00007305 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00007306 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00007307 LookupOrdinaryName,
7308 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007309 // The scope should be freshly made just for us. There is just no way
7310 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00007311 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00007312 if (PrevDecl->isTemplateParameter()) {
7313 // Maybe we will complain about the shadowed template parameter.
7314 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00007315 }
7316 }
7317
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007318 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007319 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
7320 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007321 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007322 }
7323
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007324 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007325 D.getSourceRange().getBegin(),
7326 D.getIdentifierLoc(),
7327 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007328 if (Invalid)
7329 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00007330
Sebastian Redl54c04d42008-12-22 19:15:10 +00007331 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00007332 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007333 PushOnScopeChains(ExDecl, S);
7334 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007335 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00007336
Douglas Gregor758a8692009-06-17 21:51:59 +00007337 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00007338 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007339}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007340
Abramo Bagnaraea947882011-03-08 16:41:52 +00007341Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00007342 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007343 Expr *AssertMessageExpr_,
7344 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00007345 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007346
Anders Carlsson54b26982009-03-14 00:33:21 +00007347 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7348 llvm::APSInt Value(32);
7349 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00007350 Diag(StaticAssertLoc,
7351 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00007352 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007353 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00007354 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007355
Anders Carlsson54b26982009-03-14 00:33:21 +00007356 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00007357 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00007358 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00007359 }
7360 }
Mike Stump11289f42009-09-09 15:08:12 +00007361
Douglas Gregoref68fee2010-12-15 23:55:21 +00007362 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7363 return 0;
7364
Abramo Bagnaraea947882011-03-08 16:41:52 +00007365 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7366 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00007367
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007368 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00007369 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007370}
Sebastian Redlf769df52009-03-24 22:27:57 +00007371
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007372/// \brief Perform semantic analysis of the given friend type declaration.
7373///
7374/// \returns A friend declaration that.
7375FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7376 TypeSourceInfo *TSInfo) {
7377 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7378
7379 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007380 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007381
Douglas Gregor3b4abb62010-04-07 17:57:12 +00007382 if (!getLangOptions().CPlusPlus0x) {
7383 // C++03 [class.friend]p2:
7384 // An elaborated-type-specifier shall be used in a friend declaration
7385 // for a class.*
7386 //
7387 // * The class-key of the elaborated-type-specifier is required.
7388 if (!ActiveTemplateInstantiations.empty()) {
7389 // Do not complain about the form of friend template types during
7390 // template instantiation; we will already have complained when the
7391 // template was declared.
7392 } else if (!T->isElaboratedTypeSpecifier()) {
7393 // If we evaluated the type to a record type, suggest putting
7394 // a tag in front.
7395 if (const RecordType *RT = T->getAs<RecordType>()) {
7396 RecordDecl *RD = RT->getDecl();
7397
7398 std::string InsertionText = std::string(" ") + RD->getKindName();
7399
7400 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7401 << (unsigned) RD->getTagKind()
7402 << T
7403 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7404 InsertionText);
7405 } else {
7406 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7407 << T
7408 << SourceRange(FriendLoc, TypeRange.getEnd());
7409 }
7410 } else if (T->getAs<EnumType>()) {
7411 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007412 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007413 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007414 }
7415 }
7416
Douglas Gregor3b4abb62010-04-07 17:57:12 +00007417 // C++0x [class.friend]p3:
7418 // If the type specifier in a friend declaration designates a (possibly
7419 // cv-qualified) class type, that class is declared as a friend; otherwise,
7420 // the friend declaration is ignored.
7421
7422 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7423 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007424
7425 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7426}
7427
John McCallace48cd2010-10-19 01:40:49 +00007428/// Handle a friend tag declaration where the scope specifier was
7429/// templated.
7430Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7431 unsigned TagSpec, SourceLocation TagLoc,
7432 CXXScopeSpec &SS,
7433 IdentifierInfo *Name, SourceLocation NameLoc,
7434 AttributeList *Attr,
7435 MultiTemplateParamsArg TempParamLists) {
7436 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7437
7438 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00007439 bool Invalid = false;
7440
7441 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00007442 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00007443 TempParamLists.get(),
7444 TempParamLists.size(),
7445 /*friend*/ true,
7446 isExplicitSpecialization,
7447 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00007448 if (TemplateParams->size() > 0) {
7449 // This is a declaration of a class template.
7450 if (Invalid)
7451 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007452
John McCallace48cd2010-10-19 01:40:49 +00007453 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7454 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007455 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007456 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007457 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00007458 } else {
7459 // The "template<>" header is extraneous.
7460 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7461 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7462 isExplicitSpecialization = true;
7463 }
7464 }
7465
7466 if (Invalid) return 0;
7467
7468 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7469
7470 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007471 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00007472 if (TempParamLists.get()[I]->size()) {
7473 isAllExplicitSpecializations = false;
7474 break;
7475 }
7476 }
7477
7478 // FIXME: don't ignore attributes.
7479
7480 // If it's explicit specializations all the way down, just forget
7481 // about the template header and build an appropriate non-templated
7482 // friend. TODO: for source fidelity, remember the headers.
7483 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007484 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00007485 ElaboratedTypeKeyword Keyword
7486 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007487 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007488 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00007489 if (T.isNull())
7490 return 0;
7491
7492 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7493 if (isa<DependentNameType>(T)) {
7494 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7495 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007496 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007497 TL.setNameLoc(NameLoc);
7498 } else {
7499 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7500 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007501 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007502 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7503 }
7504
7505 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7506 TSI, FriendLoc);
7507 Friend->setAccess(AS_public);
7508 CurContext->addDecl(Friend);
7509 return Friend;
7510 }
7511
7512 // Handle the case of a templated-scope friend class. e.g.
7513 // template <class T> class A<T>::B;
7514 // FIXME: we don't support these right now.
7515 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7516 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7517 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7518 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7519 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007520 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00007521 TL.setNameLoc(NameLoc);
7522
7523 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7524 TSI, FriendLoc);
7525 Friend->setAccess(AS_public);
7526 Friend->setUnsupportedFriend(true);
7527 CurContext->addDecl(Friend);
7528 return Friend;
7529}
7530
7531
John McCall11083da2009-09-16 22:47:08 +00007532/// Handle a friend type declaration. This works in tandem with
7533/// ActOnTag.
7534///
7535/// Notes on friend class templates:
7536///
7537/// We generally treat friend class declarations as if they were
7538/// declaring a class. So, for example, the elaborated type specifier
7539/// in a friend declaration is required to obey the restrictions of a
7540/// class-head (i.e. no typedefs in the scope chain), template
7541/// parameters are required to match up with simple template-ids, &c.
7542/// However, unlike when declaring a template specialization, it's
7543/// okay to refer to a template specialization without an empty
7544/// template parameter declaration, e.g.
7545/// friend class A<T>::B<unsigned>;
7546/// We permit this as a special case; if there are any template
7547/// parameters present at all, require proper matching, i.e.
7548/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00007549Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00007550 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007551 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00007552
7553 assert(DS.isFriendSpecified());
7554 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7555
John McCall11083da2009-09-16 22:47:08 +00007556 // Try to convert the decl specifier to a type. This works for
7557 // friend templates because ActOnTag never produces a ClassTemplateDecl
7558 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00007559 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00007560 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7561 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00007562 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00007563 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007564
Douglas Gregor6c110f32010-12-16 01:14:37 +00007565 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7566 return 0;
7567
John McCall11083da2009-09-16 22:47:08 +00007568 // This is definitely an error in C++98. It's probably meant to
7569 // be forbidden in C++0x, too, but the specification is just
7570 // poorly written.
7571 //
7572 // The problem is with declarations like the following:
7573 // template <T> friend A<T>::foo;
7574 // where deciding whether a class C is a friend or not now hinges
7575 // on whether there exists an instantiation of A that causes
7576 // 'foo' to equal C. There are restrictions on class-heads
7577 // (which we declare (by fiat) elaborated friend declarations to
7578 // be) that makes this tractable.
7579 //
7580 // FIXME: handle "template <> friend class A<T>;", which
7581 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00007582 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00007583 Diag(Loc, diag::err_tagless_friend_type_template)
7584 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007585 return 0;
John McCall11083da2009-09-16 22:47:08 +00007586 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007587
John McCallaa74a0c2009-08-28 07:59:38 +00007588 // C++98 [class.friend]p1: A friend of a class is a function
7589 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00007590 // This is fixed in DR77, which just barely didn't make the C++03
7591 // deadline. It's also a very silly restriction that seriously
7592 // affects inner classes and which nobody else seems to implement;
7593 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00007594 //
7595 // But note that we could warn about it: it's always useless to
7596 // friend one of your own members (it's not, however, worthless to
7597 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00007598
John McCall11083da2009-09-16 22:47:08 +00007599 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007600 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00007601 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007602 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00007603 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00007604 TSI,
John McCall11083da2009-09-16 22:47:08 +00007605 DS.getFriendSpecLoc());
7606 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007607 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7608
7609 if (!D)
John McCall48871652010-08-21 09:40:31 +00007610 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007611
John McCall11083da2009-09-16 22:47:08 +00007612 D->setAccess(AS_public);
7613 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00007614
John McCall48871652010-08-21 09:40:31 +00007615 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00007616}
7617
John McCallde3fd222010-10-12 23:13:28 +00007618Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7619 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007620 const DeclSpec &DS = D.getDeclSpec();
7621
7622 assert(DS.isFriendSpecified());
7623 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7624
7625 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00007626 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7627 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00007628
7629 // C++ [class.friend]p1
7630 // A friend of a class is a function or class....
7631 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00007632 // It *doesn't* see through dependent types, which is correct
7633 // according to [temp.arg.type]p3:
7634 // If a declaration acquires a function type through a
7635 // type dependent on a template-parameter and this causes
7636 // a declaration that does not use the syntactic form of a
7637 // function declarator to have a function type, the program
7638 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00007639 if (!T->isFunctionType()) {
7640 Diag(Loc, diag::err_unexpected_friend);
7641
7642 // It might be worthwhile to try to recover by creating an
7643 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00007644 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007645 }
7646
7647 // C++ [namespace.memdef]p3
7648 // - If a friend declaration in a non-local class first declares a
7649 // class or function, the friend class or function is a member
7650 // of the innermost enclosing namespace.
7651 // - The name of the friend is not found by simple name lookup
7652 // until a matching declaration is provided in that namespace
7653 // scope (either before or after the class declaration granting
7654 // friendship).
7655 // - If a friend function is called, its name may be found by the
7656 // name lookup that considers functions from namespaces and
7657 // classes associated with the types of the function arguments.
7658 // - When looking for a prior declaration of a class or a function
7659 // declared as a friend, scopes outside the innermost enclosing
7660 // namespace scope are not considered.
7661
John McCallde3fd222010-10-12 23:13:28 +00007662 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007663 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7664 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00007665 assert(Name);
7666
Douglas Gregor6c110f32010-12-16 01:14:37 +00007667 // Check for unexpanded parameter packs.
7668 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7669 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7670 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7671 return 0;
7672
John McCall07e91c02009-08-06 02:15:43 +00007673 // The context we found the declaration in, or in which we should
7674 // create the declaration.
7675 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00007676 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007677 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00007678 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00007679
John McCallde3fd222010-10-12 23:13:28 +00007680 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00007681
John McCallde3fd222010-10-12 23:13:28 +00007682 // There are four cases here.
7683 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00007684 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00007685 // there as appropriate.
7686 // Recover from invalid scope qualifiers as if they just weren't there.
7687 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00007688 // C++0x [namespace.memdef]p3:
7689 // If the name in a friend declaration is neither qualified nor
7690 // a template-id and the declaration is a function or an
7691 // elaborated-type-specifier, the lookup to determine whether
7692 // the entity has been previously declared shall not consider
7693 // any scopes outside the innermost enclosing namespace.
7694 // C++0x [class.friend]p11:
7695 // If a friend declaration appears in a local class and the name
7696 // specified is an unqualified name, a prior declaration is
7697 // looked up without considering scopes that are outside the
7698 // innermost enclosing non-class scope. For a friend function
7699 // declaration, if there is no prior declaration, the program is
7700 // ill-formed.
7701 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00007702 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00007703
John McCallf7cfb222010-10-13 05:45:15 +00007704 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00007705 DC = CurContext;
7706 while (true) {
7707 // Skip class contexts. If someone can cite chapter and verse
7708 // for this behavior, that would be nice --- it's what GCC and
7709 // EDG do, and it seems like a reasonable intent, but the spec
7710 // really only says that checks for unqualified existing
7711 // declarations should stop at the nearest enclosing namespace,
7712 // not that they should only consider the nearest enclosing
7713 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007714 while (DC->isRecord())
7715 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00007716
John McCall1f82f242009-11-18 22:49:29 +00007717 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00007718
7719 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00007720 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00007721 break;
John McCallf7cfb222010-10-13 05:45:15 +00007722
John McCallf4776592010-10-14 22:22:28 +00007723 if (isTemplateId) {
7724 if (isa<TranslationUnitDecl>(DC)) break;
7725 } else {
7726 if (DC->isFileContext()) break;
7727 }
John McCall07e91c02009-08-06 02:15:43 +00007728 DC = DC->getParent();
7729 }
7730
7731 // C++ [class.friend]p1: A friend of a class is a function or
7732 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00007733 // C++0x changes this for both friend types and functions.
7734 // Most C++ 98 compilers do seem to give an error here, so
7735 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00007736 if (!Previous.empty() && DC->Equals(CurContext)
7737 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00007738 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00007739
John McCallccbc0322010-10-13 06:22:15 +00007740 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00007741
John McCallde3fd222010-10-12 23:13:28 +00007742 // - There's a non-dependent scope specifier, in which case we
7743 // compute it and do a previous lookup there for a function
7744 // or function template.
7745 } else if (!SS.getScopeRep()->isDependent()) {
7746 DC = computeDeclContext(SS);
7747 if (!DC) return 0;
7748
7749 if (RequireCompleteDeclContext(SS, DC)) return 0;
7750
7751 LookupQualifiedName(Previous, DC);
7752
7753 // Ignore things found implicitly in the wrong scope.
7754 // TODO: better diagnostics for this case. Suggesting the right
7755 // qualified scope would be nice...
7756 LookupResult::Filter F = Previous.makeFilter();
7757 while (F.hasNext()) {
7758 NamedDecl *D = F.next();
7759 if (!DC->InEnclosingNamespaceSetOf(
7760 D->getDeclContext()->getRedeclContext()))
7761 F.erase();
7762 }
7763 F.done();
7764
7765 if (Previous.empty()) {
7766 D.setInvalidType();
7767 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7768 return 0;
7769 }
7770
7771 // C++ [class.friend]p1: A friend of a class is a function or
7772 // class that is not a member of the class . . .
7773 if (DC->Equals(CurContext))
7774 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7775
7776 // - There's a scope specifier that does not match any template
7777 // parameter lists, in which case we use some arbitrary context,
7778 // create a method or method template, and wait for instantiation.
7779 // - There's a scope specifier that does match some template
7780 // parameter lists, which we don't handle right now.
7781 } else {
7782 DC = CurContext;
7783 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00007784 }
7785
John McCallf7cfb222010-10-13 05:45:15 +00007786 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00007787 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00007788 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7789 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7790 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00007791 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00007792 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7793 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00007794 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007795 }
John McCall07e91c02009-08-06 02:15:43 +00007796 }
7797
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007798 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00007799 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007800 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00007801 IsDefinition,
7802 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00007803 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00007804
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007805 assert(ND->getDeclContext() == DC);
7806 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00007807
John McCall759e32b2009-08-31 22:39:49 +00007808 // Add the function declaration to the appropriate lookup tables,
7809 // adjusting the redeclarations list as necessary. We don't
7810 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00007811 //
John McCall759e32b2009-08-31 22:39:49 +00007812 // Also update the scope-based lookup if the target context's
7813 // lookup context is in lexical scope.
7814 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007815 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007816 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007817 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007818 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007819 }
John McCallaa74a0c2009-08-28 07:59:38 +00007820
7821 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007822 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00007823 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00007824 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00007825 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00007826
John McCallde3fd222010-10-12 23:13:28 +00007827 if (ND->isInvalidDecl())
7828 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00007829 else {
7830 FunctionDecl *FD;
7831 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7832 FD = FTD->getTemplatedDecl();
7833 else
7834 FD = cast<FunctionDecl>(ND);
7835
7836 // Mark templated-scope function declarations as unsupported.
7837 if (FD->getNumTemplateParameterLists())
7838 FrD->setUnsupportedFriend(true);
7839 }
John McCallde3fd222010-10-12 23:13:28 +00007840
John McCall48871652010-08-21 09:40:31 +00007841 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00007842}
7843
John McCall48871652010-08-21 09:40:31 +00007844void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7845 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00007846
Sebastian Redlf769df52009-03-24 22:27:57 +00007847 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7848 if (!Fn) {
7849 Diag(DelLoc, diag::err_deleted_non_function);
7850 return;
7851 }
7852 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7853 Diag(DelLoc, diag::err_deleted_decl_not_first);
7854 Diag(Prev->getLocation(), diag::note_previous_declaration);
7855 // If the declaration wasn't the first, we delete the function anyway for
7856 // recovery.
7857 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007858 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00007859}
Sebastian Redl4c018662009-04-27 21:33:24 +00007860
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007861void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
7862 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
7863
7864 if (MD) {
7865 CXXSpecialMember Member = getSpecialMember(MD);
7866 if (Member == CXXInvalid) {
7867 Diag(DefaultLoc, diag::err_default_special_members);
7868 return;
7869 }
7870
7871 MD->setDefaulted();
7872 MD->setExplicitlyDefaulted();
7873
7874 // We'll check it when the record is done
7875 if (MD == MD->getCanonicalDecl())
7876 return;
7877
7878 switch (Member) {
7879 case CXXDefaultConstructor: {
7880 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
7881 CheckExplicitlyDefaultedDefaultConstructor(CD);
7882 DefineImplicitDefaultConstructor(DefaultLoc, CD);
7883 break;
7884 }
7885 default:
7886 // FIXME: Do the rest once we have functions
7887 break;
7888 }
7889 } else {
7890 Diag(DefaultLoc, diag::err_default_special_members);
7891 }
7892}
7893
Sebastian Redl4c018662009-04-27 21:33:24 +00007894static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00007895 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00007896 Stmt *SubStmt = *CI;
7897 if (!SubStmt)
7898 continue;
7899 if (isa<ReturnStmt>(SubStmt))
7900 Self.Diag(SubStmt->getSourceRange().getBegin(),
7901 diag::err_return_in_constructor_handler);
7902 if (!isa<Expr>(SubStmt))
7903 SearchForReturnInStmt(Self, SubStmt);
7904 }
7905}
7906
7907void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7908 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7909 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7910 SearchForReturnInStmt(*this, Handler);
7911 }
7912}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007913
Mike Stump11289f42009-09-09 15:08:12 +00007914bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007915 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00007916 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7917 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007918
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007919 if (Context.hasSameType(NewTy, OldTy) ||
7920 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007921 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007922
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007923 // Check if the return types are covariant
7924 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007925
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007926 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007927 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7928 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007929 NewClassTy = NewPT->getPointeeType();
7930 OldClassTy = OldPT->getPointeeType();
7931 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007932 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7933 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7934 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7935 NewClassTy = NewRT->getPointeeType();
7936 OldClassTy = OldRT->getPointeeType();
7937 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007938 }
7939 }
Mike Stump11289f42009-09-09 15:08:12 +00007940
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007941 // The return types aren't either both pointers or references to a class type.
7942 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007943 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007944 diag::err_different_return_type_for_overriding_virtual_function)
7945 << New->getDeclName() << NewTy << OldTy;
7946 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007947
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007948 return true;
7949 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007950
Anders Carlssone60365b2009-12-31 18:34:24 +00007951 // C++ [class.virtual]p6:
7952 // If the return type of D::f differs from the return type of B::f, the
7953 // class type in the return type of D::f shall be complete at the point of
7954 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007955 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7956 if (!RT->isBeingDefined() &&
7957 RequireCompleteType(New->getLocation(), NewClassTy,
7958 PDiag(diag::err_covariant_return_incomplete)
7959 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007960 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007961 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007962
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007963 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007964 // Check if the new class derives from the old class.
7965 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7966 Diag(New->getLocation(),
7967 diag::err_covariant_return_not_derived)
7968 << New->getDeclName() << NewTy << OldTy;
7969 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7970 return true;
7971 }
Mike Stump11289f42009-09-09 15:08:12 +00007972
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007973 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007974 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007975 diag::err_covariant_return_inaccessible_base,
7976 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7977 // FIXME: Should this point to the return type?
7978 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00007979 // FIXME: this note won't trigger for delayed access control
7980 // diagnostics, and it's impossible to get an undelayed error
7981 // here from access control during the original parse because
7982 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007983 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7984 return true;
7985 }
7986 }
Mike Stump11289f42009-09-09 15:08:12 +00007987
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007988 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007989 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007990 Diag(New->getLocation(),
7991 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007992 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007993 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7994 return true;
7995 };
Mike Stump11289f42009-09-09 15:08:12 +00007996
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007997
7998 // The new class type must have the same or less qualifiers as the old type.
7999 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8000 Diag(New->getLocation(),
8001 diag::err_covariant_return_type_class_type_more_qualified)
8002 << New->getDeclName() << NewTy << OldTy;
8003 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8004 return true;
8005 };
Mike Stump11289f42009-09-09 15:08:12 +00008006
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008007 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008008}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008009
Douglas Gregor21920e372009-12-01 17:24:26 +00008010/// \brief Mark the given method pure.
8011///
8012/// \param Method the method to be marked pure.
8013///
8014/// \param InitRange the source range that covers the "0" initializer.
8015bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008016 SourceLocation EndLoc = InitRange.getEnd();
8017 if (EndLoc.isValid())
8018 Method->setRangeEnd(EndLoc);
8019
Douglas Gregor21920e372009-12-01 17:24:26 +00008020 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8021 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00008022 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008023 }
Douglas Gregor21920e372009-12-01 17:24:26 +00008024
8025 if (!Method->isInvalidDecl())
8026 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8027 << Method->getDeclName() << InitRange;
8028 return true;
8029}
8030
John McCall1f4ee7b2009-12-19 09:28:58 +00008031/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8032/// an initializer for the out-of-line declaration 'Dcl'. The scope
8033/// is a fresh scope pushed for just this purpose.
8034///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008035/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8036/// static data member of class X, names should be looked up in the scope of
8037/// class X.
John McCall48871652010-08-21 09:40:31 +00008038void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008039 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008040 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008041
John McCall1f4ee7b2009-12-19 09:28:58 +00008042 // We should only get called for declarations with scope specifiers, like:
8043 // int foo::bar;
8044 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008045 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008046}
8047
8048/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00008049/// initializer for the out-of-line declaration 'D'.
8050void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008051 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008052 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008053
John McCall1f4ee7b2009-12-19 09:28:58 +00008054 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008055 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008056}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008057
8058/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8059/// C++ if/switch/while/for statement.
8060/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00008061DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008062 // C++ 6.4p2:
8063 // The declarator shall not specify a function or an array.
8064 // The type-specifier-seq shall not contain typedef and shall not declare a
8065 // new class or enumeration.
8066 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8067 "Parser allowed 'typedef' as storage class of condition decl.");
8068
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008069 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00008070 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
8071 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008072
8073 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
8074 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
8075 // would be created and CXXConditionDeclExpr wants a VarDecl.
8076 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
8077 << D.getSourceRange();
8078 return DeclResult();
8079 } else if (OwnedTag && OwnedTag->isDefinition()) {
8080 // The type-specifier-seq shall not declare a new class or enumeration.
8081 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
8082 }
8083
John McCall48871652010-08-21 09:40:31 +00008084 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008085 if (!Dcl)
8086 return DeclResult();
8087
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008088 return Dcl;
8089}
Anders Carlssonf98849e2009-12-02 17:15:43 +00008090
Douglas Gregor88d292c2010-05-13 16:44:06 +00008091void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8092 bool DefinitionRequired) {
8093 // Ignore any vtable uses in unevaluated operands or for classes that do
8094 // not have a vtable.
8095 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8096 CurContext->isDependentContext() ||
8097 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00008098 return;
8099
Douglas Gregor88d292c2010-05-13 16:44:06 +00008100 // Try to insert this class into the map.
8101 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8102 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8103 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8104 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00008105 // If we already had an entry, check to see if we are promoting this vtable
8106 // to required a definition. If so, we need to reappend to the VTableUses
8107 // list, since we may have already processed the first entry.
8108 if (DefinitionRequired && !Pos.first->second) {
8109 Pos.first->second = true;
8110 } else {
8111 // Otherwise, we can early exit.
8112 return;
8113 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008114 }
8115
8116 // Local classes need to have their virtual members marked
8117 // immediately. For all other classes, we mark their virtual members
8118 // at the end of the translation unit.
8119 if (Class->isLocalClass())
8120 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00008121 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00008122 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00008123}
8124
Douglas Gregor88d292c2010-05-13 16:44:06 +00008125bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008126 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00008127 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00008128
Douglas Gregor88d292c2010-05-13 16:44:06 +00008129 // Note: The VTableUses vector could grow as a result of marking
8130 // the members of a class as "used", so we check the size each
8131 // time through the loop and prefer indices (with are stable) to
8132 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00008133 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00008134 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00008135 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00008136 if (!Class)
8137 continue;
8138
8139 SourceLocation Loc = VTableUses[I].second;
8140
8141 // If this class has a key function, but that key function is
8142 // defined in another translation unit, we don't need to emit the
8143 // vtable even though we're using it.
8144 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00008145 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008146 switch (KeyFunction->getTemplateSpecializationKind()) {
8147 case TSK_Undeclared:
8148 case TSK_ExplicitSpecialization:
8149 case TSK_ExplicitInstantiationDeclaration:
8150 // The key function is in another translation unit.
8151 continue;
8152
8153 case TSK_ExplicitInstantiationDefinition:
8154 case TSK_ImplicitInstantiation:
8155 // We will be instantiating the key function.
8156 break;
8157 }
8158 } else if (!KeyFunction) {
8159 // If we have a class with no key function that is the subject
8160 // of an explicit instantiation declaration, suppress the
8161 // vtable; it will live with the explicit instantiation
8162 // definition.
8163 bool IsExplicitInstantiationDeclaration
8164 = Class->getTemplateSpecializationKind()
8165 == TSK_ExplicitInstantiationDeclaration;
8166 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
8167 REnd = Class->redecls_end();
8168 R != REnd; ++R) {
8169 TemplateSpecializationKind TSK
8170 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
8171 if (TSK == TSK_ExplicitInstantiationDeclaration)
8172 IsExplicitInstantiationDeclaration = true;
8173 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8174 IsExplicitInstantiationDeclaration = false;
8175 break;
8176 }
8177 }
8178
8179 if (IsExplicitInstantiationDeclaration)
8180 continue;
8181 }
8182
8183 // Mark all of the virtual members of this class as referenced, so
8184 // that we can build a vtable. Then, tell the AST consumer that a
8185 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00008186 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00008187 MarkVirtualMembersReferenced(Loc, Class);
8188 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8189 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
8190
8191 // Optionally warn if we're emitting a weak vtable.
8192 if (Class->getLinkage() == ExternalLinkage &&
8193 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00008194 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00008195 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
8196 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00008197 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008198 VTableUses.clear();
8199
Douglas Gregor97509692011-04-22 22:25:37 +00008200 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00008201}
Anders Carlsson82fccd02009-12-07 08:24:59 +00008202
Rafael Espindola5b334082010-03-26 00:36:59 +00008203void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
8204 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00008205 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
8206 e = RD->method_end(); i != e; ++i) {
8207 CXXMethodDecl *MD = *i;
8208
8209 // C++ [basic.def.odr]p2:
8210 // [...] A virtual member function is used if it is not pure. [...]
8211 if (MD->isVirtual() && !MD->isPure())
8212 MarkDeclarationReferenced(Loc, MD);
8213 }
Rafael Espindola5b334082010-03-26 00:36:59 +00008214
8215 // Only classes that have virtual bases need a VTT.
8216 if (RD->getNumVBases() == 0)
8217 return;
8218
8219 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
8220 e = RD->bases_end(); i != e; ++i) {
8221 const CXXRecordDecl *Base =
8222 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00008223 if (Base->getNumVBases() == 0)
8224 continue;
8225 MarkVirtualMembersReferenced(Loc, Base);
8226 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00008227}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008228
8229/// SetIvarInitializers - This routine builds initialization ASTs for the
8230/// Objective-C implementation whose ivars need be initialized.
8231void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
8232 if (!getLangOptions().CPlusPlus)
8233 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00008234 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008235 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
8236 CollectIvarsToConstructOrDestruct(OID, ivars);
8237 if (ivars.empty())
8238 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00008239 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008240 for (unsigned i = 0; i < ivars.size(); i++) {
8241 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00008242 if (Field->isInvalidDecl())
8243 continue;
8244
Alexis Hunt1d792652011-01-08 20:30:50 +00008245 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008246 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
8247 InitializationKind InitKind =
8248 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
8249
8250 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00008251 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00008252 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00008253 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008254 // Note, MemberInit could actually come back empty if no initialization
8255 // is required (e.g., because it would call a trivial default constructor)
8256 if (!MemberInit.get() || MemberInit.isInvalid())
8257 continue;
John McCallacf0ee52010-10-08 02:01:28 +00008258
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008259 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00008260 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
8261 SourceLocation(),
8262 MemberInit.takeAs<Expr>(),
8263 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008264 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00008265
8266 // Be sure that the destructor is accessible and is marked as referenced.
8267 if (const RecordType *RecordTy
8268 = Context.getBaseElementType(Field->getType())
8269 ->getAs<RecordType>()) {
8270 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00008271 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00008272 MarkDeclarationReferenced(Field->getLocation(), Destructor);
8273 CheckDestructorAccess(Field->getLocation(), Destructor,
8274 PDiag(diag::err_access_dtor_ivar)
8275 << Context.getBaseElementType(Field->getType()));
8276 }
8277 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008278 }
8279 ObjCImplementation->setIvarInitializers(Context,
8280 AllToInit.data(), AllToInit.size());
8281 }
8282}
Alexis Hunt6118d662011-05-04 05:57:24 +00008283
Alexis Hunt27a761d2011-05-04 23:29:54 +00008284static
8285void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
8286 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
8287 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
8288 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
8289 Sema &S) {
8290 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8291 CE = Current.end();
8292 if (Ctor->isInvalidDecl())
8293 return;
8294
8295 const FunctionDecl *FNTarget = 0;
8296 CXXConstructorDecl *Target;
8297
8298 // We ignore the result here since if we don't have a body, Target will be
8299 // null below.
8300 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
8301 Target
8302= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
8303
8304 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
8305 // Avoid dereferencing a null pointer here.
8306 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
8307
8308 if (!Current.insert(Canonical))
8309 return;
8310
8311 // We know that beyond here, we aren't chaining into a cycle.
8312 if (!Target || !Target->isDelegatingConstructor() ||
8313 Target->isInvalidDecl() || Valid.count(TCanonical)) {
8314 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8315 Valid.insert(*CI);
8316 Current.clear();
8317 // We've hit a cycle.
8318 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
8319 Current.count(TCanonical)) {
8320 // If we haven't diagnosed this cycle yet, do so now.
8321 if (!Invalid.count(TCanonical)) {
8322 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00008323 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00008324 << Ctor;
8325
8326 // Don't add a note for a function delegating directo to itself.
8327 if (TCanonical != Canonical)
8328 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
8329
8330 CXXConstructorDecl *C = Target;
8331 while (C->getCanonicalDecl() != Canonical) {
8332 (void)C->getTargetConstructor()->hasBody(FNTarget);
8333 assert(FNTarget && "Ctor cycle through bodiless function");
8334
8335 C
8336 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
8337 S.Diag(C->getLocation(), diag::note_which_delegates_to);
8338 }
8339 }
8340
8341 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8342 Invalid.insert(*CI);
8343 Current.clear();
8344 } else {
8345 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
8346 }
8347}
8348
8349
Alexis Hunt6118d662011-05-04 05:57:24 +00008350void Sema::CheckDelegatingCtorCycles() {
8351 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
8352
Alexis Hunt27a761d2011-05-04 23:29:54 +00008353 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8354 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00008355
8356 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00008357 I = DelegatingCtorDecls.begin(),
8358 E = DelegatingCtorDecls.end();
8359 I != E; ++I) {
8360 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00008361 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00008362
8363 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
8364 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00008365}