blob: 81540d34432b69c5b66b3ac80e30cfedc5533765 [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,
1028 ExprTy *InitExpr, bool IsDefinition,
Alexis Hunt83dc3e82011-05-06 21:24:28 +00001029 bool Deleted, SourceLocation DefaultLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001030 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001031 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1032 DeclarationName Name = NameInfo.getName();
1033 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001034
1035 // For anonymous bitfields, the location should point to the type.
1036 if (Loc.isInvalid())
1037 Loc = D.getSourceRange().getBegin();
1038
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001039 Expr *BitWidth = static_cast<Expr*>(BW);
1040 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001041
John McCallb1cd7da2010-06-04 08:34:12 +00001042 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001043 assert(!DS.isFriendSpecified());
1044
John McCallb1cd7da2010-06-04 08:34:12 +00001045 bool isFunc = false;
1046 if (D.isFunctionDeclarator())
1047 isFunc = true;
1048 else if (D.getNumTypeObjects() == 0 &&
1049 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +00001050 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +00001051 isFunc = TDType->isFunctionType();
1052 }
1053
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001054 // C++ 9.2p6: A member shall not be declared to have automatic storage
1055 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001056 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1057 // data members and cannot be applied to names declared const or static,
1058 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001059 switch (DS.getStorageClassSpec()) {
1060 case DeclSpec::SCS_unspecified:
1061 case DeclSpec::SCS_typedef:
1062 case DeclSpec::SCS_static:
1063 // FALL THROUGH.
1064 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001065 case DeclSpec::SCS_mutable:
1066 if (isFunc) {
1067 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001068 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001069 else
Chris Lattner3b054132008-11-19 05:08:23 +00001070 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001071
Sebastian Redl8071edb2008-11-17 23:24:37 +00001072 // FIXME: It would be nicer if the keyword was ignored only for this
1073 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001074 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001075 }
1076 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001077 default:
1078 if (DS.getStorageClassSpecLoc().isValid())
1079 Diag(DS.getStorageClassSpecLoc(),
1080 diag::err_storageclass_invalid_for_member);
1081 else
1082 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1083 D.getMutableDeclSpec().ClearStorageClassSpecs();
1084 }
1085
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001086 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1087 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001088 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001089
1090 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001091 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001092 CXXScopeSpec &SS = D.getCXXScopeSpec();
1093
Alexis Hunt83dc3e82011-05-06 21:24:28 +00001094 if (DefaultLoc.isValid())
1095 Diag(DefaultLoc, diag::err_default_special_members);
Douglas Gregora007d362010-10-13 22:19:53 +00001096
1097 if (SS.isSet() && !SS.isInvalid()) {
1098 // The user provided a superfluous scope specifier inside a class
1099 // definition:
1100 //
1101 // class X {
1102 // int X::member;
1103 // };
1104 DeclContext *DC = 0;
1105 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1106 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1107 << Name << FixItHint::CreateRemoval(SS.getRange());
1108 else
1109 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1110 << Name << SS.getRange();
1111
1112 SS.clear();
1113 }
1114
Douglas Gregor3447e762009-08-20 22:52:58 +00001115 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001116 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001117 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1118 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001119 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001120 } else {
Alexis Hunt5dafebc2011-05-06 01:42:00 +00001121 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition,
Alexis Hunt83dc3e82011-05-06 21:24:28 +00001122 DefaultLoc);
Chris Lattner97e277e2009-03-05 23:03:49 +00001123 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001124 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001125 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001126
1127 // Non-instance-fields can't have a bitfield.
1128 if (BitWidth) {
1129 if (Member->isInvalidDecl()) {
1130 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001131 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001132 // C++ 9.6p3: A bit-field shall not be a static member.
1133 // "static member 'A' cannot be a bit-field"
1134 Diag(Loc, diag::err_static_not_bitfield)
1135 << Name << BitWidth->getSourceRange();
1136 } else if (isa<TypedefDecl>(Member)) {
1137 // "typedef member 'x' cannot be a bit-field"
1138 Diag(Loc, diag::err_typedef_not_bitfield)
1139 << Name << BitWidth->getSourceRange();
1140 } else {
1141 // A function typedef ("typedef int f(); f a;").
1142 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1143 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001144 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001145 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001146 }
Mike Stump11289f42009-09-09 15:08:12 +00001147
Chris Lattnerd26760a2009-03-05 23:01:03 +00001148 BitWidth = 0;
1149 Member->setInvalidDecl();
1150 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001151
1152 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001153
Douglas Gregor3447e762009-08-20 22:52:58 +00001154 // If we have declared a member function template, set the access of the
1155 // templated declaration as well.
1156 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1157 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001158 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001159
Anders Carlsson13a69102011-01-20 04:34:22 +00001160 if (VS.isOverrideSpecified()) {
1161 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1162 if (!MD || !MD->isVirtual()) {
1163 Diag(Member->getLocStart(),
1164 diag::override_keyword_only_allowed_on_virtual_member_functions)
1165 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001166 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001167 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001168 }
1169 if (VS.isFinalSpecified()) {
1170 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1171 if (!MD || !MD->isVirtual()) {
1172 Diag(Member->getLocStart(),
1173 diag::override_keyword_only_allowed_on_virtual_member_functions)
1174 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001175 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001176 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001177 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001178
Douglas Gregorf2f08062011-03-08 17:10:18 +00001179 if (VS.getLastLocation().isValid()) {
1180 // Update the end location of a method that has a virt-specifiers.
1181 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1182 MD->setRangeEnd(VS.getLastLocation());
1183 }
1184
Anders Carlssonc87f8612011-01-20 06:29:02 +00001185 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001186
Douglas Gregor92751d42008-11-17 22:58:34 +00001187 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001188
Douglas Gregor0c880302009-03-11 23:00:04 +00001189 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001190 AddInitializerToDecl(Member, Init, false,
1191 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001192 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001193 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001194
Richard Smithb2bc2e62011-02-21 20:05:19 +00001195 FinalizeDeclaration(Member);
1196
John McCall25849ca2011-02-15 07:12:36 +00001197 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001198 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001199 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001200}
1201
Douglas Gregor15e77a22009-12-31 09:10:24 +00001202/// \brief Find the direct and/or virtual base specifiers that
1203/// correspond to the given base type, for use in base initialization
1204/// within a constructor.
1205static bool FindBaseInitializer(Sema &SemaRef,
1206 CXXRecordDecl *ClassDecl,
1207 QualType BaseType,
1208 const CXXBaseSpecifier *&DirectBaseSpec,
1209 const CXXBaseSpecifier *&VirtualBaseSpec) {
1210 // First, check for a direct base class.
1211 DirectBaseSpec = 0;
1212 for (CXXRecordDecl::base_class_const_iterator Base
1213 = ClassDecl->bases_begin();
1214 Base != ClassDecl->bases_end(); ++Base) {
1215 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1216 // We found a direct base of this type. That's what we're
1217 // initializing.
1218 DirectBaseSpec = &*Base;
1219 break;
1220 }
1221 }
1222
1223 // Check for a virtual base class.
1224 // FIXME: We might be able to short-circuit this if we know in advance that
1225 // there are no virtual bases.
1226 VirtualBaseSpec = 0;
1227 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1228 // We haven't found a base yet; search the class hierarchy for a
1229 // virtual base class.
1230 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1231 /*DetectVirtual=*/false);
1232 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1233 BaseType, Paths)) {
1234 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1235 Path != Paths.end(); ++Path) {
1236 if (Path->back().Base->isVirtual()) {
1237 VirtualBaseSpec = Path->back().Base;
1238 break;
1239 }
1240 }
1241 }
1242 }
1243
1244 return DirectBaseSpec || VirtualBaseSpec;
1245}
1246
Douglas Gregore8381c02008-11-05 04:29:56 +00001247/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001248MemInitResult
John McCall48871652010-08-21 09:40:31 +00001249Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001250 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001251 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001252 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001253 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001254 SourceLocation IdLoc,
1255 SourceLocation LParenLoc,
1256 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001257 SourceLocation RParenLoc,
1258 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001259 if (!ConstructorD)
1260 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001261
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001262 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001263
1264 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001265 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001266 if (!Constructor) {
1267 // The user wrote a constructor initializer on a function that is
1268 // not a C++ constructor. Ignore the error for now, because we may
1269 // have more member initializers coming; we'll diagnose it just
1270 // once in ActOnMemInitializers.
1271 return true;
1272 }
1273
1274 CXXRecordDecl *ClassDecl = Constructor->getParent();
1275
1276 // C++ [class.base.init]p2:
1277 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001278 // constructor's class and, if not found in that scope, are looked
1279 // up in the scope containing the constructor's definition.
1280 // [Note: if the constructor's class contains a member with the
1281 // same name as a direct or virtual base class of the class, a
1282 // mem-initializer-id naming the member or base class and composed
1283 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001284 // mem-initializer-id for the hidden base class may be specified
1285 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001286 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001287 // Look for a member, first.
1288 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001289 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001290 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001291 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001292 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001293
Douglas Gregor44e7df62011-01-04 00:32:56 +00001294 if (Member) {
1295 if (EllipsisLoc.isValid())
1296 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1297 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1298
Francois Pichetd583da02010-12-04 09:14:42 +00001299 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001300 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001301 }
1302
Francois Pichetd583da02010-12-04 09:14:42 +00001303 // Handle anonymous union case.
1304 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001305 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1306 if (EllipsisLoc.isValid())
1307 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1308 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1309
Francois Pichetd583da02010-12-04 09:14:42 +00001310 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1311 NumArgs, IdLoc,
1312 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001313 }
Francois Pichetd583da02010-12-04 09:14:42 +00001314 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001315 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001316 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001317 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001318 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001319
1320 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001321 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001322 } else {
1323 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1324 LookupParsedName(R, S, &SS);
1325
1326 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1327 if (!TyD) {
1328 if (R.isAmbiguous()) return true;
1329
John McCallda6841b2010-04-09 19:01:14 +00001330 // We don't want access-control diagnostics here.
1331 R.suppressDiagnostics();
1332
Douglas Gregora3b624a2010-01-19 06:46:48 +00001333 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1334 bool NotUnknownSpecialization = false;
1335 DeclContext *DC = computeDeclContext(SS, false);
1336 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1337 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1338
1339 if (!NotUnknownSpecialization) {
1340 // When the scope specifier can refer to a member of an unknown
1341 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001342 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1343 SS.getWithLocInContext(Context),
1344 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001345 if (BaseType.isNull())
1346 return true;
1347
Douglas Gregora3b624a2010-01-19 06:46:48 +00001348 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001349 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001350 }
1351 }
1352
Douglas Gregor15e77a22009-12-31 09:10:24 +00001353 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001354 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001355 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1356 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001357 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001358 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001359 // We have found a non-static data member with a similar
1360 // name to what was typed; complain and initialize that
1361 // member.
1362 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1363 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001364 << FixItHint::CreateReplacement(R.getNameLoc(),
1365 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001366 Diag(Member->getLocation(), diag::note_previous_decl)
1367 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001368
1369 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1370 LParenLoc, RParenLoc);
1371 }
1372 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1373 const CXXBaseSpecifier *DirectBaseSpec;
1374 const CXXBaseSpecifier *VirtualBaseSpec;
1375 if (FindBaseInitializer(*this, ClassDecl,
1376 Context.getTypeDeclType(Type),
1377 DirectBaseSpec, VirtualBaseSpec)) {
1378 // We have found a direct or virtual base class with a
1379 // similar name to what was typed; complain and initialize
1380 // that base class.
1381 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1382 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001383 << FixItHint::CreateReplacement(R.getNameLoc(),
1384 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001385
1386 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1387 : VirtualBaseSpec;
1388 Diag(BaseSpec->getSourceRange().getBegin(),
1389 diag::note_base_class_specified_here)
1390 << BaseSpec->getType()
1391 << BaseSpec->getSourceRange();
1392
Douglas Gregor15e77a22009-12-31 09:10:24 +00001393 TyD = Type;
1394 }
1395 }
1396 }
1397
Douglas Gregora3b624a2010-01-19 06:46:48 +00001398 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001399 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1400 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1401 return true;
1402 }
John McCallb5a0d312009-12-21 10:41:20 +00001403 }
1404
Douglas Gregora3b624a2010-01-19 06:46:48 +00001405 if (BaseType.isNull()) {
1406 BaseType = Context.getTypeDeclType(TyD);
1407 if (SS.isSet()) {
1408 NestedNameSpecifier *Qualifier =
1409 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001410
Douglas Gregora3b624a2010-01-19 06:46:48 +00001411 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001412 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001413 }
John McCallb5a0d312009-12-21 10:41:20 +00001414 }
1415 }
Mike Stump11289f42009-09-09 15:08:12 +00001416
John McCallbcd03502009-12-07 02:54:59 +00001417 if (!TInfo)
1418 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001419
John McCallbcd03502009-12-07 02:54:59 +00001420 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001421 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001422}
1423
John McCalle22a04a2009-11-04 23:02:40 +00001424/// Checks an initializer expression for use of uninitialized fields, such as
1425/// containing the field that is being initialized. Returns true if there is an
1426/// uninitialized field was used an updates the SourceLocation parameter; false
1427/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001428static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001429 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001430 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001431 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1432
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001433 if (isa<CallExpr>(S)) {
1434 // Do not descend into function calls or constructors, as the use
1435 // of an uninitialized field may be valid. One would have to inspect
1436 // the contents of the function/ctor to determine if it is safe or not.
1437 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1438 // may be safe, depending on what the function/ctor does.
1439 return false;
1440 }
1441 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1442 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001443
1444 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1445 // The member expression points to a static data member.
1446 assert(VD->isStaticDataMember() &&
1447 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001448 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001449 return false;
1450 }
1451
1452 if (isa<EnumConstantDecl>(RhsField)) {
1453 // The member expression points to an enum.
1454 return false;
1455 }
1456
John McCalle22a04a2009-11-04 23:02:40 +00001457 if (RhsField == LhsField) {
1458 // Initializing a field with itself. Throw a warning.
1459 // But wait; there are exceptions!
1460 // Exception #1: The field may not belong to this record.
1461 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001462 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001463 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1464 // Even though the field matches, it does not belong to this record.
1465 return false;
1466 }
1467 // None of the exceptions triggered; return true to indicate an
1468 // uninitialized field was used.
1469 *L = ME->getMemberLoc();
1470 return true;
1471 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001472 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001473 // sizeof/alignof doesn't reference contents, do not warn.
1474 return false;
1475 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1476 // address-of doesn't reference contents (the pointer may be dereferenced
1477 // in the same expression but it would be rare; and weird).
1478 if (UOE->getOpcode() == UO_AddrOf)
1479 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001480 }
John McCall8322c3a2011-02-13 04:07:26 +00001481 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001482 if (!*it) {
1483 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001484 continue;
1485 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001486 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1487 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001488 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001489 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001490}
1491
John McCallfaf5fb42010-08-26 23:41:50 +00001492MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001493Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001494 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001495 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001496 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001497 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1498 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1499 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001500 "Member must be a FieldDecl or IndirectFieldDecl");
1501
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001502 if (Member->isInvalidDecl())
1503 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001504
John McCalle22a04a2009-11-04 23:02:40 +00001505 // Diagnose value-uses of fields to initialize themselves, e.g.
1506 // foo(foo)
1507 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001508 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001509 for (unsigned i = 0; i < NumArgs; ++i) {
1510 SourceLocation L;
1511 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1512 // FIXME: Return true in the case when other fields are used before being
1513 // uninitialized. For example, let this field be the i'th field. When
1514 // initializing the i'th field, throw a warning if any of the >= i'th
1515 // fields are used, as they are not yet initialized.
1516 // Right now we are only handling the case where the i'th field uses
1517 // itself in its initializer.
1518 Diag(L, diag::warn_field_is_uninit);
1519 }
1520 }
1521
Eli Friedman8e1433b2009-07-29 19:44:27 +00001522 bool HasDependentArg = false;
1523 for (unsigned i = 0; i < NumArgs; i++)
1524 HasDependentArg |= Args[i]->isTypeDependent();
1525
Chandler Carruthd44c3102010-12-06 09:23:57 +00001526 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001527 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001528 // Can't check initialization for a member of dependent type or when
1529 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001530 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1531 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001532
1533 // Erase any temporaries within this evaluation context; we're not
1534 // going to track them in the AST, since we'll be rebuilding the
1535 // ASTs during template instantiation.
1536 ExprTemporaries.erase(
1537 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1538 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001539 } else {
1540 // Initialize the member.
1541 InitializedEntity MemberEntity =
1542 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1543 : InitializedEntity::InitializeMember(IndirectMember, 0);
1544 InitializationKind Kind =
1545 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001546
Chandler Carruthd44c3102010-12-06 09:23:57 +00001547 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1548
1549 ExprResult MemberInit =
1550 InitSeq.Perform(*this, MemberEntity, Kind,
1551 MultiExprArg(*this, Args, NumArgs), 0);
1552 if (MemberInit.isInvalid())
1553 return true;
1554
1555 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1556
1557 // C++0x [class.base.init]p7:
1558 // The initialization of each base and member constitutes a
1559 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001560 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001561 if (MemberInit.isInvalid())
1562 return true;
1563
1564 // If we are in a dependent context, template instantiation will
1565 // perform this type-checking again. Just save the arguments that we
1566 // received in a ParenListExpr.
1567 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1568 // of the information that we have about the member
1569 // initializer. However, deconstructing the ASTs is a dicey process,
1570 // and this approach is far more likely to get the corner cases right.
1571 if (CurContext->isDependentContext())
1572 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1573 RParenLoc);
1574 else
1575 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001576 }
1577
Chandler Carruthd44c3102010-12-06 09:23:57 +00001578 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001579 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001580 IdLoc, LParenLoc, Init,
1581 RParenLoc);
1582 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001583 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001584 IdLoc, LParenLoc, Init,
1585 RParenLoc);
1586 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001587}
1588
John McCallfaf5fb42010-08-26 23:41:50 +00001589MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001590Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1591 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001592 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001593 SourceLocation LParenLoc,
1594 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001595 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001596 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1597 if (!LangOpts.CPlusPlus0x)
1598 return Diag(Loc, diag::err_delegation_0x_only)
1599 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001600
Alexis Huntc5575cc2011-02-26 19:13:13 +00001601 // Initialize the object.
1602 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1603 QualType(ClassDecl->getTypeForDecl(), 0));
1604 InitializationKind Kind =
1605 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1606
1607 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1608
1609 ExprResult DelegationInit =
1610 InitSeq.Perform(*this, DelegationEntity, Kind,
1611 MultiExprArg(*this, Args, NumArgs), 0);
1612 if (DelegationInit.isInvalid())
1613 return true;
1614
1615 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001616 CXXConstructorDecl *Constructor
1617 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001618 assert(Constructor && "Delegating constructor with no target?");
1619
1620 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1621
1622 // C++0x [class.base.init]p7:
1623 // The initialization of each base and member constitutes a
1624 // full-expression.
1625 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1626 if (DelegationInit.isInvalid())
1627 return true;
1628
1629 // If we are in a dependent context, template instantiation will
1630 // perform this type-checking again. Just save the arguments that we
1631 // received in a ParenListExpr.
1632 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1633 // of the information that we have about the base
1634 // initializer. However, deconstructing the ASTs is a dicey process,
1635 // and this approach is far more likely to get the corner cases right.
1636 if (CurContext->isDependentContext()) {
1637 ExprResult Init
1638 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1639 NumArgs, RParenLoc));
1640 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1641 Constructor, Init.takeAs<Expr>(),
1642 RParenLoc);
1643 }
1644
1645 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1646 DelegationInit.takeAs<Expr>(),
1647 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001648}
1649
1650MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001651Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001652 Expr **Args, unsigned NumArgs,
1653 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001654 CXXRecordDecl *ClassDecl,
1655 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001656 bool HasDependentArg = false;
1657 for (unsigned i = 0; i < NumArgs; i++)
1658 HasDependentArg |= Args[i]->isTypeDependent();
1659
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001660 SourceLocation BaseLoc
1661 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1662
1663 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1664 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1665 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1666
1667 // C++ [class.base.init]p2:
1668 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001669 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001670 // of that class, the mem-initializer is ill-formed. A
1671 // mem-initializer-list can initialize a base class using any
1672 // name that denotes that base class type.
1673 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1674
Douglas Gregor44e7df62011-01-04 00:32:56 +00001675 if (EllipsisLoc.isValid()) {
1676 // This is a pack expansion.
1677 if (!BaseType->containsUnexpandedParameterPack()) {
1678 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1679 << SourceRange(BaseLoc, RParenLoc);
1680
1681 EllipsisLoc = SourceLocation();
1682 }
1683 } else {
1684 // Check for any unexpanded parameter packs.
1685 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1686 return true;
1687
1688 for (unsigned I = 0; I != NumArgs; ++I)
1689 if (DiagnoseUnexpandedParameterPack(Args[I]))
1690 return true;
1691 }
1692
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001693 // Check for direct and virtual base classes.
1694 const CXXBaseSpecifier *DirectBaseSpec = 0;
1695 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1696 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001697 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1698 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001699 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1700 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001701
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001702 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1703 VirtualBaseSpec);
1704
1705 // C++ [base.class.init]p2:
1706 // Unless the mem-initializer-id names a nonstatic data member of the
1707 // constructor's class or a direct or virtual base of that class, the
1708 // mem-initializer is ill-formed.
1709 if (!DirectBaseSpec && !VirtualBaseSpec) {
1710 // If the class has any dependent bases, then it's possible that
1711 // one of those types will resolve to the same type as
1712 // BaseType. Therefore, just treat this as a dependent base
1713 // class initialization. FIXME: Should we try to check the
1714 // initialization anyway? It seems odd.
1715 if (ClassDecl->hasAnyDependentBases())
1716 Dependent = true;
1717 else
1718 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1719 << BaseType << Context.getTypeDeclType(ClassDecl)
1720 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1721 }
1722 }
1723
1724 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001725 // Can't check initialization for a base of dependent type or when
1726 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001727 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001728 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1729 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001730
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001731 // Erase any temporaries within this evaluation context; we're not
1732 // going to track them in the AST, since we'll be rebuilding the
1733 // ASTs during template instantiation.
1734 ExprTemporaries.erase(
1735 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1736 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001737
Alexis Hunt1d792652011-01-08 20:30:50 +00001738 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001739 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001740 LParenLoc,
1741 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001742 RParenLoc,
1743 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001744 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001745
1746 // C++ [base.class.init]p2:
1747 // If a mem-initializer-id is ambiguous because it designates both
1748 // a direct non-virtual base class and an inherited virtual base
1749 // class, the mem-initializer is ill-formed.
1750 if (DirectBaseSpec && VirtualBaseSpec)
1751 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001752 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001753
1754 CXXBaseSpecifier *BaseSpec
1755 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1756 if (!BaseSpec)
1757 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1758
1759 // Initialize the base.
1760 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001761 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001762 InitializationKind Kind =
1763 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1764
1765 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1766
John McCalldadc5752010-08-24 06:29:42 +00001767 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001768 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001769 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001770 if (BaseInit.isInvalid())
1771 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001772
1773 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001774
1775 // C++0x [class.base.init]p7:
1776 // The initialization of each base and member constitutes a
1777 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001778 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001779 if (BaseInit.isInvalid())
1780 return true;
1781
1782 // If we are in a dependent context, template instantiation will
1783 // perform this type-checking again. Just save the arguments that we
1784 // received in a ParenListExpr.
1785 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1786 // of the information that we have about the base
1787 // initializer. However, deconstructing the ASTs is a dicey process,
1788 // and this approach is far more likely to get the corner cases right.
1789 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001790 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001791 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1792 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001793 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001794 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001795 LParenLoc,
1796 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001797 RParenLoc,
1798 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001799 }
1800
Alexis Hunt1d792652011-01-08 20:30:50 +00001801 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001802 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001803 LParenLoc,
1804 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001805 RParenLoc,
1806 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001807}
1808
Anders Carlsson1b00e242010-04-23 03:10:23 +00001809/// ImplicitInitializerKind - How an implicit base or member initializer should
1810/// initialize its base or member.
1811enum ImplicitInitializerKind {
1812 IIK_Default,
1813 IIK_Copy,
1814 IIK_Move
1815};
1816
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001817static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001818BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001819 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001820 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001821 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001822 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001823 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001824 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1825 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001826
John McCalldadc5752010-08-24 06:29:42 +00001827 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001828
1829 switch (ImplicitInitKind) {
1830 case IIK_Default: {
1831 InitializationKind InitKind
1832 = InitializationKind::CreateDefault(Constructor->getLocation());
1833 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1834 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001835 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001836 break;
1837 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001838
Anders Carlsson1b00e242010-04-23 03:10:23 +00001839 case IIK_Copy: {
1840 ParmVarDecl *Param = Constructor->getParamDecl(0);
1841 QualType ParamType = Param->getType().getNonReferenceType();
1842
1843 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001844 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001845 Constructor->getLocation(), ParamType,
1846 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001847
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001848 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001849 QualType ArgTy =
1850 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1851 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001852
1853 CXXCastPath BasePath;
1854 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001855 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1856 CK_UncheckedDerivedToBase,
1857 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001858
Anders Carlsson1b00e242010-04-23 03:10:23 +00001859 InitializationKind InitKind
1860 = InitializationKind::CreateDirect(Constructor->getLocation(),
1861 SourceLocation(), SourceLocation());
1862 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1863 &CopyCtorArg, 1);
1864 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001865 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001866 break;
1867 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001868
Anders Carlsson1b00e242010-04-23 03:10:23 +00001869 case IIK_Move:
1870 assert(false && "Unhandled initializer kind!");
1871 }
John McCallb268a282010-08-23 23:25:46 +00001872
Douglas Gregora40433a2010-12-07 00:41:46 +00001873 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001874 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001875 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001876
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001877 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001878 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001879 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1880 SourceLocation()),
1881 BaseSpec->isVirtual(),
1882 SourceLocation(),
1883 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001884 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001885 SourceLocation());
1886
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001887 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001888}
1889
Anders Carlsson3c1db572010-04-23 02:15:47 +00001890static bool
1891BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001892 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001893 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001894 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001895 if (Field->isInvalidDecl())
1896 return true;
1897
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001898 SourceLocation Loc = Constructor->getLocation();
1899
Anders Carlsson423f5d82010-04-23 16:04:08 +00001900 if (ImplicitInitKind == IIK_Copy) {
1901 ParmVarDecl *Param = Constructor->getParamDecl(0);
1902 QualType ParamType = Param->getType().getNonReferenceType();
1903
1904 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001905 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001906 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001907
1908 // Build a reference to this field within the parameter.
1909 CXXScopeSpec SS;
1910 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1911 Sema::LookupMemberName);
1912 MemberLookup.addDecl(Field, AS_public);
1913 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001914 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001915 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001916 ParamType, Loc,
1917 /*IsArrow=*/false,
1918 SS,
1919 /*FirstQualifierInScope=*/0,
1920 MemberLookup,
1921 /*TemplateArgs=*/0);
1922 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001923 return true;
1924
Douglas Gregor94f9a482010-05-05 05:51:00 +00001925 // When the field we are copying is an array, create index variables for
1926 // each dimension of the array. We use these index variables to subscript
1927 // the source array, and other clients (e.g., CodeGen) will perform the
1928 // necessary iteration with these index variables.
1929 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1930 QualType BaseType = Field->getType();
1931 QualType SizeType = SemaRef.Context.getSizeType();
1932 while (const ConstantArrayType *Array
1933 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1934 // Create the iteration variable for this array index.
1935 IdentifierInfo *IterationVarName = 0;
1936 {
1937 llvm::SmallString<8> Str;
1938 llvm::raw_svector_ostream OS(Str);
1939 OS << "__i" << IndexVariables.size();
1940 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1941 }
1942 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00001943 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001944 IterationVarName, SizeType,
1945 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001946 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001947 IndexVariables.push_back(IterationVar);
1948
1949 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001950 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001951 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001952 assert(!IterationVarRef.isInvalid() &&
1953 "Reference to invented variable cannot fail!");
1954
1955 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001956 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001957 Loc,
John McCallb268a282010-08-23 23:25:46 +00001958 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001959 Loc);
1960 if (CopyCtorArg.isInvalid())
1961 return true;
1962
1963 BaseType = Array->getElementType();
1964 }
1965
1966 // Construct the entity that we will be initializing. For an array, this
1967 // will be first element in the array, which may require several levels
1968 // of array-subscript entities.
1969 llvm::SmallVector<InitializedEntity, 4> Entities;
1970 Entities.reserve(1 + IndexVariables.size());
1971 Entities.push_back(InitializedEntity::InitializeMember(Field));
1972 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1973 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1974 0,
1975 Entities.back()));
1976
1977 // Direct-initialize to use the copy constructor.
1978 InitializationKind InitKind =
1979 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1980
1981 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1982 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1983 &CopyCtorArgE, 1);
1984
John McCalldadc5752010-08-24 06:29:42 +00001985 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001986 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001987 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001988 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001989 if (MemberInit.isInvalid())
1990 return true;
1991
1992 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001993 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001994 MemberInit.takeAs<Expr>(), Loc,
1995 IndexVariables.data(),
1996 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001997 return false;
1998 }
1999
Anders Carlsson423f5d82010-04-23 16:04:08 +00002000 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2001
Anders Carlsson3c1db572010-04-23 02:15:47 +00002002 QualType FieldBaseElementType =
2003 SemaRef.Context.getBaseElementType(Field->getType());
2004
Anders Carlsson3c1db572010-04-23 02:15:47 +00002005 if (FieldBaseElementType->isRecordType()) {
2006 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002007 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002008 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002009
2010 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002011 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002012 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002013
Douglas Gregora40433a2010-12-07 00:41:46 +00002014 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002015 if (MemberInit.isInvalid())
2016 return true;
2017
2018 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002019 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002020 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002021 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002022 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002023 return false;
2024 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002025
2026 if (FieldBaseElementType->isReferenceType()) {
2027 SemaRef.Diag(Constructor->getLocation(),
2028 diag::err_uninitialized_member_in_ctor)
2029 << (int)Constructor->isImplicit()
2030 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2031 << 0 << Field->getDeclName();
2032 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2033 return true;
2034 }
2035
2036 if (FieldBaseElementType.isConstQualified()) {
2037 SemaRef.Diag(Constructor->getLocation(),
2038 diag::err_uninitialized_member_in_ctor)
2039 << (int)Constructor->isImplicit()
2040 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2041 << 1 << Field->getDeclName();
2042 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2043 return true;
2044 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002045
2046 // Nothing to initialize.
2047 CXXMemberInit = 0;
2048 return false;
2049}
John McCallbc83b3f2010-05-20 23:23:51 +00002050
2051namespace {
2052struct BaseAndFieldInfo {
2053 Sema &S;
2054 CXXConstructorDecl *Ctor;
2055 bool AnyErrorsInInits;
2056 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002057 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2058 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002059
2060 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2061 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2062 // FIXME: Handle implicit move constructors.
2063 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2064 IIK = IIK_Copy;
2065 else
2066 IIK = IIK_Default;
2067 }
2068};
2069}
2070
2071static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2072 FieldDecl *Top, FieldDecl *Field) {
2073
Chandler Carruth139e9622010-06-30 02:59:29 +00002074 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002075 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002076 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002077 return false;
2078 }
2079
2080 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2081 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2082 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002083 CXXRecordDecl *FieldClassDecl
2084 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002085
2086 // Even though union members never have non-trivial default
2087 // constructions in C++03, we still build member initializers for aggregate
2088 // record types which can be union members, and C++0x allows non-trivial
2089 // default constructors for union members, so we ensure that only one
2090 // member is initialized for these.
2091 if (FieldClassDecl->isUnion()) {
2092 // First check for an explicit initializer for one field.
2093 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2094 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002095 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002096 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002097
2098 // Once we've initialized a field of an anonymous union, the union
2099 // field in the class is also initialized, so exit immediately.
2100 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002101 } else if ((*FA)->isAnonymousStructOrUnion()) {
2102 if (CollectFieldInitializer(Info, Top, *FA))
2103 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002104 }
2105 }
2106
2107 // Fallthrough and construct a default initializer for the union as
2108 // a whole, which can call its default constructor if such a thing exists
2109 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2110 // behavior going forward with C++0x, when anonymous unions there are
2111 // finalized, we should revisit this.
2112 } else {
2113 // For structs, we simply descend through to initialize all members where
2114 // necessary.
2115 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2116 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2117 if (CollectFieldInitializer(Info, Top, *FA))
2118 return true;
2119 }
2120 }
John McCallbc83b3f2010-05-20 23:23:51 +00002121 }
2122
2123 // Don't try to build an implicit initializer if there were semantic
2124 // errors in any of the initializers (and therefore we might be
2125 // missing some that the user actually wrote).
2126 if (Info.AnyErrorsInInits)
2127 return false;
2128
Alexis Hunt1d792652011-01-08 20:30:50 +00002129 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002130 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2131 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002132
Francois Pichetd583da02010-12-04 09:14:42 +00002133 if (Init)
2134 Info.AllToInit.push_back(Init);
2135
John McCallbc83b3f2010-05-20 23:23:51 +00002136 return false;
2137}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002138
2139bool
2140Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2141 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002142 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002143 Constructor->setNumCtorInitializers(1);
2144 CXXCtorInitializer **initializer =
2145 new (Context) CXXCtorInitializer*[1];
2146 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2147 Constructor->setCtorInitializers(initializer);
2148
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002149 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2150 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2151 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2152 }
2153
Alexis Hunte2622992011-05-05 00:05:47 +00002154 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002155
Alexis Hunt61bc1732011-05-01 07:04:31 +00002156 return false;
2157}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002158
Eli Friedman9cf6b592009-11-09 19:20:36 +00002159bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002160Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2161 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002162 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002163 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002164 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002165 // Just store the initializers as written, they will be checked during
2166 // instantiation.
2167 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002168 Constructor->setNumCtorInitializers(NumInitializers);
2169 CXXCtorInitializer **baseOrMemberInitializers =
2170 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002171 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002172 NumInitializers * sizeof(CXXCtorInitializer*));
2173 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002174 }
2175
2176 return false;
2177 }
2178
John McCallbc83b3f2010-05-20 23:23:51 +00002179 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002180
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002181 // We need to build the initializer AST according to order of construction
2182 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002183 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002184 if (!ClassDecl)
2185 return true;
2186
Eli Friedman9cf6b592009-11-09 19:20:36 +00002187 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002188
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002189 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002190 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002191
2192 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002193 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002194 else
Francois Pichetd583da02010-12-04 09:14:42 +00002195 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002196 }
2197
Anders Carlsson43c64af2010-04-21 19:52:01 +00002198 // Keep track of the direct virtual bases.
2199 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2200 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2201 E = ClassDecl->bases_end(); I != E; ++I) {
2202 if (I->isVirtual())
2203 DirectVBases.insert(I);
2204 }
2205
Anders Carlssondb0a9652010-04-02 06:26:44 +00002206 // Push virtual bases before others.
2207 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2208 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2209
Alexis Hunt1d792652011-01-08 20:30:50 +00002210 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002211 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2212 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002213 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002214 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002215 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002216 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002217 VBase, IsInheritedVirtualBase,
2218 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002219 HadError = true;
2220 continue;
2221 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002222
John McCallbc83b3f2010-05-20 23:23:51 +00002223 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002224 }
2225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
John McCallbc83b3f2010-05-20 23:23:51 +00002227 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2229 E = ClassDecl->bases_end(); Base != E; ++Base) {
2230 // Virtuals are in the virtual base list and already constructed.
2231 if (Base->isVirtual())
2232 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002233
Alexis Hunt1d792652011-01-08 20:30:50 +00002234 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002235 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2236 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002237 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002238 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002239 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002240 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002241 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002242 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002243 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002244 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002245
John McCallbc83b3f2010-05-20 23:23:51 +00002246 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002247 }
2248 }
Mike Stump11289f42009-09-09 15:08:12 +00002249
John McCallbc83b3f2010-05-20 23:23:51 +00002250 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002251 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002252 E = ClassDecl->field_end(); Field != E; ++Field) {
2253 if ((*Field)->getType()->isIncompleteArrayType()) {
2254 assert(ClassDecl->hasFlexibleArrayMember() &&
2255 "Incomplete array type is not valid");
2256 continue;
2257 }
John McCallbc83b3f2010-05-20 23:23:51 +00002258 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002259 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002260 }
Mike Stump11289f42009-09-09 15:08:12 +00002261
John McCallbc83b3f2010-05-20 23:23:51 +00002262 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002263 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002264 Constructor->setNumCtorInitializers(NumInitializers);
2265 CXXCtorInitializer **baseOrMemberInitializers =
2266 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002267 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002268 NumInitializers * sizeof(CXXCtorInitializer*));
2269 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002270
John McCalla6309952010-03-16 21:39:52 +00002271 // Constructors implicitly reference the base and member
2272 // destructors.
2273 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2274 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002275 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002276
2277 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002278}
2279
Eli Friedman952c15d2009-07-21 19:28:10 +00002280static void *GetKeyForTopLevelField(FieldDecl *Field) {
2281 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002282 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002283 if (RT->getDecl()->isAnonymousStructOrUnion())
2284 return static_cast<void *>(RT->getDecl());
2285 }
2286 return static_cast<void *>(Field);
2287}
2288
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002289static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002290 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002291}
2292
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002293static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002294 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002295 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002296 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002297
Eli Friedman952c15d2009-07-21 19:28:10 +00002298 // For fields injected into the class via declaration of an anonymous union,
2299 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002300 FieldDecl *Field = Member->getAnyMember();
2301
John McCall23eebd92010-04-10 09:28:51 +00002302 // If the field is a member of an anonymous struct or union, our key
2303 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002304 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002305 if (RD->isAnonymousStructOrUnion()) {
2306 while (true) {
2307 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2308 if (Parent->isAnonymousStructOrUnion())
2309 RD = Parent;
2310 else
2311 break;
2312 }
2313
Anders Carlsson83ac3122010-03-30 16:19:37 +00002314 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002315 }
Mike Stump11289f42009-09-09 15:08:12 +00002316
Anders Carlssona942dcd2010-03-30 15:39:27 +00002317 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002318}
2319
Anders Carlssone857b292010-04-02 03:37:03 +00002320static void
2321DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002322 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002323 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002324 unsigned NumInits) {
2325 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002326 return;
Mike Stump11289f42009-09-09 15:08:12 +00002327
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002328 // Don't check initializers order unless the warning is enabled at the
2329 // location of at least one initializer.
2330 bool ShouldCheckOrder = false;
2331 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002332 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002333 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2334 Init->getSourceLocation())
2335 != Diagnostic::Ignored) {
2336 ShouldCheckOrder = true;
2337 break;
2338 }
2339 }
2340 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002341 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002342
John McCallbb7b6582010-04-10 07:37:23 +00002343 // Build the list of bases and members in the order that they'll
2344 // actually be initialized. The explicit initializers should be in
2345 // this same order but may be missing things.
2346 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002347
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002348 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2349
John McCallbb7b6582010-04-10 07:37:23 +00002350 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002351 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002352 ClassDecl->vbases_begin(),
2353 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002354 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002355
John McCallbb7b6582010-04-10 07:37:23 +00002356 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002357 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002358 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002359 if (Base->isVirtual())
2360 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002361 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002362 }
Mike Stump11289f42009-09-09 15:08:12 +00002363
John McCallbb7b6582010-04-10 07:37:23 +00002364 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002365 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2366 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002367 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002368
John McCallbb7b6582010-04-10 07:37:23 +00002369 unsigned NumIdealInits = IdealInitKeys.size();
2370 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002371
Alexis Hunt1d792652011-01-08 20:30:50 +00002372 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002373 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002374 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002375 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002376
2377 // Scan forward to try to find this initializer in the idealized
2378 // initializers list.
2379 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2380 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002381 break;
John McCallbb7b6582010-04-10 07:37:23 +00002382
2383 // If we didn't find this initializer, it must be because we
2384 // scanned past it on a previous iteration. That can only
2385 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002386 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002387 Sema::SemaDiagnosticBuilder D =
2388 SemaRef.Diag(PrevInit->getSourceLocation(),
2389 diag::warn_initializer_out_of_order);
2390
Francois Pichetd583da02010-12-04 09:14:42 +00002391 if (PrevInit->isAnyMemberInitializer())
2392 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002393 else
2394 D << 1 << PrevInit->getBaseClassInfo()->getType();
2395
Francois Pichetd583da02010-12-04 09:14:42 +00002396 if (Init->isAnyMemberInitializer())
2397 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002398 else
2399 D << 1 << Init->getBaseClassInfo()->getType();
2400
2401 // Move back to the initializer's location in the ideal list.
2402 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2403 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002404 break;
John McCallbb7b6582010-04-10 07:37:23 +00002405
2406 assert(IdealIndex != NumIdealInits &&
2407 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002408 }
John McCallbb7b6582010-04-10 07:37:23 +00002409
2410 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002411 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002412}
2413
John McCall23eebd92010-04-10 09:28:51 +00002414namespace {
2415bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002416 CXXCtorInitializer *Init,
2417 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002418 if (!PrevInit) {
2419 PrevInit = Init;
2420 return false;
2421 }
2422
2423 if (FieldDecl *Field = Init->getMember())
2424 S.Diag(Init->getSourceLocation(),
2425 diag::err_multiple_mem_initialization)
2426 << Field->getDeclName()
2427 << Init->getSourceRange();
2428 else {
John McCall424cec92011-01-19 06:33:43 +00002429 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002430 assert(BaseClass && "neither field nor base");
2431 S.Diag(Init->getSourceLocation(),
2432 diag::err_multiple_base_initialization)
2433 << QualType(BaseClass, 0)
2434 << Init->getSourceRange();
2435 }
2436 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2437 << 0 << PrevInit->getSourceRange();
2438
2439 return true;
2440}
2441
Alexis Hunt1d792652011-01-08 20:30:50 +00002442typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002443typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2444
2445bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002446 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002447 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002448 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002449 RecordDecl *Parent = Field->getParent();
2450 if (!Parent->isAnonymousStructOrUnion())
2451 return false;
2452
2453 NamedDecl *Child = Field;
2454 do {
2455 if (Parent->isUnion()) {
2456 UnionEntry &En = Unions[Parent];
2457 if (En.first && En.first != Child) {
2458 S.Diag(Init->getSourceLocation(),
2459 diag::err_multiple_mem_union_initialization)
2460 << Field->getDeclName()
2461 << Init->getSourceRange();
2462 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2463 << 0 << En.second->getSourceRange();
2464 return true;
2465 } else if (!En.first) {
2466 En.first = Child;
2467 En.second = Init;
2468 }
2469 }
2470
2471 Child = Parent;
2472 Parent = cast<RecordDecl>(Parent->getDeclContext());
2473 } while (Parent->isAnonymousStructOrUnion());
2474
2475 return false;
2476}
2477}
2478
Anders Carlssone857b292010-04-02 03:37:03 +00002479/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002480void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002481 SourceLocation ColonLoc,
2482 MemInitTy **meminits, unsigned NumMemInits,
2483 bool AnyErrors) {
2484 if (!ConstructorDecl)
2485 return;
2486
2487 AdjustDeclIfTemplate(ConstructorDecl);
2488
2489 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002490 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002491
2492 if (!Constructor) {
2493 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2494 return;
2495 }
2496
Alexis Hunt1d792652011-01-08 20:30:50 +00002497 CXXCtorInitializer **MemInits =
2498 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002499
2500 // Mapping for the duplicate initializers check.
2501 // For member initializers, this is keyed with a FieldDecl*.
2502 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002503 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002504
2505 // Mapping for the inconsistent anonymous-union initializers check.
2506 RedundantUnionMap MemberUnions;
2507
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002508 bool HadError = false;
2509 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002510 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002511
Abramo Bagnara341d7832010-05-26 18:09:23 +00002512 // Set the source order index.
2513 Init->setSourceOrder(i);
2514
Francois Pichetd583da02010-12-04 09:14:42 +00002515 if (Init->isAnyMemberInitializer()) {
2516 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002517 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2518 CheckRedundantUnionInit(*this, Init, MemberUnions))
2519 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002520 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002521 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2522 if (CheckRedundantInit(*this, Init, Members[Key]))
2523 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002524 } else {
2525 assert(Init->isDelegatingInitializer());
2526 // This must be the only initializer
2527 if (i != 0 || NumMemInits > 1) {
2528 Diag(MemInits[0]->getSourceLocation(),
2529 diag::err_delegating_initializer_alone)
2530 << MemInits[0]->getSourceRange();
2531 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002532 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002533 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002534 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002535 // Return immediately as the initializer is set.
2536 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002537 }
Anders Carlssone857b292010-04-02 03:37:03 +00002538 }
2539
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002540 if (HadError)
2541 return;
2542
Anders Carlssone857b292010-04-02 03:37:03 +00002543 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002544
Alexis Hunt1d792652011-01-08 20:30:50 +00002545 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002546}
2547
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002548void
John McCalla6309952010-03-16 21:39:52 +00002549Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2550 CXXRecordDecl *ClassDecl) {
2551 // Ignore dependent contexts.
2552 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002553 return;
John McCall1064d7e2010-03-16 05:22:47 +00002554
2555 // FIXME: all the access-control diagnostics are positioned on the
2556 // field/base declaration. That's probably good; that said, the
2557 // user might reasonably want to know why the destructor is being
2558 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002559
Anders Carlssondee9a302009-11-17 04:44:12 +00002560 // Non-static data members.
2561 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2562 E = ClassDecl->field_end(); I != E; ++I) {
2563 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002564 if (Field->isInvalidDecl())
2565 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002566 QualType FieldType = Context.getBaseElementType(Field->getType());
2567
2568 const RecordType* RT = FieldType->getAs<RecordType>();
2569 if (!RT)
2570 continue;
2571
2572 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002573 if (FieldClassDecl->isInvalidDecl())
2574 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002575 if (FieldClassDecl->hasTrivialDestructor())
2576 continue;
2577
Douglas Gregore71edda2010-07-01 22:47:18 +00002578 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002579 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002580 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002581 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002582 << Field->getDeclName()
2583 << FieldType);
2584
John McCalla6309952010-03-16 21:39:52 +00002585 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002586 }
2587
John McCall1064d7e2010-03-16 05:22:47 +00002588 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2589
Anders Carlssondee9a302009-11-17 04:44:12 +00002590 // Bases.
2591 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2592 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002593 // Bases are always records in a well-formed non-dependent class.
2594 const RecordType *RT = Base->getType()->getAs<RecordType>();
2595
2596 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002597 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002598 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002599
John McCall1064d7e2010-03-16 05:22:47 +00002600 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002601 // If our base class is invalid, we probably can't get its dtor anyway.
2602 if (BaseClassDecl->isInvalidDecl())
2603 continue;
2604 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002605 if (BaseClassDecl->hasTrivialDestructor())
2606 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002607
Douglas Gregore71edda2010-07-01 22:47:18 +00002608 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002609 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002610
2611 // FIXME: caret should be on the start of the class name
2612 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002613 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002614 << Base->getType()
2615 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002616
John McCalla6309952010-03-16 21:39:52 +00002617 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002618 }
2619
2620 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002621 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2622 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002623
2624 // Bases are always records in a well-formed non-dependent class.
2625 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2626
2627 // Ignore direct virtual bases.
2628 if (DirectVirtualBases.count(RT))
2629 continue;
2630
John McCall1064d7e2010-03-16 05:22:47 +00002631 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002632 // If our base class is invalid, we probably can't get its dtor anyway.
2633 if (BaseClassDecl->isInvalidDecl())
2634 continue;
2635 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002636 if (BaseClassDecl->hasTrivialDestructor())
2637 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002638
Douglas Gregore71edda2010-07-01 22:47:18 +00002639 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002640 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002641 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002642 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002643 << VBase->getType());
2644
John McCalla6309952010-03-16 21:39:52 +00002645 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002646 }
2647}
2648
John McCall48871652010-08-21 09:40:31 +00002649void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002650 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002651 return;
Mike Stump11289f42009-09-09 15:08:12 +00002652
Mike Stump11289f42009-09-09 15:08:12 +00002653 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002654 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002655 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002656}
2657
Mike Stump11289f42009-09-09 15:08:12 +00002658bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002659 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002660 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002661 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002662 else
John McCall02db245d2010-08-18 09:41:07 +00002663 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002664}
2665
Anders Carlssoneabf7702009-08-27 00:13:57 +00002666bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002667 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002668 if (!getLangOptions().CPlusPlus)
2669 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002670
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002671 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002672 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002673
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002674 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002675 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002676 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002677 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002678
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002679 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002680 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002681 }
Mike Stump11289f42009-09-09 15:08:12 +00002682
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002683 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002684 if (!RT)
2685 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002686
John McCall67da35c2010-02-04 22:26:26 +00002687 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002688
John McCall02db245d2010-08-18 09:41:07 +00002689 // We can't answer whether something is abstract until it has a
2690 // definition. If it's currently being defined, we'll walk back
2691 // over all the declarations when we have a full definition.
2692 const CXXRecordDecl *Def = RD->getDefinition();
2693 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002694 return false;
2695
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002696 if (!RD->isAbstract())
2697 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002698
Anders Carlssoneabf7702009-08-27 00:13:57 +00002699 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002700 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002701
John McCall02db245d2010-08-18 09:41:07 +00002702 return true;
2703}
2704
2705void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2706 // Check if we've already emitted the list of pure virtual functions
2707 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002708 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002709 return;
Mike Stump11289f42009-09-09 15:08:12 +00002710
Douglas Gregor4165bd62010-03-23 23:47:56 +00002711 CXXFinalOverriderMap FinalOverriders;
2712 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002713
Anders Carlssona2f74f32010-06-03 01:00:02 +00002714 // Keep a set of seen pure methods so we won't diagnose the same method
2715 // more than once.
2716 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2717
Douglas Gregor4165bd62010-03-23 23:47:56 +00002718 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2719 MEnd = FinalOverriders.end();
2720 M != MEnd;
2721 ++M) {
2722 for (OverridingMethods::iterator SO = M->second.begin(),
2723 SOEnd = M->second.end();
2724 SO != SOEnd; ++SO) {
2725 // C++ [class.abstract]p4:
2726 // A class is abstract if it contains or inherits at least one
2727 // pure virtual function for which the final overrider is pure
2728 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002729
Douglas Gregor4165bd62010-03-23 23:47:56 +00002730 //
2731 if (SO->second.size() != 1)
2732 continue;
2733
2734 if (!SO->second.front().Method->isPure())
2735 continue;
2736
Anders Carlssona2f74f32010-06-03 01:00:02 +00002737 if (!SeenPureMethods.insert(SO->second.front().Method))
2738 continue;
2739
Douglas Gregor4165bd62010-03-23 23:47:56 +00002740 Diag(SO->second.front().Method->getLocation(),
2741 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002742 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002743 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002744 }
2745
2746 if (!PureVirtualClassDiagSet)
2747 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2748 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002749}
2750
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002751namespace {
John McCall02db245d2010-08-18 09:41:07 +00002752struct AbstractUsageInfo {
2753 Sema &S;
2754 CXXRecordDecl *Record;
2755 CanQualType AbstractType;
2756 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002757
John McCall02db245d2010-08-18 09:41:07 +00002758 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2759 : S(S), Record(Record),
2760 AbstractType(S.Context.getCanonicalType(
2761 S.Context.getTypeDeclType(Record))),
2762 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002763
John McCall02db245d2010-08-18 09:41:07 +00002764 void DiagnoseAbstractType() {
2765 if (Invalid) return;
2766 S.DiagnoseAbstractType(Record);
2767 Invalid = true;
2768 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002769
John McCall02db245d2010-08-18 09:41:07 +00002770 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2771};
2772
2773struct CheckAbstractUsage {
2774 AbstractUsageInfo &Info;
2775 const NamedDecl *Ctx;
2776
2777 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2778 : Info(Info), Ctx(Ctx) {}
2779
2780 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2781 switch (TL.getTypeLocClass()) {
2782#define ABSTRACT_TYPELOC(CLASS, PARENT)
2783#define TYPELOC(CLASS, PARENT) \
2784 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2785#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002786 }
John McCall02db245d2010-08-18 09:41:07 +00002787 }
Mike Stump11289f42009-09-09 15:08:12 +00002788
John McCall02db245d2010-08-18 09:41:07 +00002789 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2790 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2791 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002792 if (!TL.getArg(I))
2793 continue;
2794
John McCall02db245d2010-08-18 09:41:07 +00002795 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2796 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002797 }
John McCall02db245d2010-08-18 09:41:07 +00002798 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002799
John McCall02db245d2010-08-18 09:41:07 +00002800 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2801 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2802 }
Mike Stump11289f42009-09-09 15:08:12 +00002803
John McCall02db245d2010-08-18 09:41:07 +00002804 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2805 // Visit the type parameters from a permissive context.
2806 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2807 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2808 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2809 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2810 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2811 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002812 }
John McCall02db245d2010-08-18 09:41:07 +00002813 }
Mike Stump11289f42009-09-09 15:08:12 +00002814
John McCall02db245d2010-08-18 09:41:07 +00002815 // Visit pointee types from a permissive context.
2816#define CheckPolymorphic(Type) \
2817 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2818 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2819 }
2820 CheckPolymorphic(PointerTypeLoc)
2821 CheckPolymorphic(ReferenceTypeLoc)
2822 CheckPolymorphic(MemberPointerTypeLoc)
2823 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002824
John McCall02db245d2010-08-18 09:41:07 +00002825 /// Handle all the types we haven't given a more specific
2826 /// implementation for above.
2827 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2828 // Every other kind of type that we haven't called out already
2829 // that has an inner type is either (1) sugar or (2) contains that
2830 // inner type in some way as a subobject.
2831 if (TypeLoc Next = TL.getNextTypeLoc())
2832 return Visit(Next, Sel);
2833
2834 // If there's no inner type and we're in a permissive context,
2835 // don't diagnose.
2836 if (Sel == Sema::AbstractNone) return;
2837
2838 // Check whether the type matches the abstract type.
2839 QualType T = TL.getType();
2840 if (T->isArrayType()) {
2841 Sel = Sema::AbstractArrayType;
2842 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002843 }
John McCall02db245d2010-08-18 09:41:07 +00002844 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2845 if (CT != Info.AbstractType) return;
2846
2847 // It matched; do some magic.
2848 if (Sel == Sema::AbstractArrayType) {
2849 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2850 << T << TL.getSourceRange();
2851 } else {
2852 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2853 << Sel << T << TL.getSourceRange();
2854 }
2855 Info.DiagnoseAbstractType();
2856 }
2857};
2858
2859void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2860 Sema::AbstractDiagSelID Sel) {
2861 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2862}
2863
2864}
2865
2866/// Check for invalid uses of an abstract type in a method declaration.
2867static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2868 CXXMethodDecl *MD) {
2869 // No need to do the check on definitions, which require that
2870 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002871 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00002872 return;
2873
2874 // For safety's sake, just ignore it if we don't have type source
2875 // information. This should never happen for non-implicit methods,
2876 // but...
2877 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2878 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2879}
2880
2881/// Check for invalid uses of an abstract type within a class definition.
2882static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2883 CXXRecordDecl *RD) {
2884 for (CXXRecordDecl::decl_iterator
2885 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2886 Decl *D = *I;
2887 if (D->isImplicit()) continue;
2888
2889 // Methods and method templates.
2890 if (isa<CXXMethodDecl>(D)) {
2891 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2892 } else if (isa<FunctionTemplateDecl>(D)) {
2893 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2894 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2895
2896 // Fields and static variables.
2897 } else if (isa<FieldDecl>(D)) {
2898 FieldDecl *FD = cast<FieldDecl>(D);
2899 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2900 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2901 } else if (isa<VarDecl>(D)) {
2902 VarDecl *VD = cast<VarDecl>(D);
2903 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2904 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2905
2906 // Nested classes and class templates.
2907 } else if (isa<CXXRecordDecl>(D)) {
2908 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2909 } else if (isa<ClassTemplateDecl>(D)) {
2910 CheckAbstractClassUsage(Info,
2911 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2912 }
2913 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002914}
2915
Douglas Gregorc99f1552009-12-03 18:33:45 +00002916/// \brief Perform semantic checks on a class definition that has been
2917/// completing, introducing implicitly-declared members, checking for
2918/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002919void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002920 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002921 return;
2922
John McCall02db245d2010-08-18 09:41:07 +00002923 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2924 AbstractUsageInfo Info(*this, Record);
2925 CheckAbstractClassUsage(Info, Record);
2926 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002927
2928 // If this is not an aggregate type and has no user-declared constructor,
2929 // complain about any non-static data members of reference or const scalar
2930 // type, since they will never get initializers.
2931 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2932 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2933 bool Complained = false;
2934 for (RecordDecl::field_iterator F = Record->field_begin(),
2935 FEnd = Record->field_end();
2936 F != FEnd; ++F) {
2937 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002938 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002939 if (!Complained) {
2940 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2941 << Record->getTagKind() << Record;
2942 Complained = true;
2943 }
2944
2945 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2946 << F->getType()->isReferenceType()
2947 << F->getDeclName();
2948 }
2949 }
2950 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002951
Anders Carlssone771e762011-01-25 18:08:22 +00002952 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002953 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002954
2955 if (Record->getIdentifier()) {
2956 // C++ [class.mem]p13:
2957 // If T is the name of a class, then each of the following shall have a
2958 // name different from T:
2959 // - every member of every anonymous union that is a member of class T.
2960 //
2961 // C++ [class.mem]p14:
2962 // In addition, if class T has a user-declared constructor (12.1), every
2963 // non-static data member of class T shall have a name different from T.
2964 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002965 R.first != R.second; ++R.first) {
2966 NamedDecl *D = *R.first;
2967 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2968 isa<IndirectFieldDecl>(D)) {
2969 Diag(D->getLocation(), diag::err_member_name_of_class)
2970 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002971 break;
2972 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002973 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002974 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002975
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002976 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002977 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002978 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002979 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002980 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2981 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2982 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002983
2984 // See if a method overloads virtual methods in a base
2985 /// class without overriding any.
2986 if (!Record->isDependentType()) {
2987 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2988 MEnd = Record->method_end();
2989 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00002990 if (!(*M)->isStatic())
2991 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002992 }
2993 }
Sebastian Redl08905022011-02-05 19:23:19 +00002994
2995 // Declare inherited constructors. We do this eagerly here because:
2996 // - The standard requires an eager diagnostic for conflicting inherited
2997 // constructors from different classes.
2998 // - The lazy declaration of the other implicit constructors is so as to not
2999 // waste space and performance on classes that are not meant to be
3000 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3001 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003002 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003003
3004 CheckExplicitlyDefaultedMethods(Record);
3005}
3006
3007void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3008 for (CXXRecordDecl::ctor_iterator CI = Record->ctor_begin(),
3009 CE = Record->ctor_end();
3010 CI != CE; ++CI) {
3011 if (!CI->isInvalidDecl() && CI->isExplicitlyDefaulted()) {
3012 if (CI->isDefaultConstructor()) {
3013 CheckExplicitlyDefaultedDefaultConstructor(*CI);
3014 }
3015
3016 // FIXME: Do copy and move constructors
3017 }
3018 }
3019
3020 // FIXME: Do copy and move assignment and destructors
3021}
3022
3023void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3024 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3025
3026 // Whether this was the first-declared instance of the constructor.
3027 // This affects whether we implicitly add an exception spec (and, eventually,
3028 // constexpr). It is also ill-formed to explicitly default a constructor such
3029 // that it would be deleted. (C++0x [decl.fct.def.default])
3030 bool First = CD == CD->getCanonicalDecl();
3031
3032 if (CD->getNumParams() != 0) {
3033 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3034 << CD->getSourceRange();
3035 CD->setInvalidDecl();
3036 return;
3037 }
3038
3039 ImplicitExceptionSpecification Spec
3040 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3041 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3042 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3043 *ExceptionType = Context.getFunctionType(
3044 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3045
3046 if (CtorType->hasExceptionSpec()) {
3047 if (CheckEquivalentExceptionSpec(
3048 PDiag(diag::err_incorrect_defaulted_exception_spec),
3049 PDiag(),
3050 ExceptionType, SourceLocation(),
3051 CtorType, CD->getLocation())) {
3052 CD->setInvalidDecl();
3053 return;
3054 }
3055 } else if (First) {
3056 // We set the declaration to have the computed exception spec here.
3057 // We know there are no parameters.
3058 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3059 }
3060
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003061}
3062
3063/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00003064namespace {
3065 struct FindHiddenVirtualMethodData {
3066 Sema *S;
3067 CXXMethodDecl *Method;
3068 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3069 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3070 };
3071}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003072
3073/// \brief Member lookup function that determines whether a given C++
3074/// method overloads virtual methods in a base class without overriding any,
3075/// to be used with CXXRecordDecl::lookupInBases().
3076static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3077 CXXBasePath &Path,
3078 void *UserData) {
3079 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3080
3081 FindHiddenVirtualMethodData &Data
3082 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3083
3084 DeclarationName Name = Data.Method->getDeclName();
3085 assert(Name.getNameKind() == DeclarationName::Identifier);
3086
3087 bool foundSameNameMethod = false;
3088 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3089 for (Path.Decls = BaseRecord->lookup(Name);
3090 Path.Decls.first != Path.Decls.second;
3091 ++Path.Decls.first) {
3092 NamedDecl *D = *Path.Decls.first;
3093 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003094 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003095 foundSameNameMethod = true;
3096 // Interested only in hidden virtual methods.
3097 if (!MD->isVirtual())
3098 continue;
3099 // If the method we are checking overrides a method from its base
3100 // don't warn about the other overloaded methods.
3101 if (!Data.S->IsOverload(Data.Method, MD, false))
3102 return true;
3103 // Collect the overload only if its hidden.
3104 if (!Data.OverridenAndUsingBaseMethods.count(MD))
3105 overloadedMethods.push_back(MD);
3106 }
3107 }
3108
3109 if (foundSameNameMethod)
3110 Data.OverloadedMethods.append(overloadedMethods.begin(),
3111 overloadedMethods.end());
3112 return foundSameNameMethod;
3113}
3114
3115/// \brief See if a method overloads virtual methods in a base class without
3116/// overriding any.
3117void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
3118 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
3119 MD->getLocation()) == Diagnostic::Ignored)
3120 return;
3121 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
3122 return;
3123
3124 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
3125 /*bool RecordPaths=*/false,
3126 /*bool DetectVirtual=*/false);
3127 FindHiddenVirtualMethodData Data;
3128 Data.Method = MD;
3129 Data.S = this;
3130
3131 // Keep the base methods that were overriden or introduced in the subclass
3132 // by 'using' in a set. A base method not in this set is hidden.
3133 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
3134 res.first != res.second; ++res.first) {
3135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
3136 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
3137 E = MD->end_overridden_methods();
3138 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003139 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003140 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
3141 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003142 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003143 }
3144
3145 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
3146 !Data.OverloadedMethods.empty()) {
3147 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
3148 << MD << (Data.OverloadedMethods.size() > 1);
3149
3150 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3151 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3152 Diag(overloadedMD->getLocation(),
3153 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3154 }
3155 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00003156}
3157
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003158void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00003159 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003160 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003161 SourceLocation RBrac,
3162 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003163 if (!TagDecl)
3164 return;
Mike Stump11289f42009-09-09 15:08:12 +00003165
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003166 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00003167
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003168 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00003169 // strict aliasing violation!
3170 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003171 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00003172
Douglas Gregor0be31a22010-07-02 17:43:08 +00003173 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00003174 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003175}
3176
Douglas Gregor05379422008-11-03 17:51:48 +00003177/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3178/// special functions, such as the default constructor, copy
3179/// constructor, or destructor, to the given C++ class (C++
3180/// [special]p1). This routine can only be executed just before the
3181/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003182void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00003183 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003184 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003185
Douglas Gregor54be3392010-07-01 17:57:27 +00003186 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00003187 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003188
Douglas Gregor330b9cf2010-07-02 21:50:04 +00003189 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3190 ++ASTContext::NumImplicitCopyAssignmentOperators;
3191
3192 // If we have a dynamic class, then the copy assignment operator may be
3193 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3194 // it shows up in the right place in the vtable and that we diagnose
3195 // problems with the implicit exception specification.
3196 if (ClassDecl->isDynamicClass())
3197 DeclareImplicitCopyAssignment(ClassDecl);
3198 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003199
Douglas Gregor7454c562010-07-02 20:37:36 +00003200 if (!ClassDecl->hasUserDeclaredDestructor()) {
3201 ++ASTContext::NumImplicitDestructors;
3202
3203 // If we have a dynamic class, then the destructor may be virtual, so we
3204 // have to declare the destructor immediately. This ensures that, e.g., it
3205 // shows up in the right place in the vtable and that we diagnose problems
3206 // with the implicit exception specification.
3207 if (ClassDecl->isDynamicClass())
3208 DeclareImplicitDestructor(ClassDecl);
3209 }
Douglas Gregor05379422008-11-03 17:51:48 +00003210}
3211
Francois Pichet1c229c02011-04-22 22:18:13 +00003212void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3213 if (!D)
3214 return;
3215
3216 int NumParamList = D->getNumTemplateParameterLists();
3217 for (int i = 0; i < NumParamList; i++) {
3218 TemplateParameterList* Params = D->getTemplateParameterList(i);
3219 for (TemplateParameterList::iterator Param = Params->begin(),
3220 ParamEnd = Params->end();
3221 Param != ParamEnd; ++Param) {
3222 NamedDecl *Named = cast<NamedDecl>(*Param);
3223 if (Named->getDeclName()) {
3224 S->AddDecl(Named);
3225 IdResolver.AddDecl(Named);
3226 }
3227 }
3228 }
3229}
3230
John McCall48871652010-08-21 09:40:31 +00003231void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00003232 if (!D)
3233 return;
3234
3235 TemplateParameterList *Params = 0;
3236 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3237 Params = Template->getTemplateParameters();
3238 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3239 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3240 Params = PartialSpec->getTemplateParameters();
3241 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003242 return;
3243
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003244 for (TemplateParameterList::iterator Param = Params->begin(),
3245 ParamEnd = Params->end();
3246 Param != ParamEnd; ++Param) {
3247 NamedDecl *Named = cast<NamedDecl>(*Param);
3248 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003249 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003250 IdResolver.AddDecl(Named);
3251 }
3252 }
3253}
3254
John McCall48871652010-08-21 09:40:31 +00003255void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003256 if (!RecordD) return;
3257 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003258 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003259 PushDeclContext(S, Record);
3260}
3261
John McCall48871652010-08-21 09:40:31 +00003262void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003263 if (!RecordD) return;
3264 PopDeclContext();
3265}
3266
Douglas Gregor4d87df52008-12-16 21:30:33 +00003267/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3268/// parsing a top-level (non-nested) C++ class, and we are now
3269/// parsing those parts of the given Method declaration that could
3270/// not be parsed earlier (C++ [class.mem]p2), such as default
3271/// arguments. This action should enter the scope of the given
3272/// Method declaration as if we had just parsed the qualified method
3273/// name. However, it should not bring the parameters into scope;
3274/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003275void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003276}
3277
3278/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3279/// C++ method declaration. We're (re-)introducing the given
3280/// function parameter into scope for use in parsing later parts of
3281/// the method declaration. For example, we could see an
3282/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003283void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003284 if (!ParamD)
3285 return;
Mike Stump11289f42009-09-09 15:08:12 +00003286
John McCall48871652010-08-21 09:40:31 +00003287 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003288
3289 // If this parameter has an unparsed default argument, clear it out
3290 // to make way for the parsed default argument.
3291 if (Param->hasUnparsedDefaultArg())
3292 Param->setDefaultArg(0);
3293
John McCall48871652010-08-21 09:40:31 +00003294 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003295 if (Param->getDeclName())
3296 IdResolver.AddDecl(Param);
3297}
3298
3299/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3300/// processing the delayed method declaration for Method. The method
3301/// declaration is now considered finished. There may be a separate
3302/// ActOnStartOfFunctionDef action later (not necessarily
3303/// immediately!) for this method, if it was also defined inside the
3304/// class body.
John McCall48871652010-08-21 09:40:31 +00003305void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003306 if (!MethodD)
3307 return;
Mike Stump11289f42009-09-09 15:08:12 +00003308
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003309 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003310
John McCall48871652010-08-21 09:40:31 +00003311 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003312
3313 // Now that we have our default arguments, check the constructor
3314 // again. It could produce additional diagnostics or affect whether
3315 // the class has implicitly-declared destructors, among other
3316 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003317 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3318 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003319
3320 // Check the default arguments, which we may have added.
3321 if (!Method->isInvalidDecl())
3322 CheckCXXDefaultArguments(Method);
3323}
3324
Douglas Gregor831c93f2008-11-05 20:51:48 +00003325/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003326/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003327/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003328/// emit diagnostics and set the invalid bit to true. In any case, the type
3329/// will be updated to reflect a well-formed type for the constructor and
3330/// returned.
3331QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003332 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003333 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003334
3335 // C++ [class.ctor]p3:
3336 // A constructor shall not be virtual (10.3) or static (9.4). A
3337 // constructor can be invoked for a const, volatile or const
3338 // volatile object. A constructor shall not be declared const,
3339 // volatile, or const volatile (9.3.2).
3340 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003341 if (!D.isInvalidType())
3342 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3343 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3344 << SourceRange(D.getIdentifierLoc());
3345 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003346 }
John McCall8e7d6562010-08-26 03:08:43 +00003347 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003348 if (!D.isInvalidType())
3349 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3350 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3351 << SourceRange(D.getIdentifierLoc());
3352 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003353 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003354 }
Mike Stump11289f42009-09-09 15:08:12 +00003355
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003356 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003357 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003358 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003359 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3360 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003361 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003362 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3363 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003364 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003365 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3366 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003367 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003368 }
Mike Stump11289f42009-09-09 15:08:12 +00003369
Douglas Gregordb9d6642011-01-26 05:01:58 +00003370 // C++0x [class.ctor]p4:
3371 // A constructor shall not be declared with a ref-qualifier.
3372 if (FTI.hasRefQualifier()) {
3373 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3374 << FTI.RefQualifierIsLValueRef
3375 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3376 D.setInvalidType();
3377 }
3378
Douglas Gregor831c93f2008-11-05 20:51:48 +00003379 // Rebuild the function type "R" without any type qualifiers (in
3380 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003381 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003382 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003383 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3384 return R;
3385
3386 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3387 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003388 EPI.RefQualifier = RQ_None;
3389
Chris Lattner38378bf2009-04-25 08:28:21 +00003390 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003391 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003392}
3393
Douglas Gregor4d87df52008-12-16 21:30:33 +00003394/// CheckConstructor - Checks a fully-formed constructor for
3395/// well-formedness, issuing any diagnostics required. Returns true if
3396/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003397void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003398 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003399 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3400 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003401 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003402
3403 // C++ [class.copy]p3:
3404 // A declaration of a constructor for a class X is ill-formed if
3405 // its first parameter is of type (optionally cv-qualified) X and
3406 // either there are no other parameters or else all other
3407 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003408 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003409 ((Constructor->getNumParams() == 1) ||
3410 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003411 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3412 Constructor->getTemplateSpecializationKind()
3413 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003414 QualType ParamType = Constructor->getParamDecl(0)->getType();
3415 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3416 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003417 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003418 const char *ConstRef
3419 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3420 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003421 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003422 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003423
3424 // FIXME: Rather that making the constructor invalid, we should endeavor
3425 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003426 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003427 }
3428 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003429}
3430
John McCalldeb646e2010-08-04 01:04:25 +00003431/// CheckDestructor - Checks a fully-formed destructor definition for
3432/// well-formedness, issuing any diagnostics required. Returns true
3433/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003434bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003435 CXXRecordDecl *RD = Destructor->getParent();
3436
3437 if (Destructor->isVirtual()) {
3438 SourceLocation Loc;
3439
3440 if (!Destructor->isImplicit())
3441 Loc = Destructor->getLocation();
3442 else
3443 Loc = RD->getLocation();
3444
3445 // If we have a virtual destructor, look up the deallocation function
3446 FunctionDecl *OperatorDelete = 0;
3447 DeclarationName Name =
3448 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003449 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003450 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003451
3452 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003453
3454 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003455 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003456
3457 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003458}
3459
Mike Stump11289f42009-09-09 15:08:12 +00003460static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003461FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3462 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3463 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003464 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003465}
3466
Douglas Gregor831c93f2008-11-05 20:51:48 +00003467/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3468/// the well-formednes of the destructor declarator @p D with type @p
3469/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003470/// emit diagnostics and set the declarator to invalid. Even if this happens,
3471/// will be updated to reflect a well-formed type for the destructor and
3472/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003473QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003474 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003475 // C++ [class.dtor]p1:
3476 // [...] A typedef-name that names a class is a class-name
3477 // (7.1.3); however, a typedef-name that names a class shall not
3478 // be used as the identifier in the declarator for a destructor
3479 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003480 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00003481 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00003482 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00003483 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003484 else if (const TemplateSpecializationType *TST =
3485 DeclaratorType->getAs<TemplateSpecializationType>())
3486 if (TST->isTypeAlias())
3487 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
3488 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003489
3490 // C++ [class.dtor]p2:
3491 // A destructor is used to destroy objects of its class type. A
3492 // destructor takes no parameters, and no return type can be
3493 // specified for it (not even void). The address of a destructor
3494 // shall not be taken. A destructor shall not be static. A
3495 // destructor can be invoked for a const, volatile or const
3496 // volatile object. A destructor shall not be declared const,
3497 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003498 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003499 if (!D.isInvalidType())
3500 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3501 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003502 << SourceRange(D.getIdentifierLoc())
3503 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3504
John McCall8e7d6562010-08-26 03:08:43 +00003505 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003506 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003507 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003508 // Destructors don't have return types, but the parser will
3509 // happily parse something like:
3510 //
3511 // class X {
3512 // float ~X();
3513 // };
3514 //
3515 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003516 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3517 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3518 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003519 }
Mike Stump11289f42009-09-09 15:08:12 +00003520
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003521 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003522 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003523 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003524 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3525 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003526 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003527 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3528 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003529 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003530 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3531 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003532 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003533 }
3534
Douglas Gregordb9d6642011-01-26 05:01:58 +00003535 // C++0x [class.dtor]p2:
3536 // A destructor shall not be declared with a ref-qualifier.
3537 if (FTI.hasRefQualifier()) {
3538 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3539 << FTI.RefQualifierIsLValueRef
3540 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3541 D.setInvalidType();
3542 }
3543
Douglas Gregor831c93f2008-11-05 20:51:48 +00003544 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003545 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003546 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3547
3548 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003549 FTI.freeArgs();
3550 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003551 }
3552
Mike Stump11289f42009-09-09 15:08:12 +00003553 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003554 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003555 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003556 D.setInvalidType();
3557 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003558
3559 // Rebuild the function type "R" without any type qualifiers or
3560 // parameters (in case any of the errors above fired) and with
3561 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003562 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003563 if (!D.isInvalidType())
3564 return R;
3565
Douglas Gregor95755162010-07-01 05:10:53 +00003566 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003567 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3568 EPI.Variadic = false;
3569 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003570 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003571 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003572}
3573
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003574/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3575/// well-formednes of the conversion function declarator @p D with
3576/// type @p R. If there are any errors in the declarator, this routine
3577/// will emit diagnostics and return true. Otherwise, it will return
3578/// false. Either way, the type @p R will be updated to reflect a
3579/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003580void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003581 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003582 // C++ [class.conv.fct]p1:
3583 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003584 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003585 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003586 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003587 if (!D.isInvalidType())
3588 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3589 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3590 << SourceRange(D.getIdentifierLoc());
3591 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003592 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003593 }
John McCall212fa2e2010-04-13 00:04:31 +00003594
3595 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3596
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003597 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003598 // Conversion functions don't have return types, but the parser will
3599 // happily parse something like:
3600 //
3601 // class X {
3602 // float operator bool();
3603 // };
3604 //
3605 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003606 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3607 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3608 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003609 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003610 }
3611
John McCall212fa2e2010-04-13 00:04:31 +00003612 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3613
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003614 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003615 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003616 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3617
3618 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003619 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003620 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003621 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003622 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003623 D.setInvalidType();
3624 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003625
John McCall212fa2e2010-04-13 00:04:31 +00003626 // Diagnose "&operator bool()" and other such nonsense. This
3627 // is actually a gcc extension which we don't support.
3628 if (Proto->getResultType() != ConvType) {
3629 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3630 << Proto->getResultType();
3631 D.setInvalidType();
3632 ConvType = Proto->getResultType();
3633 }
3634
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003635 // C++ [class.conv.fct]p4:
3636 // The conversion-type-id shall not represent a function type nor
3637 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003638 if (ConvType->isArrayType()) {
3639 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3640 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003641 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003642 } else if (ConvType->isFunctionType()) {
3643 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3644 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003645 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003646 }
3647
3648 // Rebuild the function type "R" without any parameters (in case any
3649 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003650 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003651 if (D.isInvalidType())
3652 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003653
Douglas Gregor5fb53972009-01-14 15:45:31 +00003654 // C++0x explicit conversion operators.
3655 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003656 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003657 diag::warn_explicit_conversion_functions)
3658 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003659}
3660
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003661/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3662/// the declaration of the given C++ conversion function. This routine
3663/// is responsible for recording the conversion function in the C++
3664/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003665Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003666 assert(Conversion && "Expected to receive a conversion function declaration");
3667
Douglas Gregor4287b372008-12-12 08:25:50 +00003668 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003669
3670 // Make sure we aren't redeclaring the conversion function.
3671 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003672
3673 // C++ [class.conv.fct]p1:
3674 // [...] A conversion function is never used to convert a
3675 // (possibly cv-qualified) object to the (possibly cv-qualified)
3676 // same object type (or a reference to it), to a (possibly
3677 // cv-qualified) base class of that type (or a reference to it),
3678 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003679 // FIXME: Suppress this warning if the conversion function ends up being a
3680 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003681 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003682 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003683 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003684 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003685 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3686 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003687 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003688 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003689 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3690 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003691 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003692 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003693 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003694 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003695 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003696 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003697 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003698 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003699 }
3700
Douglas Gregor457104e2010-09-29 04:25:11 +00003701 if (FunctionTemplateDecl *ConversionTemplate
3702 = Conversion->getDescribedFunctionTemplate())
3703 return ConversionTemplate;
3704
John McCall48871652010-08-21 09:40:31 +00003705 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003706}
3707
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003708//===----------------------------------------------------------------------===//
3709// Namespace Handling
3710//===----------------------------------------------------------------------===//
3711
John McCallb1be5232010-08-26 09:15:37 +00003712
3713
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003714/// ActOnStartNamespaceDef - This is called at the start of a namespace
3715/// definition.
John McCall48871652010-08-21 09:40:31 +00003716Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003717 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003718 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00003719 SourceLocation IdentLoc,
3720 IdentifierInfo *II,
3721 SourceLocation LBrace,
3722 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003723 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3724 // For anonymous namespace, take the location of the left brace.
3725 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00003726 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003727 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003728 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003729
3730 Scope *DeclRegionScope = NamespcScope->getParent();
3731
Anders Carlssona7bcade2010-02-07 01:09:23 +00003732 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3733
John McCall2faf32c2010-12-10 02:59:44 +00003734 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3735 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003736
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003737 if (II) {
3738 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003739 // The identifier in an original-namespace-definition shall not
3740 // have been previously defined in the declarative region in
3741 // which the original-namespace-definition appears. The
3742 // identifier in an original-namespace-definition is the name of
3743 // the namespace. Subsequently in that declarative region, it is
3744 // treated as an original-namespace-name.
3745 //
3746 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00003747 // look through using directives, just look for any ordinary names.
3748
3749 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
3750 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
3751 Decl::IDNS_Namespace;
3752 NamedDecl *PrevDecl = 0;
3753 for (DeclContext::lookup_result R
3754 = CurContext->getRedeclContext()->lookup(II);
3755 R.first != R.second; ++R.first) {
3756 if ((*R.first)->getIdentifierNamespace() & IDNS) {
3757 PrevDecl = *R.first;
3758 break;
3759 }
3760 }
3761
Douglas Gregor91f84212008-12-11 16:49:14 +00003762 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3763 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003764 if (Namespc->isInline() != OrigNS->isInline()) {
3765 // inline-ness must match
3766 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3767 << Namespc->isInline();
3768 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3769 Namespc->setInvalidDecl();
3770 // Recover by ignoring the new namespace's inline status.
3771 Namespc->setInline(OrigNS->isInline());
3772 }
3773
Douglas Gregor91f84212008-12-11 16:49:14 +00003774 // Attach this namespace decl to the chain of extended namespace
3775 // definitions.
3776 OrigNS->setNextNamespace(Namespc);
3777 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003778
Mike Stump11289f42009-09-09 15:08:12 +00003779 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003780 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003781 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003782 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003783 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003784 } else if (PrevDecl) {
3785 // This is an invalid name redefinition.
3786 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3787 << Namespc->getDeclName();
3788 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3789 Namespc->setInvalidDecl();
3790 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003791 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003792 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003793 // This is the first "real" definition of the namespace "std", so update
3794 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003795 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003796 // We had already defined a dummy namespace "std". Link this new
3797 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003798 StdNS->setNextNamespace(Namespc);
3799 StdNS->setLocation(IdentLoc);
3800 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003801 }
3802
3803 // Make our StdNamespace cache point at the first real definition of the
3804 // "std" namespace.
3805 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003806 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003807
3808 PushOnScopeChains(Namespc, DeclRegionScope);
3809 } else {
John McCall4fa53422009-10-01 00:25:31 +00003810 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003811 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003812
3813 // Link the anonymous namespace into its parent.
3814 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003815 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003816 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3817 PrevDecl = TU->getAnonymousNamespace();
3818 TU->setAnonymousNamespace(Namespc);
3819 } else {
3820 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3821 PrevDecl = ND->getAnonymousNamespace();
3822 ND->setAnonymousNamespace(Namespc);
3823 }
3824
3825 // Link the anonymous namespace with its previous declaration.
3826 if (PrevDecl) {
3827 assert(PrevDecl->isAnonymousNamespace());
3828 assert(!PrevDecl->getNextNamespace());
3829 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3830 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003831
3832 if (Namespc->isInline() != PrevDecl->isInline()) {
3833 // inline-ness must match
3834 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3835 << Namespc->isInline();
3836 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3837 Namespc->setInvalidDecl();
3838 // Recover by ignoring the new namespace's inline status.
3839 Namespc->setInline(PrevDecl->isInline());
3840 }
John McCall0db42252009-12-16 02:06:49 +00003841 }
John McCall4fa53422009-10-01 00:25:31 +00003842
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003843 CurContext->addDecl(Namespc);
3844
John McCall4fa53422009-10-01 00:25:31 +00003845 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3846 // behaves as if it were replaced by
3847 // namespace unique { /* empty body */ }
3848 // using namespace unique;
3849 // namespace unique { namespace-body }
3850 // where all occurrences of 'unique' in a translation unit are
3851 // replaced by the same identifier and this identifier differs
3852 // from all other identifiers in the entire program.
3853
3854 // We just create the namespace with an empty name and then add an
3855 // implicit using declaration, just like the standard suggests.
3856 //
3857 // CodeGen enforces the "universally unique" aspect by giving all
3858 // declarations semantically contained within an anonymous
3859 // namespace internal linkage.
3860
John McCall0db42252009-12-16 02:06:49 +00003861 if (!PrevDecl) {
3862 UsingDirectiveDecl* UD
3863 = UsingDirectiveDecl::Create(Context, CurContext,
3864 /* 'using' */ LBrace,
3865 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00003866 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00003867 /* identifier */ SourceLocation(),
3868 Namespc,
3869 /* Ancestor */ CurContext);
3870 UD->setImplicit();
3871 CurContext->addDecl(UD);
3872 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003873 }
3874
3875 // Although we could have an invalid decl (i.e. the namespace name is a
3876 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003877 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3878 // for the namespace has the declarations that showed up in that particular
3879 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003880 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003881 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003882}
3883
Sebastian Redla6602e92009-11-23 15:34:23 +00003884/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3885/// is a namespace alias, returns the namespace it points to.
3886static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3887 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3888 return AD->getNamespace();
3889 return dyn_cast_or_null<NamespaceDecl>(D);
3890}
3891
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003892/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3893/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003894void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003895 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3896 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003897 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003898 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003899 if (Namespc->hasAttr<VisibilityAttr>())
3900 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003901}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003902
John McCall28a0cf72010-08-25 07:42:41 +00003903CXXRecordDecl *Sema::getStdBadAlloc() const {
3904 return cast_or_null<CXXRecordDecl>(
3905 StdBadAlloc.get(Context.getExternalSource()));
3906}
3907
3908NamespaceDecl *Sema::getStdNamespace() const {
3909 return cast_or_null<NamespaceDecl>(
3910 StdNamespace.get(Context.getExternalSource()));
3911}
3912
Douglas Gregorcdf87022010-06-29 17:53:46 +00003913/// \brief Retrieve the special "std" namespace, which may require us to
3914/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003915NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003916 if (!StdNamespace) {
3917 // The "std" namespace has not yet been defined, so build one implicitly.
3918 StdNamespace = NamespaceDecl::Create(Context,
3919 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003920 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00003921 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003922 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003923 }
3924
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003925 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003926}
3927
Douglas Gregora172e082011-03-26 22:25:30 +00003928/// \brief Determine whether a using statement is in a context where it will be
3929/// apply in all contexts.
3930static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3931 switch (CurContext->getDeclKind()) {
3932 case Decl::TranslationUnit:
3933 return true;
3934 case Decl::LinkageSpec:
3935 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3936 default:
3937 return false;
3938 }
3939}
3940
John McCall48871652010-08-21 09:40:31 +00003941Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003942 SourceLocation UsingLoc,
3943 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003944 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003945 SourceLocation IdentLoc,
3946 IdentifierInfo *NamespcName,
3947 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003948 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3949 assert(NamespcName && "Invalid NamespcName.");
3950 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003951
3952 // This can only happen along a recovery path.
3953 while (S->getFlags() & Scope::TemplateParamScope)
3954 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003955 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003956
Douglas Gregor889ceb72009-02-03 19:21:40 +00003957 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003958 NestedNameSpecifier *Qualifier = 0;
3959 if (SS.isSet())
3960 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3961
Douglas Gregor34074322009-01-14 22:20:51 +00003962 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003963 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3964 LookupParsedName(R, S, &SS);
3965 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003966 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003967
Douglas Gregorcdf87022010-06-29 17:53:46 +00003968 if (R.empty()) {
3969 // Allow "using namespace std;" or "using namespace ::std;" even if
3970 // "std" hasn't been defined yet, for GCC compatibility.
3971 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3972 NamespcName->isStr("std")) {
3973 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003974 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003975 R.resolveKind();
3976 }
3977 // Otherwise, attempt typo correction.
3978 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3979 CTC_NoKeywords, 0)) {
3980 if (R.getAsSingle<NamespaceDecl>() ||
3981 R.getAsSingle<NamespaceAliasDecl>()) {
3982 if (DeclContext *DC = computeDeclContext(SS, false))
3983 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3984 << NamespcName << DC << Corrected << SS.getRange()
3985 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3986 else
3987 Diag(IdentLoc, diag::err_using_directive_suggest)
3988 << NamespcName << Corrected
3989 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3990 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3991 << Corrected;
3992
3993 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003994 } else {
3995 R.clear();
3996 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003997 }
3998 }
3999 }
4000
John McCall9f3059a2009-10-09 21:13:30 +00004001 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00004002 NamedDecl *Named = R.getFoundDecl();
4003 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4004 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00004005 // C++ [namespace.udir]p1:
4006 // A using-directive specifies that the names in the nominated
4007 // namespace can be used in the scope in which the
4008 // using-directive appears after the using-directive. During
4009 // unqualified name lookup (3.4.1), the names appear as if they
4010 // were declared in the nearest enclosing namespace which
4011 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00004012 // namespace. [Note: in this context, "contains" means "contains
4013 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00004014
4015 // Find enclosing context containing both using-directive and
4016 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00004017 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004018 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4019 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4020 CommonAncestor = CommonAncestor->getParent();
4021
Sebastian Redla6602e92009-11-23 15:34:23 +00004022 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00004023 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00004024 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004025
Douglas Gregora172e082011-03-26 22:25:30 +00004026 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00004027 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004028 Diag(IdentLoc, diag::warn_using_directive_in_header);
4029 }
4030
Douglas Gregor889ceb72009-02-03 19:21:40 +00004031 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004032 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00004033 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00004034 }
4035
Douglas Gregor889ceb72009-02-03 19:21:40 +00004036 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00004037 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00004038}
4039
4040void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4041 // If scope has associated entity, then using directive is at namespace
4042 // or translation unit scope. We add UsingDirectiveDecls, into
4043 // it's lookup structure.
4044 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004045 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004046 else
4047 // Otherwise it is block-sope. using-directives will affect lookup
4048 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00004049 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004050}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004051
Douglas Gregorfec52632009-06-20 00:51:54 +00004052
John McCall48871652010-08-21 09:40:31 +00004053Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00004054 AccessSpecifier AS,
4055 bool HasUsingKeyword,
4056 SourceLocation UsingLoc,
4057 CXXScopeSpec &SS,
4058 UnqualifiedId &Name,
4059 AttributeList *AttrList,
4060 bool IsTypeName,
4061 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004062 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004063
Douglas Gregor220f4272009-11-04 16:30:06 +00004064 switch (Name.getKind()) {
4065 case UnqualifiedId::IK_Identifier:
4066 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004067 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004068 case UnqualifiedId::IK_ConversionFunctionId:
4069 break;
4070
4071 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004072 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004073 // C++0x inherited constructors.
4074 if (getLangOptions().CPlusPlus0x) break;
4075
Douglas Gregor220f4272009-11-04 16:30:06 +00004076 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4077 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004078 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004079
4080 case UnqualifiedId::IK_DestructorName:
4081 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4082 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004083 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004084
4085 case UnqualifiedId::IK_TemplateId:
4086 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4087 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00004088 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004089 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004090
4091 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4092 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00004093 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00004094 return 0;
John McCall3969e302009-12-08 07:46:18 +00004095
John McCalla0097262009-12-11 02:10:03 +00004096 // Warn about using declarations.
4097 // TODO: store that the declaration was written without 'using' and
4098 // talk about access decls instead of using decls in the
4099 // diagnostics.
4100 if (!HasUsingKeyword) {
4101 UsingLoc = Name.getSourceRange().getBegin();
4102
4103 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00004104 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00004105 }
4106
Douglas Gregorc4356532010-12-16 00:46:58 +00004107 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4108 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4109 return 0;
4110
John McCall3f746822009-11-17 05:59:44 +00004111 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004112 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004113 /* IsInstantiation */ false,
4114 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00004115 if (UD)
4116 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00004117
John McCall48871652010-08-21 09:40:31 +00004118 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00004119}
4120
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004121/// \brief Determine whether a using declaration considers the given
4122/// declarations as "equivalent", e.g., if they are redeclarations of
4123/// the same entity or are both typedefs of the same type.
4124static bool
4125IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4126 bool &SuppressRedeclaration) {
4127 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4128 SuppressRedeclaration = false;
4129 return true;
4130 }
4131
Richard Smithdda56e42011-04-15 14:24:37 +00004132 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4133 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004134 SuppressRedeclaration = true;
4135 return Context.hasSameType(TD1->getUnderlyingType(),
4136 TD2->getUnderlyingType());
4137 }
4138
4139 return false;
4140}
4141
4142
John McCall84d87672009-12-10 09:41:52 +00004143/// Determines whether to create a using shadow decl for a particular
4144/// decl, given the set of decls existing prior to this using lookup.
4145bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4146 const LookupResult &Previous) {
4147 // Diagnose finding a decl which is not from a base class of the
4148 // current class. We do this now because there are cases where this
4149 // function will silently decide not to build a shadow decl, which
4150 // will pre-empt further diagnostics.
4151 //
4152 // We don't need to do this in C++0x because we do the check once on
4153 // the qualifier.
4154 //
4155 // FIXME: diagnose the following if we care enough:
4156 // struct A { int foo; };
4157 // struct B : A { using A::foo; };
4158 // template <class T> struct C : A {};
4159 // template <class T> struct D : C<T> { using B::foo; } // <---
4160 // This is invalid (during instantiation) in C++03 because B::foo
4161 // resolves to the using decl in B, which is not a base class of D<T>.
4162 // We can't diagnose it immediately because C<T> is an unknown
4163 // specialization. The UsingShadowDecl in D<T> then points directly
4164 // to A::foo, which will look well-formed when we instantiate.
4165 // The right solution is to not collapse the shadow-decl chain.
4166 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4167 DeclContext *OrigDC = Orig->getDeclContext();
4168
4169 // Handle enums and anonymous structs.
4170 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4171 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4172 while (OrigRec->isAnonymousStructOrUnion())
4173 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4174
4175 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4176 if (OrigDC == CurContext) {
4177 Diag(Using->getLocation(),
4178 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004179 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004180 Diag(Orig->getLocation(), diag::note_using_decl_target);
4181 return true;
4182 }
4183
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004184 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00004185 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004186 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00004187 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004188 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004189 Diag(Orig->getLocation(), diag::note_using_decl_target);
4190 return true;
4191 }
4192 }
4193
4194 if (Previous.empty()) return false;
4195
4196 NamedDecl *Target = Orig;
4197 if (isa<UsingShadowDecl>(Target))
4198 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4199
John McCalla17e83e2009-12-11 02:33:26 +00004200 // If the target happens to be one of the previous declarations, we
4201 // don't have a conflict.
4202 //
4203 // FIXME: but we might be increasing its access, in which case we
4204 // should redeclare it.
4205 NamedDecl *NonTag = 0, *Tag = 0;
4206 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4207 I != E; ++I) {
4208 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004209 bool Result;
4210 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4211 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00004212
4213 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4214 }
4215
John McCall84d87672009-12-10 09:41:52 +00004216 if (Target->isFunctionOrFunctionTemplate()) {
4217 FunctionDecl *FD;
4218 if (isa<FunctionTemplateDecl>(Target))
4219 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4220 else
4221 FD = cast<FunctionDecl>(Target);
4222
4223 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00004224 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00004225 case Ovl_Overload:
4226 return false;
4227
4228 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00004229 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004230 break;
4231
4232 // We found a decl with the exact signature.
4233 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004234 // If we're in a record, we want to hide the target, so we
4235 // return true (without a diagnostic) to tell the caller not to
4236 // build a shadow decl.
4237 if (CurContext->isRecord())
4238 return true;
4239
4240 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00004241 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004242 break;
4243 }
4244
4245 Diag(Target->getLocation(), diag::note_using_decl_target);
4246 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4247 return true;
4248 }
4249
4250 // Target is not a function.
4251
John McCall84d87672009-12-10 09:41:52 +00004252 if (isa<TagDecl>(Target)) {
4253 // No conflict between a tag and a non-tag.
4254 if (!Tag) return false;
4255
John McCalle29c5cd2009-12-10 19:51:03 +00004256 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004257 Diag(Target->getLocation(), diag::note_using_decl_target);
4258 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4259 return true;
4260 }
4261
4262 // No conflict between a tag and a non-tag.
4263 if (!NonTag) return false;
4264
John McCalle29c5cd2009-12-10 19:51:03 +00004265 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004266 Diag(Target->getLocation(), diag::note_using_decl_target);
4267 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4268 return true;
4269}
4270
John McCall3f746822009-11-17 05:59:44 +00004271/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004272UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004273 UsingDecl *UD,
4274 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004275
4276 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004277 NamedDecl *Target = Orig;
4278 if (isa<UsingShadowDecl>(Target)) {
4279 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4280 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004281 }
4282
4283 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004284 = UsingShadowDecl::Create(Context, CurContext,
4285 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004286 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004287
4288 Shadow->setAccess(UD->getAccess());
4289 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4290 Shadow->setInvalidDecl();
4291
John McCall3f746822009-11-17 05:59:44 +00004292 if (S)
John McCall3969e302009-12-08 07:46:18 +00004293 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004294 else
John McCall3969e302009-12-08 07:46:18 +00004295 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004296
John McCall3969e302009-12-08 07:46:18 +00004297
John McCall84d87672009-12-10 09:41:52 +00004298 return Shadow;
4299}
John McCall3969e302009-12-08 07:46:18 +00004300
John McCall84d87672009-12-10 09:41:52 +00004301/// Hides a using shadow declaration. This is required by the current
4302/// using-decl implementation when a resolvable using declaration in a
4303/// class is followed by a declaration which would hide or override
4304/// one or more of the using decl's targets; for example:
4305///
4306/// struct Base { void foo(int); };
4307/// struct Derived : Base {
4308/// using Base::foo;
4309/// void foo(int);
4310/// };
4311///
4312/// The governing language is C++03 [namespace.udecl]p12:
4313///
4314/// When a using-declaration brings names from a base class into a
4315/// derived class scope, member functions in the derived class
4316/// override and/or hide member functions with the same name and
4317/// parameter types in a base class (rather than conflicting).
4318///
4319/// There are two ways to implement this:
4320/// (1) optimistically create shadow decls when they're not hidden
4321/// by existing declarations, or
4322/// (2) don't create any shadow decls (or at least don't make them
4323/// visible) until we've fully parsed/instantiated the class.
4324/// The problem with (1) is that we might have to retroactively remove
4325/// a shadow decl, which requires several O(n) operations because the
4326/// decl structures are (very reasonably) not designed for removal.
4327/// (2) avoids this but is very fiddly and phase-dependent.
4328void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004329 if (Shadow->getDeclName().getNameKind() ==
4330 DeclarationName::CXXConversionFunctionName)
4331 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4332
John McCall84d87672009-12-10 09:41:52 +00004333 // Remove it from the DeclContext...
4334 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004335
John McCall84d87672009-12-10 09:41:52 +00004336 // ...and the scope, if applicable...
4337 if (S) {
John McCall48871652010-08-21 09:40:31 +00004338 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004339 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004340 }
4341
John McCall84d87672009-12-10 09:41:52 +00004342 // ...and the using decl.
4343 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4344
4345 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004346 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004347}
4348
John McCalle61f2ba2009-11-18 02:36:19 +00004349/// Builds a using declaration.
4350///
4351/// \param IsInstantiation - Whether this call arises from an
4352/// instantiation of an unresolved using declaration. We treat
4353/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004354NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4355 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004356 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004357 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004358 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004359 bool IsInstantiation,
4360 bool IsTypeName,
4361 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004362 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004363 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004364 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004365
Anders Carlssonf038fc22009-08-28 05:49:21 +00004366 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004367
Anders Carlsson59140b32009-08-28 03:16:11 +00004368 if (SS.isEmpty()) {
4369 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004370 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004371 }
Mike Stump11289f42009-09-09 15:08:12 +00004372
John McCall84d87672009-12-10 09:41:52 +00004373 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004374 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004375 ForRedeclaration);
4376 Previous.setHideTags(false);
4377 if (S) {
4378 LookupName(Previous, S);
4379
4380 // It is really dumb that we have to do this.
4381 LookupResult::Filter F = Previous.makeFilter();
4382 while (F.hasNext()) {
4383 NamedDecl *D = F.next();
4384 if (!isDeclInScope(D, CurContext, S))
4385 F.erase();
4386 }
4387 F.done();
4388 } else {
4389 assert(IsInstantiation && "no scope in non-instantiation");
4390 assert(CurContext->isRecord() && "scope not record in instantiation");
4391 LookupQualifiedName(Previous, CurContext);
4392 }
4393
John McCall84d87672009-12-10 09:41:52 +00004394 // Check for invalid redeclarations.
4395 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4396 return 0;
4397
4398 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004399 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4400 return 0;
4401
John McCall84c16cf2009-11-12 03:15:40 +00004402 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004403 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004404 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00004405 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004406 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004407 // FIXME: not all declaration name kinds are legal here
4408 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4409 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004410 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004411 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004412 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004413 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4414 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004415 }
John McCallb96ec562009-12-04 22:46:56 +00004416 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004417 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4418 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004419 }
John McCallb96ec562009-12-04 22:46:56 +00004420 D->setAccess(AS);
4421 CurContext->addDecl(D);
4422
4423 if (!LookupContext) return D;
4424 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004425
John McCall0b66eb32010-05-01 00:40:08 +00004426 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004427 UD->setInvalidDecl();
4428 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004429 }
4430
Sebastian Redl08905022011-02-05 19:23:19 +00004431 // Constructor inheriting using decls get special treatment.
4432 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00004433 if (CheckInheritedConstructorUsingDecl(UD))
4434 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00004435 return UD;
4436 }
4437
4438 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00004439
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004440 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004441
John McCall3969e302009-12-08 07:46:18 +00004442 // Unlike most lookups, we don't always want to hide tag
4443 // declarations: tag names are visible through the using declaration
4444 // even if hidden by ordinary names, *except* in a dependent context
4445 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004446 if (!IsInstantiation)
4447 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004448
John McCall27b18f82009-11-17 02:14:36 +00004449 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004450
John McCall9f3059a2009-10-09 21:13:30 +00004451 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004452 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004453 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004454 UD->setInvalidDecl();
4455 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004456 }
4457
John McCallb96ec562009-12-04 22:46:56 +00004458 if (R.isAmbiguous()) {
4459 UD->setInvalidDecl();
4460 return UD;
4461 }
Mike Stump11289f42009-09-09 15:08:12 +00004462
John McCalle61f2ba2009-11-18 02:36:19 +00004463 if (IsTypeName) {
4464 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004465 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004466 Diag(IdentLoc, diag::err_using_typename_non_type);
4467 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4468 Diag((*I)->getUnderlyingDecl()->getLocation(),
4469 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004470 UD->setInvalidDecl();
4471 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004472 }
4473 } else {
4474 // If we asked for a non-typename and we got a type, error out,
4475 // but only if this is an instantiation of an unresolved using
4476 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004477 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004478 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4479 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004480 UD->setInvalidDecl();
4481 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004482 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004483 }
4484
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004485 // C++0x N2914 [namespace.udecl]p6:
4486 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004487 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004488 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4489 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004490 UD->setInvalidDecl();
4491 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004492 }
Mike Stump11289f42009-09-09 15:08:12 +00004493
John McCall84d87672009-12-10 09:41:52 +00004494 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4495 if (!CheckUsingShadowDecl(UD, *I, Previous))
4496 BuildUsingShadowDecl(S, UD, *I);
4497 }
John McCall3f746822009-11-17 05:59:44 +00004498
4499 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004500}
4501
Sebastian Redl08905022011-02-05 19:23:19 +00004502/// Additional checks for a using declaration referring to a constructor name.
4503bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4504 if (UD->isTypeName()) {
4505 // FIXME: Cannot specify typename when specifying constructor
4506 return true;
4507 }
4508
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004509 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00004510 assert(SourceType &&
4511 "Using decl naming constructor doesn't have type in scope spec.");
4512 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4513
4514 // Check whether the named type is a direct base class.
4515 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4516 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4517 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4518 BaseIt != BaseE; ++BaseIt) {
4519 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4520 if (CanonicalSourceType == BaseType)
4521 break;
4522 }
4523
4524 if (BaseIt == BaseE) {
4525 // Did not find SourceType in the bases.
4526 Diag(UD->getUsingLocation(),
4527 diag::err_using_decl_constructor_not_in_direct_base)
4528 << UD->getNameInfo().getSourceRange()
4529 << QualType(SourceType, 0) << TargetClass;
4530 return true;
4531 }
4532
4533 BaseIt->setInheritConstructors();
4534
4535 return false;
4536}
4537
John McCall84d87672009-12-10 09:41:52 +00004538/// Checks that the given using declaration is not an invalid
4539/// redeclaration. Note that this is checking only for the using decl
4540/// itself, not for any ill-formedness among the UsingShadowDecls.
4541bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4542 bool isTypeName,
4543 const CXXScopeSpec &SS,
4544 SourceLocation NameLoc,
4545 const LookupResult &Prev) {
4546 // C++03 [namespace.udecl]p8:
4547 // C++0x [namespace.udecl]p10:
4548 // A using-declaration is a declaration and can therefore be used
4549 // repeatedly where (and only where) multiple declarations are
4550 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004551 //
John McCall032092f2010-11-29 18:01:58 +00004552 // That's in non-member contexts.
4553 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004554 return false;
4555
4556 NestedNameSpecifier *Qual
4557 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4558
4559 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4560 NamedDecl *D = *I;
4561
4562 bool DTypename;
4563 NestedNameSpecifier *DQual;
4564 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4565 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004566 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004567 } else if (UnresolvedUsingValueDecl *UD
4568 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4569 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004570 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004571 } else if (UnresolvedUsingTypenameDecl *UD
4572 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4573 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004574 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004575 } else continue;
4576
4577 // using decls differ if one says 'typename' and the other doesn't.
4578 // FIXME: non-dependent using decls?
4579 if (isTypeName != DTypename) continue;
4580
4581 // using decls differ if they name different scopes (but note that
4582 // template instantiation can cause this check to trigger when it
4583 // didn't before instantiation).
4584 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4585 Context.getCanonicalNestedNameSpecifier(DQual))
4586 continue;
4587
4588 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004589 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004590 return true;
4591 }
4592
4593 return false;
4594}
4595
John McCall3969e302009-12-08 07:46:18 +00004596
John McCallb96ec562009-12-04 22:46:56 +00004597/// Checks that the given nested-name qualifier used in a using decl
4598/// in the current context is appropriately related to the current
4599/// scope. If an error is found, diagnoses it and returns true.
4600bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4601 const CXXScopeSpec &SS,
4602 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004603 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004604
John McCall3969e302009-12-08 07:46:18 +00004605 if (!CurContext->isRecord()) {
4606 // C++03 [namespace.udecl]p3:
4607 // C++0x [namespace.udecl]p8:
4608 // A using-declaration for a class member shall be a member-declaration.
4609
4610 // If we weren't able to compute a valid scope, it must be a
4611 // dependent class scope.
4612 if (!NamedContext || NamedContext->isRecord()) {
4613 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4614 << SS.getRange();
4615 return true;
4616 }
4617
4618 // Otherwise, everything is known to be fine.
4619 return false;
4620 }
4621
4622 // The current scope is a record.
4623
4624 // If the named context is dependent, we can't decide much.
4625 if (!NamedContext) {
4626 // FIXME: in C++0x, we can diagnose if we can prove that the
4627 // nested-name-specifier does not refer to a base class, which is
4628 // still possible in some cases.
4629
4630 // Otherwise we have to conservatively report that things might be
4631 // okay.
4632 return false;
4633 }
4634
4635 if (!NamedContext->isRecord()) {
4636 // Ideally this would point at the last name in the specifier,
4637 // but we don't have that level of source info.
4638 Diag(SS.getRange().getBegin(),
4639 diag::err_using_decl_nested_name_specifier_is_not_class)
4640 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4641 return true;
4642 }
4643
Douglas Gregor7c842292010-12-21 07:41:49 +00004644 if (!NamedContext->isDependentContext() &&
4645 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4646 return true;
4647
John McCall3969e302009-12-08 07:46:18 +00004648 if (getLangOptions().CPlusPlus0x) {
4649 // C++0x [namespace.udecl]p3:
4650 // In a using-declaration used as a member-declaration, the
4651 // nested-name-specifier shall name a base class of the class
4652 // being defined.
4653
4654 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4655 cast<CXXRecordDecl>(NamedContext))) {
4656 if (CurContext == NamedContext) {
4657 Diag(NameLoc,
4658 diag::err_using_decl_nested_name_specifier_is_current_class)
4659 << SS.getRange();
4660 return true;
4661 }
4662
4663 Diag(SS.getRange().getBegin(),
4664 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4665 << (NestedNameSpecifier*) SS.getScopeRep()
4666 << cast<CXXRecordDecl>(CurContext)
4667 << SS.getRange();
4668 return true;
4669 }
4670
4671 return false;
4672 }
4673
4674 // C++03 [namespace.udecl]p4:
4675 // A using-declaration used as a member-declaration shall refer
4676 // to a member of a base class of the class being defined [etc.].
4677
4678 // Salient point: SS doesn't have to name a base class as long as
4679 // lookup only finds members from base classes. Therefore we can
4680 // diagnose here only if we can prove that that can't happen,
4681 // i.e. if the class hierarchies provably don't intersect.
4682
4683 // TODO: it would be nice if "definitely valid" results were cached
4684 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4685 // need to be repeated.
4686
4687 struct UserData {
4688 llvm::DenseSet<const CXXRecordDecl*> Bases;
4689
4690 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4691 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4692 Data->Bases.insert(Base);
4693 return true;
4694 }
4695
4696 bool hasDependentBases(const CXXRecordDecl *Class) {
4697 return !Class->forallBases(collect, this);
4698 }
4699
4700 /// Returns true if the base is dependent or is one of the
4701 /// accumulated base classes.
4702 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4703 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4704 return !Data->Bases.count(Base);
4705 }
4706
4707 bool mightShareBases(const CXXRecordDecl *Class) {
4708 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4709 }
4710 };
4711
4712 UserData Data;
4713
4714 // Returns false if we find a dependent base.
4715 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4716 return false;
4717
4718 // Returns false if the class has a dependent base or if it or one
4719 // of its bases is present in the base set of the current context.
4720 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4721 return false;
4722
4723 Diag(SS.getRange().getBegin(),
4724 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4725 << (NestedNameSpecifier*) SS.getScopeRep()
4726 << cast<CXXRecordDecl>(CurContext)
4727 << SS.getRange();
4728
4729 return true;
John McCallb96ec562009-12-04 22:46:56 +00004730}
4731
Richard Smithdda56e42011-04-15 14:24:37 +00004732Decl *Sema::ActOnAliasDeclaration(Scope *S,
4733 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004734 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00004735 SourceLocation UsingLoc,
4736 UnqualifiedId &Name,
4737 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00004738 // Skip up to the relevant declaration scope.
4739 while (S->getFlags() & Scope::TemplateParamScope)
4740 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00004741 assert((S->getFlags() & Scope::DeclScope) &&
4742 "got alias-declaration outside of declaration scope");
4743
4744 if (Type.isInvalid())
4745 return 0;
4746
4747 bool Invalid = false;
4748 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4749 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00004750 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004751
4752 if (DiagnoseClassNameShadow(CurContext, NameInfo))
4753 return 0;
4754
4755 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004756 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00004757 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00004758 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
4759 TInfo->getTypeLoc().getBeginLoc());
4760 }
Richard Smithdda56e42011-04-15 14:24:37 +00004761
4762 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4763 LookupName(Previous, S);
4764
4765 // Warn about shadowing the name of a template parameter.
4766 if (Previous.isSingleResult() &&
4767 Previous.getFoundDecl()->isTemplateParameter()) {
4768 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4769 Previous.getFoundDecl()))
4770 Invalid = true;
4771 Previous.clear();
4772 }
4773
4774 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4775 "name in alias declaration must be an identifier");
4776 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4777 Name.StartLocation,
4778 Name.Identifier, TInfo);
4779
4780 NewTD->setAccess(AS);
4781
4782 if (Invalid)
4783 NewTD->setInvalidDecl();
4784
Richard Smith3f1b5d02011-05-05 21:57:07 +00004785 CheckTypedefForVariablyModifiedType(S, NewTD);
4786 Invalid |= NewTD->isInvalidDecl();
4787
Richard Smithdda56e42011-04-15 14:24:37 +00004788 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00004789
4790 NamedDecl *NewND;
4791 if (TemplateParamLists.size()) {
4792 TypeAliasTemplateDecl *OldDecl = 0;
4793 TemplateParameterList *OldTemplateParams = 0;
4794
4795 if (TemplateParamLists.size() != 1) {
4796 Diag(UsingLoc, diag::err_alias_template_extra_headers)
4797 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
4798 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
4799 }
4800 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
4801
4802 // Only consider previous declarations in the same scope.
4803 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
4804 /*ExplicitInstantiationOrSpecialization*/false);
4805 if (!Previous.empty()) {
4806 Redeclaration = true;
4807
4808 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
4809 if (!OldDecl && !Invalid) {
4810 Diag(UsingLoc, diag::err_redefinition_different_kind)
4811 << Name.Identifier;
4812
4813 NamedDecl *OldD = Previous.getRepresentativeDecl();
4814 if (OldD->getLocation().isValid())
4815 Diag(OldD->getLocation(), diag::note_previous_definition);
4816
4817 Invalid = true;
4818 }
4819
4820 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
4821 if (TemplateParameterListsAreEqual(TemplateParams,
4822 OldDecl->getTemplateParameters(),
4823 /*Complain=*/true,
4824 TPL_TemplateMatch))
4825 OldTemplateParams = OldDecl->getTemplateParameters();
4826 else
4827 Invalid = true;
4828
4829 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
4830 if (!Invalid &&
4831 !Context.hasSameType(OldTD->getUnderlyingType(),
4832 NewTD->getUnderlyingType())) {
4833 // FIXME: The C++0x standard does not clearly say this is ill-formed,
4834 // but we can't reasonably accept it.
4835 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
4836 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
4837 if (OldTD->getLocation().isValid())
4838 Diag(OldTD->getLocation(), diag::note_previous_definition);
4839 Invalid = true;
4840 }
4841 }
4842 }
4843
4844 // Merge any previous default template arguments into our parameters,
4845 // and check the parameter list.
4846 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
4847 TPC_TypeAliasTemplate))
4848 return 0;
4849
4850 TypeAliasTemplateDecl *NewDecl =
4851 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
4852 Name.Identifier, TemplateParams,
4853 NewTD);
4854
4855 NewDecl->setAccess(AS);
4856
4857 if (Invalid)
4858 NewDecl->setInvalidDecl();
4859 else if (OldDecl)
4860 NewDecl->setPreviousDeclaration(OldDecl);
4861
4862 NewND = NewDecl;
4863 } else {
4864 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
4865 NewND = NewTD;
4866 }
Richard Smithdda56e42011-04-15 14:24:37 +00004867
4868 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00004869 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00004870
Richard Smith3f1b5d02011-05-05 21:57:07 +00004871 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00004872}
4873
John McCall48871652010-08-21 09:40:31 +00004874Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004875 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004876 SourceLocation AliasLoc,
4877 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004878 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004879 SourceLocation IdentLoc,
4880 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004881
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004882 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004883 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4884 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004885
Anders Carlssondca83c42009-03-28 06:23:46 +00004886 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004887 NamedDecl *PrevDecl
4888 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4889 ForRedeclaration);
4890 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4891 PrevDecl = 0;
4892
4893 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004894 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004895 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004896 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004897 // FIXME: At some point, we'll want to create the (redundant)
4898 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004899 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004900 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004901 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004902 }
Mike Stump11289f42009-09-09 15:08:12 +00004903
Anders Carlssondca83c42009-03-28 06:23:46 +00004904 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4905 diag::err_redefinition_different_kind;
4906 Diag(AliasLoc, DiagID) << Alias;
4907 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004908 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004909 }
4910
John McCall27b18f82009-11-17 02:14:36 +00004911 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004912 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004913
John McCall9f3059a2009-10-09 21:13:30 +00004914 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004915 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4916 CTC_NoKeywords, 0)) {
4917 if (R.getAsSingle<NamespaceDecl>() ||
4918 R.getAsSingle<NamespaceAliasDecl>()) {
4919 if (DeclContext *DC = computeDeclContext(SS, false))
4920 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4921 << Ident << DC << Corrected << SS.getRange()
4922 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4923 else
4924 Diag(IdentLoc, diag::err_using_directive_suggest)
4925 << Ident << Corrected
4926 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4927
4928 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4929 << Corrected;
4930
4931 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004932 } else {
4933 R.clear();
4934 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004935 }
4936 }
4937
4938 if (R.empty()) {
4939 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004940 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004941 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004942 }
Mike Stump11289f42009-09-09 15:08:12 +00004943
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004944 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004945 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00004946 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00004947 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004948
John McCalld8d0d432010-02-16 06:53:13 +00004949 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004950 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004951}
4952
Douglas Gregora57478e2010-05-01 15:04:51 +00004953namespace {
4954 /// \brief Scoped object used to handle the state changes required in Sema
4955 /// to implicitly define the body of a C++ member function;
4956 class ImplicitlyDefinedFunctionScope {
4957 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00004958 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00004959
4960 public:
4961 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00004962 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00004963 {
Douglas Gregora57478e2010-05-01 15:04:51 +00004964 S.PushFunctionScope();
4965 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4966 }
4967
4968 ~ImplicitlyDefinedFunctionScope() {
4969 S.PopExpressionEvaluationContext();
4970 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00004971 }
4972 };
4973}
4974
Sebastian Redlc15c3262010-09-13 22:02:47 +00004975static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4976 CXXRecordDecl *D) {
4977 ASTContext &Context = Self.Context;
4978 QualType ClassType = Context.getTypeDeclType(D);
4979 DeclarationName ConstructorName
4980 = Context.DeclarationNames.getCXXConstructorName(
4981 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4982
4983 DeclContext::lookup_const_iterator Con, ConEnd;
4984 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4985 Con != ConEnd; ++Con) {
4986 // FIXME: In C++0x, a constructor template can be a default constructor.
4987 if (isa<FunctionTemplateDecl>(*Con))
4988 continue;
4989
4990 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4991 if (Constructor->isDefaultConstructor())
4992 return Constructor;
4993 }
4994 return 0;
4995}
4996
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004997Sema::ImplicitExceptionSpecification
4998Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00004999 // C++ [except.spec]p14:
5000 // An implicitly declared special member function (Clause 12) shall have an
5001 // exception-specification. [...]
5002 ImplicitExceptionSpecification ExceptSpec(Context);
5003
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005004 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005005 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5006 BEnd = ClassDecl->bases_end();
5007 B != BEnd; ++B) {
5008 if (B->isVirtual()) // Handled below.
5009 continue;
5010
Douglas Gregor9672f922010-07-03 00:47:00 +00005011 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5012 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunt88c75c32011-05-09 21:45:35 +00005013 if (!BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005014 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00005015 else if (CXXConstructorDecl *Constructor
5016 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005017 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005018 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005019 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005020
5021 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005022 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5023 BEnd = ClassDecl->vbases_end();
5024 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00005025 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5026 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunt88c75c32011-05-09 21:45:35 +00005027 if (!BaseClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005028 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5029 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00005030 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005031 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005032 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005033 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005034
5035 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005036 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5037 FEnd = ClassDecl->field_end();
5038 F != FEnd; ++F) {
5039 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00005040 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5041 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Alexis Hunt88c75c32011-05-09 21:45:35 +00005042 if (!FieldClassDecl->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005043 ExceptSpec.CalledDecl(
5044 DeclareImplicitDefaultConstructor(FieldClassDecl));
5045 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00005046 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00005047 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005048 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005049 }
John McCalldb40c7f2010-12-14 08:05:40 +00005050
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005051 return ExceptSpec;
5052}
5053
5054CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5055 CXXRecordDecl *ClassDecl) {
5056 // C++ [class.ctor]p5:
5057 // A default constructor for a class X is a constructor of class X
5058 // that can be called without an argument. If there is no
5059 // user-declared constructor for class X, a default constructor is
5060 // implicitly declared. An implicitly-declared default constructor
5061 // is an inline public member of its class.
5062 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5063 "Should not build implicit default constructor!");
5064
5065 ImplicitExceptionSpecification Spec =
5066 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5067 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005068
Douglas Gregor6d880b12010-07-01 22:31:05 +00005069 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005070 CanQualType ClassType
5071 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005072 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005073 DeclarationName Name
5074 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005075 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005076 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00005077 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005078 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005079 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005080 /*TInfo=*/0,
5081 /*isExplicit=*/false,
5082 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005083 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005084 DefaultCon->setAccess(AS_public);
5085 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00005086 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00005087
5088 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00005089 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5090
Douglas Gregor0be31a22010-07-02 17:43:08 +00005091 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00005092 PushOnScopeChains(DefaultCon, S, false);
5093 ClassDecl->addDecl(DefaultCon);
5094
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005095 return DefaultCon;
5096}
5097
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005098void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5099 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00005100 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005101 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00005102 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005103
Anders Carlsson423f5d82010-04-23 16:04:08 +00005104 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00005105 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00005106
Douglas Gregora57478e2010-05-01 15:04:51 +00005107 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005108 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00005109 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005110 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005111 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Huntbe3f9ec2011-05-10 00:41:46 +00005112 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00005113 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00005114 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00005115 }
Douglas Gregor73193272010-09-20 16:48:21 +00005116
5117 SourceLocation Loc = Constructor->getLocation();
5118 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5119
5120 Constructor->setUsed();
5121 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00005122
5123 if (ASTMutationListener *L = getASTMutationListener()) {
5124 L->CompletedImplicitDefinition(Constructor);
5125 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005126}
5127
Sebastian Redl08905022011-02-05 19:23:19 +00005128void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
5129 // We start with an initial pass over the base classes to collect those that
5130 // inherit constructors from. If there are none, we can forgo all further
5131 // processing.
5132 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
5133 BasesVector BasesToInheritFrom;
5134 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
5135 BaseE = ClassDecl->bases_end();
5136 BaseIt != BaseE; ++BaseIt) {
5137 if (BaseIt->getInheritConstructors()) {
5138 QualType Base = BaseIt->getType();
5139 if (Base->isDependentType()) {
5140 // If we inherit constructors from anything that is dependent, just
5141 // abort processing altogether. We'll get another chance for the
5142 // instantiations.
5143 return;
5144 }
5145 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
5146 }
5147 }
5148 if (BasesToInheritFrom.empty())
5149 return;
5150
5151 // Now collect the constructors that we already have in the current class.
5152 // Those take precedence over inherited constructors.
5153 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5154 // unless there is a user-declared constructor with the same signature in
5155 // the class where the using-declaration appears.
5156 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5157 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5158 CtorE = ClassDecl->ctor_end();
5159 CtorIt != CtorE; ++CtorIt) {
5160 ExistingConstructors.insert(
5161 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5162 }
5163
5164 Scope *S = getScopeForContext(ClassDecl);
5165 DeclarationName CreatedCtorName =
5166 Context.DeclarationNames.getCXXConstructorName(
5167 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5168
5169 // Now comes the true work.
5170 // First, we keep a map from constructor types to the base that introduced
5171 // them. Needed for finding conflicting constructors. We also keep the
5172 // actually inserted declarations in there, for pretty diagnostics.
5173 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5174 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5175 ConstructorToSourceMap InheritedConstructors;
5176 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5177 BaseE = BasesToInheritFrom.end();
5178 BaseIt != BaseE; ++BaseIt) {
5179 const RecordType *Base = *BaseIt;
5180 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5181 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5182 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5183 CtorE = BaseDecl->ctor_end();
5184 CtorIt != CtorE; ++CtorIt) {
5185 // Find the using declaration for inheriting this base's constructors.
5186 DeclarationName Name =
5187 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5188 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5189 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5190 SourceLocation UsingLoc = UD ? UD->getLocation() :
5191 ClassDecl->getLocation();
5192
5193 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5194 // from the class X named in the using-declaration consists of actual
5195 // constructors and notional constructors that result from the
5196 // transformation of defaulted parameters as follows:
5197 // - all non-template default constructors of X, and
5198 // - for each non-template constructor of X that has at least one
5199 // parameter with a default argument, the set of constructors that
5200 // results from omitting any ellipsis parameter specification and
5201 // successively omitting parameters with a default argument from the
5202 // end of the parameter-type-list.
5203 CXXConstructorDecl *BaseCtor = *CtorIt;
5204 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5205 const FunctionProtoType *BaseCtorType =
5206 BaseCtor->getType()->getAs<FunctionProtoType>();
5207
5208 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5209 maxParams = BaseCtor->getNumParams();
5210 params <= maxParams; ++params) {
5211 // Skip default constructors. They're never inherited.
5212 if (params == 0)
5213 continue;
5214 // Skip copy and move constructors for the same reason.
5215 if (CanBeCopyOrMove && params == 1)
5216 continue;
5217
5218 // Build up a function type for this particular constructor.
5219 // FIXME: The working paper does not consider that the exception spec
5220 // for the inheriting constructor might be larger than that of the
5221 // source. This code doesn't yet, either.
5222 const Type *NewCtorType;
5223 if (params == maxParams)
5224 NewCtorType = BaseCtorType;
5225 else {
5226 llvm::SmallVector<QualType, 16> Args;
5227 for (unsigned i = 0; i < params; ++i) {
5228 Args.push_back(BaseCtorType->getArgType(i));
5229 }
5230 FunctionProtoType::ExtProtoInfo ExtInfo =
5231 BaseCtorType->getExtProtoInfo();
5232 ExtInfo.Variadic = false;
5233 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5234 Args.data(), params, ExtInfo)
5235 .getTypePtr();
5236 }
5237 const Type *CanonicalNewCtorType =
5238 Context.getCanonicalType(NewCtorType);
5239
5240 // Now that we have the type, first check if the class already has a
5241 // constructor with this signature.
5242 if (ExistingConstructors.count(CanonicalNewCtorType))
5243 continue;
5244
5245 // Then we check if we have already declared an inherited constructor
5246 // with this signature.
5247 std::pair<ConstructorToSourceMap::iterator, bool> result =
5248 InheritedConstructors.insert(std::make_pair(
5249 CanonicalNewCtorType,
5250 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5251 if (!result.second) {
5252 // Already in the map. If it came from a different class, that's an
5253 // error. Not if it's from the same.
5254 CanQualType PreviousBase = result.first->second.first;
5255 if (CanonicalBase != PreviousBase) {
5256 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5257 const CXXConstructorDecl *PrevBaseCtor =
5258 PrevCtor->getInheritedConstructor();
5259 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5260
5261 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5262 Diag(BaseCtor->getLocation(),
5263 diag::note_using_decl_constructor_conflict_current_ctor);
5264 Diag(PrevBaseCtor->getLocation(),
5265 diag::note_using_decl_constructor_conflict_previous_ctor);
5266 Diag(PrevCtor->getLocation(),
5267 diag::note_using_decl_constructor_conflict_previous_using);
5268 }
5269 continue;
5270 }
5271
5272 // OK, we're there, now add the constructor.
5273 // C++0x [class.inhctor]p8: [...] that would be performed by a
5274 // user-writtern inline constructor [...]
5275 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5276 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00005277 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5278 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005279 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00005280 NewCtor->setAccess(BaseCtor->getAccess());
5281
5282 // Build up the parameter decls and add them.
5283 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5284 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005285 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5286 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00005287 /*IdentifierInfo=*/0,
5288 BaseCtorType->getArgType(i),
5289 /*TInfo=*/0, SC_None,
5290 SC_None, /*DefaultArg=*/0));
5291 }
5292 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5293 NewCtor->setInheritedConstructor(BaseCtor);
5294
5295 PushOnScopeChains(NewCtor, S, false);
5296 ClassDecl->addDecl(NewCtor);
5297 result.first->second.second = NewCtor;
5298 }
5299 }
5300 }
5301}
5302
Douglas Gregor0be31a22010-07-02 17:43:08 +00005303CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00005304 // C++ [class.dtor]p2:
5305 // If a class has no user-declared destructor, a destructor is
5306 // declared implicitly. An implicitly-declared destructor is an
5307 // inline public member of its class.
5308
5309 // C++ [except.spec]p14:
5310 // An implicitly declared special member function (Clause 12) shall have
5311 // an exception-specification.
5312 ImplicitExceptionSpecification ExceptSpec(Context);
5313
5314 // Direct base-class destructors.
5315 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5316 BEnd = ClassDecl->bases_end();
5317 B != BEnd; ++B) {
5318 if (B->isVirtual()) // Handled below.
5319 continue;
5320
5321 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5322 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005323 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005324 }
5325
5326 // Virtual base-class destructors.
5327 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5328 BEnd = ClassDecl->vbases_end();
5329 B != BEnd; ++B) {
5330 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5331 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005332 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005333 }
5334
5335 // Field destructors.
5336 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5337 FEnd = ClassDecl->field_end();
5338 F != FEnd; ++F) {
5339 if (const RecordType *RecordTy
5340 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5341 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005342 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005343 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005344
Douglas Gregor7454c562010-07-02 20:37:36 +00005345 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00005346 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005347 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005348 EPI.NumExceptions = ExceptSpec.size();
5349 EPI.Exceptions = ExceptSpec.data();
5350 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005351
Douglas Gregorf1203042010-07-01 19:09:28 +00005352 CanQualType ClassType
5353 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005354 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00005355 DeclarationName Name
5356 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005357 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00005358 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005359 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5360 /*isInline=*/true,
5361 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00005362 Destructor->setAccess(AS_public);
5363 Destructor->setImplicit();
5364 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00005365
5366 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00005367 ++ASTContext::NumImplicitDestructorsDeclared;
5368
5369 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005370 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00005371 PushOnScopeChains(Destructor, S, false);
5372 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00005373
5374 // This could be uniqued if it ever proves significant.
5375 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5376
5377 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00005378
Douglas Gregorf1203042010-07-01 19:09:28 +00005379 return Destructor;
5380}
5381
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005382void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00005383 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00005384 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005385 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00005386 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005387 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005388
Douglas Gregor54818f02010-05-12 16:39:35 +00005389 if (Destructor->isInvalidDecl())
5390 return;
5391
Douglas Gregora57478e2010-05-01 15:04:51 +00005392 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005393
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005394 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00005395 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5396 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00005397
Douglas Gregor54818f02010-05-12 16:39:35 +00005398 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005399 Diag(CurrentLocation, diag::note_member_synthesized_at)
5400 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5401
5402 Destructor->setInvalidDecl();
5403 return;
5404 }
5405
Douglas Gregor73193272010-09-20 16:48:21 +00005406 SourceLocation Loc = Destructor->getLocation();
5407 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5408
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005409 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00005410 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00005411
5412 if (ASTMutationListener *L = getASTMutationListener()) {
5413 L->CompletedImplicitDefinition(Destructor);
5414 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005415}
5416
Douglas Gregorb139cd52010-05-01 20:49:11 +00005417/// \brief Builds a statement that copies the given entity from \p From to
5418/// \c To.
5419///
5420/// This routine is used to copy the members of a class with an
5421/// implicitly-declared copy assignment operator. When the entities being
5422/// copied are arrays, this routine builds for loops to copy them.
5423///
5424/// \param S The Sema object used for type-checking.
5425///
5426/// \param Loc The location where the implicit copy is being generated.
5427///
5428/// \param T The type of the expressions being copied. Both expressions must
5429/// have this type.
5430///
5431/// \param To The expression we are copying to.
5432///
5433/// \param From The expression we are copying from.
5434///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005435/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5436/// Otherwise, it's a non-static member subobject.
5437///
Douglas Gregorb139cd52010-05-01 20:49:11 +00005438/// \param Depth Internal parameter recording the depth of the recursion.
5439///
5440/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00005441static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00005442BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00005443 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005444 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005445 // C++0x [class.copy]p30:
5446 // Each subobject is assigned in the manner appropriate to its type:
5447 //
5448 // - if the subobject is of class type, the copy assignment operator
5449 // for the class is used (as if by explicit qualification; that is,
5450 // ignoring any possible virtual overriding functions in more derived
5451 // classes);
5452 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5453 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5454
5455 // Look for operator=.
5456 DeclarationName Name
5457 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5458 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5459 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5460
5461 // Filter out any result that isn't a copy-assignment operator.
5462 LookupResult::Filter F = OpLookup.makeFilter();
5463 while (F.hasNext()) {
5464 NamedDecl *D = F.next();
5465 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5466 if (Method->isCopyAssignmentOperator())
5467 continue;
5468
5469 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00005470 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005471 F.done();
5472
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005473 // Suppress the protected check (C++ [class.protected]) for each of the
5474 // assignment operators we found. This strange dance is required when
5475 // we're assigning via a base classes's copy-assignment operator. To
5476 // ensure that we're getting the right base class subobject (without
5477 // ambiguities), we need to cast "this" to that subobject type; to
5478 // ensure that we don't go through the virtual call mechanism, we need
5479 // to qualify the operator= name with the base class (see below). However,
5480 // this means that if the base class has a protected copy assignment
5481 // operator, the protected member access check will fail. So, we
5482 // rewrite "protected" access to "public" access in this case, since we
5483 // know by construction that we're calling from a derived class.
5484 if (CopyingBaseSubobject) {
5485 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5486 L != LEnd; ++L) {
5487 if (L.getAccess() == AS_protected)
5488 L.setAccess(AS_public);
5489 }
5490 }
5491
Douglas Gregorb139cd52010-05-01 20:49:11 +00005492 // Create the nested-name-specifier that will be used to qualify the
5493 // reference to operator=; this is required to suppress the virtual
5494 // call mechanism.
5495 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005496 SS.MakeTrivial(S.Context,
5497 NestedNameSpecifier::Create(S.Context, 0, false,
5498 T.getTypePtr()),
5499 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005500
5501 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00005502 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00005503 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005504 /*FirstQualifierInScope=*/0, OpLookup,
5505 /*TemplateArgs=*/0,
5506 /*SuppressQualifierCheck=*/true);
5507 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005508 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005509
5510 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00005511
John McCalldadc5752010-08-24 06:29:42 +00005512 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005513 OpEqualRef.takeAs<Expr>(),
5514 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005515 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005516 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005517
5518 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005519 }
John McCallab8c2732010-03-16 06:11:48 +00005520
Douglas Gregorb139cd52010-05-01 20:49:11 +00005521 // - if the subobject is of scalar type, the built-in assignment
5522 // operator is used.
5523 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5524 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00005525 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005526 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005527 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005528
5529 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005530 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005531
5532 // - if the subobject is an array, each element is assigned, in the
5533 // manner appropriate to the element type;
5534
5535 // Construct a loop over the array bounds, e.g.,
5536 //
5537 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5538 //
5539 // that will copy each of the array elements.
5540 QualType SizeType = S.Context.getSizeType();
5541
5542 // Create the iteration variable.
5543 IdentifierInfo *IterationVarName = 0;
5544 {
5545 llvm::SmallString<8> Str;
5546 llvm::raw_svector_ostream OS(Str);
5547 OS << "__i" << Depth;
5548 IterationVarName = &S.Context.Idents.get(OS.str());
5549 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00005550 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005551 IterationVarName, SizeType,
5552 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005553 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005554
5555 // Initialize the iteration variable to zero.
5556 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005557 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005558
5559 // Create a reference to the iteration variable; we'll use this several
5560 // times throughout.
5561 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00005562 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005563 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5564
5565 // Create the DeclStmt that holds the iteration variable.
5566 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5567
5568 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005569 llvm::APInt Upper
5570 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00005571 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00005572 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00005573 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5574 BO_NE, S.Context.BoolTy,
5575 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005576
5577 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005578 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00005579 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5580 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005581
5582 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005583 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5584 IterationVarRef, Loc));
5585 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5586 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005587
5588 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00005589 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5590 To, From, CopyingBaseSubobject,
5591 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00005592 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005593 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005594
5595 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00005596 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005597 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00005598 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00005599 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005600}
5601
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005602/// \brief Determine whether the given class has a copy assignment operator
5603/// that accepts a const-qualified argument.
5604static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5605 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5606
5607 if (!Class->hasDeclaredCopyAssignment())
5608 S.DeclareImplicitCopyAssignment(Class);
5609
5610 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5611 DeclarationName OpName
5612 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5613
5614 DeclContext::lookup_const_iterator Op, OpEnd;
5615 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5616 // C++ [class.copy]p9:
5617 // A user-declared copy assignment operator is a non-static non-template
5618 // member function of class X with exactly one parameter of type X, X&,
5619 // const X&, volatile X& or const volatile X&.
5620 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5621 if (!Method)
5622 continue;
5623
5624 if (Method->isStatic())
5625 continue;
5626 if (Method->getPrimaryTemplate())
5627 continue;
5628 const FunctionProtoType *FnType =
5629 Method->getType()->getAs<FunctionProtoType>();
5630 assert(FnType && "Overloaded operator has no prototype.");
5631 // Don't assert on this; an invalid decl might have been left in the AST.
5632 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5633 continue;
5634 bool AcceptsConst = true;
5635 QualType ArgType = FnType->getArgType(0);
5636 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5637 ArgType = Ref->getPointeeType();
5638 // Is it a non-const lvalue reference?
5639 if (!ArgType.isConstQualified())
5640 AcceptsConst = false;
5641 }
5642 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5643 continue;
5644
5645 // We have a single argument of type cv X or cv X&, i.e. we've found the
5646 // copy assignment operator. Return whether it accepts const arguments.
5647 return AcceptsConst;
5648 }
5649 assert(Class->isInvalidDecl() &&
5650 "No copy assignment operator declared in valid code.");
5651 return false;
5652}
5653
Douglas Gregor0be31a22010-07-02 17:43:08 +00005654CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005655 // Note: The following rules are largely analoguous to the copy
5656 // constructor rules. Note that virtual bases are not taken into account
5657 // for determining the argument type of the operator. Note also that
5658 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005659
5660
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005661 // C++ [class.copy]p10:
5662 // If the class definition does not explicitly declare a copy
5663 // assignment operator, one is declared implicitly.
5664 // The implicitly-defined copy assignment operator for a class X
5665 // will have the form
5666 //
5667 // X& X::operator=(const X&)
5668 //
5669 // if
5670 bool HasConstCopyAssignment = true;
5671
5672 // -- each direct base class B of X has a copy assignment operator
5673 // whose parameter is of type const B&, const volatile B& or B,
5674 // and
5675 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5676 BaseEnd = ClassDecl->bases_end();
5677 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5678 assert(!Base->getType()->isDependentType() &&
5679 "Cannot generate implicit members for class with dependent bases.");
5680 const CXXRecordDecl *BaseClassDecl
5681 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005682 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005683 }
5684
5685 // -- for all the nonstatic data members of X that are of a class
5686 // type M (or array thereof), each such class type has a copy
5687 // assignment operator whose parameter is of type const M&,
5688 // const volatile M& or M.
5689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5690 FieldEnd = ClassDecl->field_end();
5691 HasConstCopyAssignment && Field != FieldEnd;
5692 ++Field) {
5693 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5694 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5695 const CXXRecordDecl *FieldClassDecl
5696 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005697 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005698 }
5699 }
5700
5701 // Otherwise, the implicitly declared copy assignment operator will
5702 // have the form
5703 //
5704 // X& X::operator=(X&)
5705 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5706 QualType RetType = Context.getLValueReferenceType(ArgType);
5707 if (HasConstCopyAssignment)
5708 ArgType = ArgType.withConst();
5709 ArgType = Context.getLValueReferenceType(ArgType);
5710
Douglas Gregor68e11362010-07-01 17:48:08 +00005711 // C++ [except.spec]p14:
5712 // An implicitly declared special member function (Clause 12) shall have an
5713 // exception-specification. [...]
5714 ImplicitExceptionSpecification ExceptSpec(Context);
5715 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5716 BaseEnd = ClassDecl->bases_end();
5717 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005718 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005719 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005720
5721 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5722 DeclareImplicitCopyAssignment(BaseClassDecl);
5723
Douglas Gregor68e11362010-07-01 17:48:08 +00005724 if (CXXMethodDecl *CopyAssign
5725 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5726 ExceptSpec.CalledDecl(CopyAssign);
5727 }
5728 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5729 FieldEnd = ClassDecl->field_end();
5730 Field != FieldEnd;
5731 ++Field) {
5732 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5733 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005734 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005735 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005736
5737 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5738 DeclareImplicitCopyAssignment(FieldClassDecl);
5739
Douglas Gregor68e11362010-07-01 17:48:08 +00005740 if (CXXMethodDecl *CopyAssign
5741 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5742 ExceptSpec.CalledDecl(CopyAssign);
5743 }
5744 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005745
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005746 // An implicitly-declared copy assignment operator is an inline public
5747 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005748 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005749 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005750 EPI.NumExceptions = ExceptSpec.size();
5751 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005752 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005753 SourceLocation ClassLoc = ClassDecl->getLocation();
5754 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005755 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00005756 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005757 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005758 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005759 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00005760 /*isInline=*/true,
5761 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005762 CopyAssignment->setAccess(AS_public);
5763 CopyAssignment->setImplicit();
5764 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005765
5766 // Add the parameter to the operator.
5767 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005768 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005769 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005770 SC_None,
5771 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005772 CopyAssignment->setParams(&FromParam, 1);
5773
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005774 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005775 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5776
Douglas Gregor0be31a22010-07-02 17:43:08 +00005777 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005778 PushOnScopeChains(CopyAssignment, S, false);
5779 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005780
5781 AddOverriddenMethods(ClassDecl, CopyAssignment);
5782 return CopyAssignment;
5783}
5784
Douglas Gregorb139cd52010-05-01 20:49:11 +00005785void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5786 CXXMethodDecl *CopyAssignOperator) {
5787 assert((CopyAssignOperator->isImplicit() &&
5788 CopyAssignOperator->isOverloadedOperator() &&
5789 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005790 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005791 "DefineImplicitCopyAssignment called for wrong function");
5792
5793 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5794
5795 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5796 CopyAssignOperator->setInvalidDecl();
5797 return;
5798 }
5799
5800 CopyAssignOperator->setUsed();
5801
5802 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005803 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005804
5805 // C++0x [class.copy]p30:
5806 // The implicitly-defined or explicitly-defaulted copy assignment operator
5807 // for a non-union class X performs memberwise copy assignment of its
5808 // subobjects. The direct base classes of X are assigned first, in the
5809 // order of their declaration in the base-specifier-list, and then the
5810 // immediate non-static data members of X are assigned, in the order in
5811 // which they were declared in the class definition.
5812
5813 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005814 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005815
5816 // The parameter for the "other" object, which we are copying from.
5817 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5818 Qualifiers OtherQuals = Other->getType().getQualifiers();
5819 QualType OtherRefType = Other->getType();
5820 if (const LValueReferenceType *OtherRef
5821 = OtherRefType->getAs<LValueReferenceType>()) {
5822 OtherRefType = OtherRef->getPointeeType();
5823 OtherQuals = OtherRefType.getQualifiers();
5824 }
5825
5826 // Our location for everything implicitly-generated.
5827 SourceLocation Loc = CopyAssignOperator->getLocation();
5828
5829 // Construct a reference to the "other" object. We'll be using this
5830 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005831 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005832 assert(OtherRef && "Reference to parameter cannot fail!");
5833
5834 // Construct the "this" pointer. We'll be using this throughout the generated
5835 // ASTs.
5836 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5837 assert(This && "Reference to this cannot fail!");
5838
5839 // Assign base classes.
5840 bool Invalid = false;
5841 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5842 E = ClassDecl->bases_end(); Base != E; ++Base) {
5843 // Form the assignment:
5844 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5845 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005846 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005847 Invalid = true;
5848 continue;
5849 }
5850
John McCallcf142162010-08-07 06:22:56 +00005851 CXXCastPath BasePath;
5852 BasePath.push_back(Base);
5853
Douglas Gregorb139cd52010-05-01 20:49:11 +00005854 // Construct the "from" expression, which is an implicit cast to the
5855 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005856 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00005857 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5858 CK_UncheckedDerivedToBase,
5859 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005860
5861 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005862 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005863
5864 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00005865 To = ImpCastExprToType(To.take(),
5866 Context.getCVRQualifiedType(BaseType,
5867 CopyAssignOperator->getTypeQualifiers()),
5868 CK_UncheckedDerivedToBase,
5869 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005870
5871 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005872 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005873 To.get(), From,
5874 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005875 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005876 Diag(CurrentLocation, diag::note_member_synthesized_at)
5877 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5878 CopyAssignOperator->setInvalidDecl();
5879 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005880 }
5881
5882 // Success! Record the copy.
5883 Statements.push_back(Copy.takeAs<Expr>());
5884 }
5885
5886 // \brief Reference to the __builtin_memcpy function.
5887 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005888 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005889 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005890
5891 // Assign non-static members.
5892 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5893 FieldEnd = ClassDecl->field_end();
5894 Field != FieldEnd; ++Field) {
5895 // Check for members of reference type; we can't copy those.
5896 if (Field->getType()->isReferenceType()) {
5897 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5898 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5899 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005900 Diag(CurrentLocation, diag::note_member_synthesized_at)
5901 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005902 Invalid = true;
5903 continue;
5904 }
5905
5906 // Check for members of const-qualified, non-class type.
5907 QualType BaseType = Context.getBaseElementType(Field->getType());
5908 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5909 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5910 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5911 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005912 Diag(CurrentLocation, diag::note_member_synthesized_at)
5913 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005914 Invalid = true;
5915 continue;
5916 }
5917
5918 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005919 if (FieldType->isIncompleteArrayType()) {
5920 assert(ClassDecl->hasFlexibleArrayMember() &&
5921 "Incomplete array type is not valid");
5922 continue;
5923 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005924
5925 // Build references to the field in the object we're copying from and to.
5926 CXXScopeSpec SS; // Intentionally empty
5927 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5928 LookupMemberName);
5929 MemberLookup.addDecl(*Field);
5930 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005931 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005932 Loc, /*IsArrow=*/false,
5933 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005934 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005935 Loc, /*IsArrow=*/true,
5936 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005937 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5938 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5939
5940 // If the field should be copied with __builtin_memcpy rather than via
5941 // explicit assignments, do so. This optimization only applies for arrays
5942 // of scalars and arrays of class type with trivial copy-assignment
5943 // operators.
5944 if (FieldType->isArrayType() &&
5945 (!BaseType->isRecordType() ||
5946 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5947 ->hasTrivialCopyAssignment())) {
5948 // Compute the size of the memory buffer to be copied.
5949 QualType SizeType = Context.getSizeType();
5950 llvm::APInt Size(Context.getTypeSize(SizeType),
5951 Context.getTypeSizeInChars(BaseType).getQuantity());
5952 for (const ConstantArrayType *Array
5953 = Context.getAsConstantArrayType(FieldType);
5954 Array;
5955 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005956 llvm::APInt ArraySize
5957 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005958 Size *= ArraySize;
5959 }
5960
5961 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005962 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5963 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005964
5965 bool NeedsCollectableMemCpy =
5966 (BaseType->isRecordType() &&
5967 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5968
5969 if (NeedsCollectableMemCpy) {
5970 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005971 // Create a reference to the __builtin_objc_memmove_collectable function.
5972 LookupResult R(*this,
5973 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005974 Loc, LookupOrdinaryName);
5975 LookupName(R, TUScope, true);
5976
5977 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5978 if (!CollectableMemCpy) {
5979 // Something went horribly wrong earlier, and we will have
5980 // complained about it.
5981 Invalid = true;
5982 continue;
5983 }
5984
5985 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5986 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005987 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005988 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5989 }
5990 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005991 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005992 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005993 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5994 LookupOrdinaryName);
5995 LookupName(R, TUScope, true);
5996
5997 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5998 if (!BuiltinMemCpy) {
5999 // Something went horribly wrong earlier, and we will have complained
6000 // about it.
6001 Invalid = true;
6002 continue;
6003 }
6004
6005 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6006 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006007 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006008 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6009 }
6010
John McCall37ad5512010-08-23 06:44:23 +00006011 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006012 CallArgs.push_back(To.takeAs<Expr>());
6013 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006014 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00006015 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006016 if (NeedsCollectableMemCpy)
6017 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006018 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006019 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006020 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006021 else
6022 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00006023 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006024 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00006025 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00006026
Douglas Gregorb139cd52010-05-01 20:49:11 +00006027 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
6028 Statements.push_back(Call.takeAs<Expr>());
6029 continue;
6030 }
6031
6032 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00006033 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00006034 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006035 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006036 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006037 Diag(CurrentLocation, diag::note_member_synthesized_at)
6038 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6039 CopyAssignOperator->setInvalidDecl();
6040 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006041 }
6042
6043 // Success! Record the copy.
6044 Statements.push_back(Copy.takeAs<Stmt>());
6045 }
6046
6047 if (!Invalid) {
6048 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00006049 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006050
John McCalldadc5752010-08-24 06:29:42 +00006051 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006052 if (Return.isInvalid())
6053 Invalid = true;
6054 else {
6055 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00006056
6057 if (Trap.hasErrorOccurred()) {
6058 Diag(CurrentLocation, diag::note_member_synthesized_at)
6059 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6060 Invalid = true;
6061 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006062 }
6063 }
6064
6065 if (Invalid) {
6066 CopyAssignOperator->setInvalidDecl();
6067 return;
6068 }
6069
John McCalldadc5752010-08-24 06:29:42 +00006070 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00006071 /*isStmtExpr=*/false);
6072 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
6073 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00006074
6075 if (ASTMutationListener *L = getASTMutationListener()) {
6076 L->CompletedImplicitDefinition(CopyAssignOperator);
6077 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006078}
6079
Douglas Gregor0be31a22010-07-02 17:43:08 +00006080CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
6081 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00006082 // C++ [class.copy]p4:
6083 // If the class definition does not explicitly declare a copy
6084 // constructor, one is declared implicitly.
6085
Douglas Gregor54be3392010-07-01 17:57:27 +00006086 // C++ [class.copy]p5:
6087 // The implicitly-declared copy constructor for a class X will
6088 // have the form
6089 //
6090 // X::X(const X&)
6091 //
6092 // if
6093 bool HasConstCopyConstructor = true;
6094
6095 // -- each direct or virtual base class B of X has a copy
6096 // constructor whose first parameter is of type const B& or
6097 // const volatile B&, and
6098 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6099 BaseEnd = ClassDecl->bases_end();
6100 HasConstCopyConstructor && Base != BaseEnd;
6101 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00006102 // Virtual bases are handled below.
6103 if (Base->isVirtual())
6104 continue;
6105
Douglas Gregora6d69502010-07-02 23:41:54 +00006106 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00006107 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006108 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6109 DeclareImplicitCopyConstructor(BaseClassDecl);
6110
Douglas Gregorcfe68222010-07-01 18:27:03 +00006111 HasConstCopyConstructor
6112 = BaseClassDecl->hasConstCopyConstructor(Context);
6113 }
6114
6115 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6116 BaseEnd = ClassDecl->vbases_end();
6117 HasConstCopyConstructor && Base != BaseEnd;
6118 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006119 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00006120 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006121 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6122 DeclareImplicitCopyConstructor(BaseClassDecl);
6123
Douglas Gregor54be3392010-07-01 17:57:27 +00006124 HasConstCopyConstructor
6125 = BaseClassDecl->hasConstCopyConstructor(Context);
6126 }
6127
6128 // -- for all the nonstatic data members of X that are of a
6129 // class type M (or array thereof), each such class type
6130 // has a copy constructor whose first parameter is of type
6131 // const M& or const volatile M&.
6132 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6133 FieldEnd = ClassDecl->field_end();
6134 HasConstCopyConstructor && Field != FieldEnd;
6135 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00006136 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00006137 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006138 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00006139 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006140 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6141 DeclareImplicitCopyConstructor(FieldClassDecl);
6142
Douglas Gregor54be3392010-07-01 17:57:27 +00006143 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00006144 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00006145 }
6146 }
6147
6148 // Otherwise, the implicitly declared copy constructor will have
6149 // the form
6150 //
6151 // X::X(X&)
6152 QualType ClassType = Context.getTypeDeclType(ClassDecl);
6153 QualType ArgType = ClassType;
6154 if (HasConstCopyConstructor)
6155 ArgType = ArgType.withConst();
6156 ArgType = Context.getLValueReferenceType(ArgType);
6157
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006158 // C++ [except.spec]p14:
6159 // An implicitly declared special member function (Clause 12) shall have an
6160 // exception-specification. [...]
6161 ImplicitExceptionSpecification ExceptSpec(Context);
6162 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6163 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6164 BaseEnd = ClassDecl->bases_end();
6165 Base != BaseEnd;
6166 ++Base) {
6167 // Virtual bases are handled below.
6168 if (Base->isVirtual())
6169 continue;
6170
Douglas Gregora6d69502010-07-02 23:41:54 +00006171 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006172 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006173 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6174 DeclareImplicitCopyConstructor(BaseClassDecl);
6175
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006176 if (CXXConstructorDecl *CopyConstructor
6177 = BaseClassDecl->getCopyConstructor(Context, Quals))
6178 ExceptSpec.CalledDecl(CopyConstructor);
6179 }
6180 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6181 BaseEnd = ClassDecl->vbases_end();
6182 Base != BaseEnd;
6183 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006184 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006185 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006186 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6187 DeclareImplicitCopyConstructor(BaseClassDecl);
6188
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006189 if (CXXConstructorDecl *CopyConstructor
6190 = BaseClassDecl->getCopyConstructor(Context, Quals))
6191 ExceptSpec.CalledDecl(CopyConstructor);
6192 }
6193 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6194 FieldEnd = ClassDecl->field_end();
6195 Field != FieldEnd;
6196 ++Field) {
6197 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6198 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006199 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006200 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006201 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6202 DeclareImplicitCopyConstructor(FieldClassDecl);
6203
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006204 if (CXXConstructorDecl *CopyConstructor
6205 = FieldClassDecl->getCopyConstructor(Context, Quals))
6206 ExceptSpec.CalledDecl(CopyConstructor);
6207 }
6208 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006209
Douglas Gregor54be3392010-07-01 17:57:27 +00006210 // An implicitly-declared copy constructor is an inline public
6211 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00006212 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006213 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00006214 EPI.NumExceptions = ExceptSpec.size();
6215 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00006216 DeclarationName Name
6217 = Context.DeclarationNames.getCXXConstructorName(
6218 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006219 SourceLocation ClassLoc = ClassDecl->getLocation();
6220 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor54be3392010-07-01 17:57:27 +00006221 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00006222 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00006223 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006224 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00006225 /*TInfo=*/0,
6226 /*isExplicit=*/false,
6227 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006228 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00006229 CopyConstructor->setAccess(AS_public);
Douglas Gregor54be3392010-07-01 17:57:27 +00006230 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6231
Douglas Gregora6d69502010-07-02 23:41:54 +00006232 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00006233 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6234
Douglas Gregor54be3392010-07-01 17:57:27 +00006235 // Add the parameter to the constructor.
6236 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006237 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00006238 /*IdentifierInfo=*/0,
6239 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006240 SC_None,
6241 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00006242 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00006243 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00006244 PushOnScopeChains(CopyConstructor, S, false);
6245 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00006246
6247 return CopyConstructor;
6248}
6249
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006250void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6251 CXXConstructorDecl *CopyConstructor,
6252 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00006253 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00006254 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00006255 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006256 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006257
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00006258 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006259 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006260
Douglas Gregora57478e2010-05-01 15:04:51 +00006261 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006262 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006263
Alexis Hunt1d792652011-01-08 20:30:50 +00006264 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006265 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00006266 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00006267 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00006268 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00006269 } else {
6270 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6271 CopyConstructor->getLocation(),
6272 MultiStmtArg(*this, 0, 0),
6273 /*isStmtExpr=*/false)
6274 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00006275 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00006276
6277 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00006278
6279 if (ASTMutationListener *L = getASTMutationListener()) {
6280 L->CompletedImplicitDefinition(CopyConstructor);
6281 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006282}
6283
John McCalldadc5752010-08-24 06:29:42 +00006284ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006285Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00006286 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006287 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006288 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006289 unsigned ConstructKind,
6290 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00006291 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00006292
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006293 // C++0x [class.copy]p34:
6294 // When certain criteria are met, an implementation is allowed to
6295 // omit the copy/move construction of a class object, even if the
6296 // copy/move constructor and/or destructor for the object have
6297 // side effects. [...]
6298 // - when a temporary class object that has not been bound to a
6299 // reference (12.2) would be copied/moved to a class object
6300 // with the same cv-unqualified type, the copy/move operation
6301 // can be omitted by constructing the temporary object
6302 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00006303 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00006304 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006305 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00006306 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00006307 }
Mike Stump11289f42009-09-09 15:08:12 +00006308
6309 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006310 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006311 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00006312}
6313
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006314/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6315/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00006316ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006317Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6318 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006319 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006320 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006321 unsigned ConstructKind,
6322 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006323 unsigned NumExprs = ExprArgs.size();
6324 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00006325
Nick Lewyckyd4693212011-03-25 01:44:32 +00006326 for (specific_attr_iterator<NonNullAttr>
6327 i = Constructor->specific_attr_begin<NonNullAttr>(),
6328 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6329 const NonNullAttr *NonNull = *i;
6330 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6331 }
6332
Douglas Gregor27381f32009-11-23 12:27:39 +00006333 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00006334 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006335 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00006336 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006337 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6338 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006339}
6340
Mike Stump11289f42009-09-09 15:08:12 +00006341bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006342 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006343 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00006344 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00006345 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00006346 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00006347 move(Exprs), false, CXXConstructExpr::CK_Complete,
6348 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006349 if (TempResult.isInvalid())
6350 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006351
Anders Carlsson6eb55572009-08-25 05:12:04 +00006352 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00006353 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00006354 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00006355 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00006356 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00006357
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006358 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00006359}
6360
John McCall03c48482010-02-02 09:10:11 +00006361void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00006362 if (VD->isInvalidDecl()) return;
6363
John McCall03c48482010-02-02 09:10:11 +00006364 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00006365 if (ClassDecl->isInvalidDecl()) return;
6366 if (ClassDecl->hasTrivialDestructor()) return;
6367 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00006368
Chandler Carruth86d17d32011-03-27 21:26:48 +00006369 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6370 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6371 CheckDestructorAccess(VD->getLocation(), Destructor,
6372 PDiag(diag::err_access_dtor_var)
6373 << VD->getDeclName()
6374 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00006375
Chandler Carruth86d17d32011-03-27 21:26:48 +00006376 if (!VD->hasGlobalStorage()) return;
6377
6378 // Emit warning for non-trivial dtor in global scope (a real global,
6379 // class-static, function-static).
6380 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6381
6382 // TODO: this should be re-enabled for static locals by !CXAAtExit
6383 if (!VD->isStaticLocal())
6384 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006385}
6386
Mike Stump11289f42009-09-09 15:08:12 +00006387/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006388/// ActOnDeclarator, when a C++ direct initializer is present.
6389/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00006390void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00006391 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006392 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00006393 SourceLocation RParenLoc,
6394 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00006395 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006396
6397 // If there is no declaration, there was an error parsing it. Just ignore
6398 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00006399 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006400 return;
Mike Stump11289f42009-09-09 15:08:12 +00006401
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006402 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6403 if (!VDecl) {
6404 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6405 RealDecl->setInvalidDecl();
6406 return;
6407 }
6408
Richard Smith30482bc2011-02-20 03:19:35 +00006409 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6410 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00006411 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6412 if (Exprs.size() > 1) {
6413 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6414 diag::err_auto_var_init_multiple_expressions)
6415 << VDecl->getDeclName() << VDecl->getType()
6416 << VDecl->getSourceRange();
6417 RealDecl->setInvalidDecl();
6418 return;
6419 }
6420
6421 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00006422 TypeSourceInfo *DeducedType = 0;
6423 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00006424 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6425 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6426 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00006427 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00006428 RealDecl->setInvalidDecl();
6429 return;
6430 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006431 VDecl->setTypeSourceInfo(DeducedType);
6432 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00006433
6434 // If this is a redeclaration, check that the type we just deduced matches
6435 // the previously declared type.
6436 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6437 MergeVarDeclTypes(VDecl, Old);
6438 }
6439
Douglas Gregor402250f2009-08-26 21:14:46 +00006440 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006441 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006442 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6443 //
6444 // Clients that want to distinguish between the two forms, can check for
6445 // direct initializer using VarDecl::hasCXXDirectInitializer().
6446 // A major benefit is that clients that don't particularly care about which
6447 // exactly form was it (like the CodeGen) can handle both cases without
6448 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006449
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006450 // C++ 8.5p11:
6451 // The form of initialization (using parentheses or '=') is generally
6452 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006453 // class type.
6454
Douglas Gregor50dc2192010-02-11 22:55:30 +00006455 if (!VDecl->getType()->isDependentType() &&
6456 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00006457 diag::err_typecheck_decl_incomplete_type)) {
6458 VDecl->setInvalidDecl();
6459 return;
6460 }
6461
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006462 // The variable can not have an abstract class type.
6463 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6464 diag::err_abstract_type_in_decl,
6465 AbstractVariableType))
6466 VDecl->setInvalidDecl();
6467
Sebastian Redl5ca79842010-02-01 20:16:42 +00006468 const VarDecl *Def;
6469 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006470 Diag(VDecl->getLocation(), diag::err_redefinition)
6471 << VDecl->getDeclName();
6472 Diag(Def->getLocation(), diag::note_previous_definition);
6473 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006474 return;
6475 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00006476
Douglas Gregorf0f83692010-08-24 05:27:49 +00006477 // C++ [class.static.data]p4
6478 // If a static data member is of const integral or const
6479 // enumeration type, its declaration in the class definition can
6480 // specify a constant-initializer which shall be an integral
6481 // constant expression (5.19). In that case, the member can appear
6482 // in integral constant expressions. The member shall still be
6483 // defined in a namespace scope if it is used in the program and the
6484 // namespace scope definition shall not contain an initializer.
6485 //
6486 // We already performed a redefinition check above, but for static
6487 // data members we also need to check whether there was an in-class
6488 // declaration with an initializer.
6489 const VarDecl* PrevInit = 0;
6490 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6491 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6492 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6493 return;
6494 }
6495
Douglas Gregor71f39c92010-12-16 01:31:22 +00006496 bool IsDependent = false;
6497 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6498 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6499 VDecl->setInvalidDecl();
6500 return;
6501 }
6502
6503 if (Exprs.get()[I]->isTypeDependent())
6504 IsDependent = true;
6505 }
6506
Douglas Gregor50dc2192010-02-11 22:55:30 +00006507 // If either the declaration has a dependent type or if any of the
6508 // expressions is type-dependent, we represent the initialization
6509 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00006510 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00006511 // Let clients know that initialization was done with a direct initializer.
6512 VDecl->setCXXDirectInitializer(true);
6513
6514 // Store the initialization expressions as a ParenListExpr.
6515 unsigned NumExprs = Exprs.size();
6516 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6517 (Expr **)Exprs.release(),
6518 NumExprs, RParenLoc));
6519 return;
6520 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006521
6522 // Capture the variable that is being initialized and the style of
6523 // initialization.
6524 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6525
6526 // FIXME: Poor source location information.
6527 InitializationKind Kind
6528 = InitializationKind::CreateDirect(VDecl->getLocation(),
6529 LParenLoc, RParenLoc);
6530
6531 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00006532 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00006533 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006534 if (Result.isInvalid()) {
6535 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006536 return;
6537 }
John McCallacf0ee52010-10-08 02:01:28 +00006538
6539 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006540
Douglas Gregora40433a2010-12-07 00:41:46 +00006541 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00006542 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006543 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006544
John McCall8b7fd8f12011-01-19 11:48:09 +00006545 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006546}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006547
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006548/// \brief Given a constructor and the set of arguments provided for the
6549/// constructor, convert the arguments and add any required default arguments
6550/// to form a proper call to this constructor.
6551///
6552/// \returns true if an error occurred, false otherwise.
6553bool
6554Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6555 MultiExprArg ArgsPtr,
6556 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00006557 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006558 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6559 unsigned NumArgs = ArgsPtr.size();
6560 Expr **Args = (Expr **)ArgsPtr.get();
6561
6562 const FunctionProtoType *Proto
6563 = Constructor->getType()->getAs<FunctionProtoType>();
6564 assert(Proto && "Constructor without a prototype?");
6565 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006566
6567 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006568 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006569 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006570 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006571 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006572
6573 VariadicCallType CallType =
6574 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6575 llvm::SmallVector<Expr *, 8> AllArgs;
6576 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6577 Proto, 0, Args, NumArgs, AllArgs,
6578 CallType);
6579 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6580 ConvertedArgs.push_back(AllArgs[i]);
6581 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006582}
6583
Anders Carlssone363c8e2009-12-12 00:32:00 +00006584static inline bool
6585CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6586 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006587 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00006588 if (isa<NamespaceDecl>(DC)) {
6589 return SemaRef.Diag(FnDecl->getLocation(),
6590 diag::err_operator_new_delete_declared_in_namespace)
6591 << FnDecl->getDeclName();
6592 }
6593
6594 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00006595 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006596 return SemaRef.Diag(FnDecl->getLocation(),
6597 diag::err_operator_new_delete_declared_static)
6598 << FnDecl->getDeclName();
6599 }
6600
Anders Carlsson60659a82009-12-12 02:43:16 +00006601 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00006602}
6603
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006604static inline bool
6605CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6606 CanQualType ExpectedResultType,
6607 CanQualType ExpectedFirstParamType,
6608 unsigned DependentParamTypeDiag,
6609 unsigned InvalidParamTypeDiag) {
6610 QualType ResultType =
6611 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6612
6613 // Check that the result type is not dependent.
6614 if (ResultType->isDependentType())
6615 return SemaRef.Diag(FnDecl->getLocation(),
6616 diag::err_operator_new_delete_dependent_result_type)
6617 << FnDecl->getDeclName() << ExpectedResultType;
6618
6619 // Check that the result type is what we expect.
6620 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6621 return SemaRef.Diag(FnDecl->getLocation(),
6622 diag::err_operator_new_delete_invalid_result_type)
6623 << FnDecl->getDeclName() << ExpectedResultType;
6624
6625 // A function template must have at least 2 parameters.
6626 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6627 return SemaRef.Diag(FnDecl->getLocation(),
6628 diag::err_operator_new_delete_template_too_few_parameters)
6629 << FnDecl->getDeclName();
6630
6631 // The function decl must have at least 1 parameter.
6632 if (FnDecl->getNumParams() == 0)
6633 return SemaRef.Diag(FnDecl->getLocation(),
6634 diag::err_operator_new_delete_too_few_parameters)
6635 << FnDecl->getDeclName();
6636
6637 // Check the the first parameter type is not dependent.
6638 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6639 if (FirstParamType->isDependentType())
6640 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6641 << FnDecl->getDeclName() << ExpectedFirstParamType;
6642
6643 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00006644 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006645 ExpectedFirstParamType)
6646 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6647 << FnDecl->getDeclName() << ExpectedFirstParamType;
6648
6649 return false;
6650}
6651
Anders Carlsson12308f42009-12-11 23:23:22 +00006652static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006653CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006654 // C++ [basic.stc.dynamic.allocation]p1:
6655 // A program is ill-formed if an allocation function is declared in a
6656 // namespace scope other than global scope or declared static in global
6657 // scope.
6658 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6659 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006660
6661 CanQualType SizeTy =
6662 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6663
6664 // C++ [basic.stc.dynamic.allocation]p1:
6665 // The return type shall be void*. The first parameter shall have type
6666 // std::size_t.
6667 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6668 SizeTy,
6669 diag::err_operator_new_dependent_param_type,
6670 diag::err_operator_new_param_type))
6671 return true;
6672
6673 // C++ [basic.stc.dynamic.allocation]p1:
6674 // The first parameter shall not have an associated default argument.
6675 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00006676 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006677 diag::err_operator_new_default_arg)
6678 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6679
6680 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00006681}
6682
6683static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00006684CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6685 // C++ [basic.stc.dynamic.deallocation]p1:
6686 // A program is ill-formed if deallocation functions are declared in a
6687 // namespace scope other than global scope or declared static in global
6688 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006689 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6690 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006691
6692 // C++ [basic.stc.dynamic.deallocation]p2:
6693 // Each deallocation function shall return void and its first parameter
6694 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006695 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6696 SemaRef.Context.VoidPtrTy,
6697 diag::err_operator_delete_dependent_param_type,
6698 diag::err_operator_delete_param_type))
6699 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006700
Anders Carlsson12308f42009-12-11 23:23:22 +00006701 return false;
6702}
6703
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006704/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6705/// of this overloaded operator is well-formed. If so, returns false;
6706/// otherwise, emits appropriate diagnostics and returns true.
6707bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006708 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006709 "Expected an overloaded operator declaration");
6710
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006711 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6712
Mike Stump11289f42009-09-09 15:08:12 +00006713 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006714 // The allocation and deallocation functions, operator new,
6715 // operator new[], operator delete and operator delete[], are
6716 // described completely in 3.7.3. The attributes and restrictions
6717 // found in the rest of this subclause do not apply to them unless
6718 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006719 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006720 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006721
Anders Carlsson22f443f2009-12-12 00:26:23 +00006722 if (Op == OO_New || Op == OO_Array_New)
6723 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006724
6725 // C++ [over.oper]p6:
6726 // An operator function shall either be a non-static member
6727 // function or be a non-member function and have at least one
6728 // parameter whose type is a class, a reference to a class, an
6729 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006730 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6731 if (MethodDecl->isStatic())
6732 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006733 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006734 } else {
6735 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006736 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6737 ParamEnd = FnDecl->param_end();
6738 Param != ParamEnd; ++Param) {
6739 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006740 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6741 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006742 ClassOrEnumParam = true;
6743 break;
6744 }
6745 }
6746
Douglas Gregord69246b2008-11-17 16:14:12 +00006747 if (!ClassOrEnumParam)
6748 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006749 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006750 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006751 }
6752
6753 // C++ [over.oper]p8:
6754 // An operator function cannot have default arguments (8.3.6),
6755 // except where explicitly stated below.
6756 //
Mike Stump11289f42009-09-09 15:08:12 +00006757 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006758 // (C++ [over.call]p1).
6759 if (Op != OO_Call) {
6760 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6761 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006762 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006763 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006764 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006765 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006766 }
6767 }
6768
Douglas Gregor6cf08062008-11-10 13:38:07 +00006769 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6770 { false, false, false }
6771#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6772 , { Unary, Binary, MemberOnly }
6773#include "clang/Basic/OperatorKinds.def"
6774 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006775
Douglas Gregor6cf08062008-11-10 13:38:07 +00006776 bool CanBeUnaryOperator = OperatorUses[Op][0];
6777 bool CanBeBinaryOperator = OperatorUses[Op][1];
6778 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006779
6780 // C++ [over.oper]p8:
6781 // [...] Operator functions cannot have more or fewer parameters
6782 // than the number required for the corresponding operator, as
6783 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006784 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006785 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006786 if (Op != OO_Call &&
6787 ((NumParams == 1 && !CanBeUnaryOperator) ||
6788 (NumParams == 2 && !CanBeBinaryOperator) ||
6789 (NumParams < 1) || (NumParams > 2))) {
6790 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006791 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006792 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006793 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006794 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006795 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006796 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006797 assert(CanBeBinaryOperator &&
6798 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006799 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006800 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006801
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006802 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006803 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006804 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006805
Douglas Gregord69246b2008-11-17 16:14:12 +00006806 // Overloaded operators other than operator() cannot be variadic.
6807 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006808 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006809 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006810 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006811 }
6812
6813 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006814 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6815 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006816 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006817 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006818 }
6819
6820 // C++ [over.inc]p1:
6821 // The user-defined function called operator++ implements the
6822 // prefix and postfix ++ operator. If this function is a member
6823 // function with no parameters, or a non-member function with one
6824 // parameter of class or enumeration type, it defines the prefix
6825 // increment operator ++ for objects of that type. If the function
6826 // is a member function with one parameter (which shall be of type
6827 // int) or a non-member function with two parameters (the second
6828 // of which shall be of type int), it defines the postfix
6829 // increment operator ++ for objects of that type.
6830 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6831 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6832 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006833 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006834 ParamIsInt = BT->getKind() == BuiltinType::Int;
6835
Chris Lattner2b786902008-11-21 07:50:02 +00006836 if (!ParamIsInt)
6837 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006838 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006839 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006840 }
6841
Douglas Gregord69246b2008-11-17 16:14:12 +00006842 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006843}
Chris Lattner3b024a32008-12-17 07:09:26 +00006844
Alexis Huntc88db062010-01-13 09:01:02 +00006845/// CheckLiteralOperatorDeclaration - Check whether the declaration
6846/// of this literal operator function is well-formed. If so, returns
6847/// false; otherwise, emits appropriate diagnostics and returns true.
6848bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6849 DeclContext *DC = FnDecl->getDeclContext();
6850 Decl::Kind Kind = DC->getDeclKind();
6851 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6852 Kind != Decl::LinkageSpec) {
6853 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6854 << FnDecl->getDeclName();
6855 return true;
6856 }
6857
6858 bool Valid = false;
6859
Alexis Hunt7dd26172010-04-07 23:11:06 +00006860 // template <char...> type operator "" name() is the only valid template
6861 // signature, and the only valid signature with no parameters.
6862 if (FnDecl->param_size() == 0) {
6863 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6864 // Must have only one template parameter
6865 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6866 if (Params->size() == 1) {
6867 NonTypeTemplateParmDecl *PmDecl =
6868 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006869
Alexis Hunt7dd26172010-04-07 23:11:06 +00006870 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006871 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6872 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6873 Valid = true;
6874 }
6875 }
6876 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006877 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006878 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6879
Alexis Huntc88db062010-01-13 09:01:02 +00006880 QualType T = (*Param)->getType();
6881
Alexis Hunt079a6f72010-04-07 22:57:35 +00006882 // unsigned long long int, long double, and any character type are allowed
6883 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006884 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6885 Context.hasSameType(T, Context.LongDoubleTy) ||
6886 Context.hasSameType(T, Context.CharTy) ||
6887 Context.hasSameType(T, Context.WCharTy) ||
6888 Context.hasSameType(T, Context.Char16Ty) ||
6889 Context.hasSameType(T, Context.Char32Ty)) {
6890 if (++Param == FnDecl->param_end())
6891 Valid = true;
6892 goto FinishedParams;
6893 }
6894
Alexis Hunt079a6f72010-04-07 22:57:35 +00006895 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006896 const PointerType *PT = T->getAs<PointerType>();
6897 if (!PT)
6898 goto FinishedParams;
6899 T = PT->getPointeeType();
6900 if (!T.isConstQualified())
6901 goto FinishedParams;
6902 T = T.getUnqualifiedType();
6903
6904 // Move on to the second parameter;
6905 ++Param;
6906
6907 // If there is no second parameter, the first must be a const char *
6908 if (Param == FnDecl->param_end()) {
6909 if (Context.hasSameType(T, Context.CharTy))
6910 Valid = true;
6911 goto FinishedParams;
6912 }
6913
6914 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6915 // are allowed as the first parameter to a two-parameter function
6916 if (!(Context.hasSameType(T, Context.CharTy) ||
6917 Context.hasSameType(T, Context.WCharTy) ||
6918 Context.hasSameType(T, Context.Char16Ty) ||
6919 Context.hasSameType(T, Context.Char32Ty)))
6920 goto FinishedParams;
6921
6922 // The second and final parameter must be an std::size_t
6923 T = (*Param)->getType().getUnqualifiedType();
6924 if (Context.hasSameType(T, Context.getSizeType()) &&
6925 ++Param == FnDecl->param_end())
6926 Valid = true;
6927 }
6928
6929 // FIXME: This diagnostic is absolutely terrible.
6930FinishedParams:
6931 if (!Valid) {
6932 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6933 << FnDecl->getDeclName();
6934 return true;
6935 }
6936
6937 return false;
6938}
6939
Douglas Gregor07665a62009-01-05 19:45:36 +00006940/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6941/// linkage specification, including the language and (if present)
6942/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6943/// the location of the language string literal, which is provided
6944/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6945/// the '{' brace. Otherwise, this linkage specification does not
6946/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006947Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6948 SourceLocation LangLoc,
6949 llvm::StringRef Lang,
6950 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006951 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006952 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006953 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006954 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006955 Language = LinkageSpecDecl::lang_cxx;
6956 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006957 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006958 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006959 }
Mike Stump11289f42009-09-09 15:08:12 +00006960
Chris Lattner438e5012008-12-17 07:13:27 +00006961 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006962
Douglas Gregor07665a62009-01-05 19:45:36 +00006963 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00006964 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006965 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006966 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006967 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006968}
6969
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006970/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006971/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6972/// valid, it's the position of the closing '}' brace in a linkage
6973/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006974Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006975 Decl *LinkageSpec,
6976 SourceLocation RBraceLoc) {
6977 if (LinkageSpec) {
6978 if (RBraceLoc.isValid()) {
6979 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6980 LSDecl->setRBraceLoc(RBraceLoc);
6981 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006982 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006983 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006984 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006985}
6986
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006987/// \brief Perform semantic analysis for the variable declaration that
6988/// occurs within a C++ catch clause, returning the newly-created
6989/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00006990VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006991 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006992 SourceLocation StartLoc,
6993 SourceLocation Loc,
6994 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006995 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006996 QualType ExDeclType = TInfo->getType();
6997
Sebastian Redl54c04d42008-12-22 19:15:10 +00006998 // Arrays and functions decay.
6999 if (ExDeclType->isArrayType())
7000 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7001 else if (ExDeclType->isFunctionType())
7002 ExDeclType = Context.getPointerType(ExDeclType);
7003
7004 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7005 // The exception-declaration shall not denote a pointer or reference to an
7006 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00007007 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00007008 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007009 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00007010 Invalid = true;
7011 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007012
Douglas Gregor104ee002010-03-08 01:47:36 +00007013 // GCC allows catching pointers and references to incomplete types
7014 // as an extension; so do we, but we warn by default.
7015
Sebastian Redl54c04d42008-12-22 19:15:10 +00007016 QualType BaseType = ExDeclType;
7017 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00007018 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00007019 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007020 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007021 BaseType = Ptr->getPointeeType();
7022 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00007023 DK = diag::ext_catch_incomplete_ptr;
7024 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00007025 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00007026 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00007027 BaseType = Ref->getPointeeType();
7028 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00007029 DK = diag::ext_catch_incomplete_ref;
7030 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007031 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00007032 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00007033 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
7034 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00007035 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007036
Mike Stump11289f42009-09-09 15:08:12 +00007037 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007038 RequireNonAbstractType(Loc, ExDeclType,
7039 diag::err_abstract_type_in_decl,
7040 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00007041 Invalid = true;
7042
John McCall2ca705e2010-07-24 00:37:23 +00007043 // Only the non-fragile NeXT runtime currently supports C++ catches
7044 // of ObjC types, and no runtime supports catching ObjC types by value.
7045 if (!Invalid && getLangOptions().ObjC1) {
7046 QualType T = ExDeclType;
7047 if (const ReferenceType *RT = T->getAs<ReferenceType>())
7048 T = RT->getPointeeType();
7049
7050 if (T->isObjCObjectType()) {
7051 Diag(Loc, diag::err_objc_object_catch);
7052 Invalid = true;
7053 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00007054 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00007055 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
7056 Invalid = true;
7057 }
7058 }
7059 }
7060
Abramo Bagnaradff19302011-03-08 08:55:46 +00007061 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
7062 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00007063 ExDecl->setExceptionVariable(true);
7064
Douglas Gregor6de584c2010-03-05 23:38:39 +00007065 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00007066 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00007067 // C++ [except.handle]p16:
7068 // The object declared in an exception-declaration or, if the
7069 // exception-declaration does not specify a name, a temporary (12.2) is
7070 // copy-initialized (8.5) from the exception object. [...]
7071 // The object is destroyed when the handler exits, after the destruction
7072 // of any automatic objects initialized within the handler.
7073 //
7074 // We just pretend to initialize the object with itself, then make sure
7075 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00007076 QualType initType = ExDeclType;
7077
7078 InitializedEntity entity =
7079 InitializedEntity::InitializeVariable(ExDecl);
7080 InitializationKind initKind =
7081 InitializationKind::CreateCopy(Loc, SourceLocation());
7082
7083 Expr *opaqueValue =
7084 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
7085 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
7086 ExprResult result = sequence.Perform(*this, entity, initKind,
7087 MultiExprArg(&opaqueValue, 1));
7088 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00007089 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00007090 else {
7091 // If the constructor used was non-trivial, set this as the
7092 // "initializer".
7093 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
7094 if (!construct->getConstructor()->isTrivial()) {
7095 Expr *init = MaybeCreateExprWithCleanups(construct);
7096 ExDecl->setInit(init);
7097 }
7098
7099 // And make sure it's destructable.
7100 FinalizeVarWithDestructor(ExDecl, recordType);
7101 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00007102 }
7103 }
7104
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007105 if (Invalid)
7106 ExDecl->setInvalidDecl();
7107
7108 return ExDecl;
7109}
7110
7111/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
7112/// handler.
John McCall48871652010-08-21 09:40:31 +00007113Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00007114 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00007115 bool Invalid = D.isInvalidType();
7116
7117 // Check for unexpanded parameter packs.
7118 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7119 UPPC_ExceptionType)) {
7120 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7121 D.getIdentifierLoc());
7122 Invalid = true;
7123 }
7124
Sebastian Redl54c04d42008-12-22 19:15:10 +00007125 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00007126 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00007127 LookupOrdinaryName,
7128 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007129 // The scope should be freshly made just for us. There is just no way
7130 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00007131 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00007132 if (PrevDecl->isTemplateParameter()) {
7133 // Maybe we will complain about the shadowed template parameter.
7134 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00007135 }
7136 }
7137
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007138 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00007139 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
7140 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007141 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007142 }
7143
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007144 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007145 D.getSourceRange().getBegin(),
7146 D.getIdentifierLoc(),
7147 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007148 if (Invalid)
7149 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00007150
Sebastian Redl54c04d42008-12-22 19:15:10 +00007151 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00007152 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007153 PushOnScopeChains(ExDecl, S);
7154 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007155 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00007156
Douglas Gregor758a8692009-06-17 21:51:59 +00007157 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00007158 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00007159}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007160
Abramo Bagnaraea947882011-03-08 16:41:52 +00007161Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00007162 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007163 Expr *AssertMessageExpr_,
7164 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00007165 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007166
Anders Carlsson54b26982009-03-14 00:33:21 +00007167 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7168 llvm::APSInt Value(32);
7169 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00007170 Diag(StaticAssertLoc,
7171 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00007172 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007173 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00007174 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007175
Anders Carlsson54b26982009-03-14 00:33:21 +00007176 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00007177 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00007178 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00007179 }
7180 }
Mike Stump11289f42009-09-09 15:08:12 +00007181
Douglas Gregoref68fee2010-12-15 23:55:21 +00007182 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7183 return 0;
7184
Abramo Bagnaraea947882011-03-08 16:41:52 +00007185 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7186 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00007187
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007188 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00007189 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007190}
Sebastian Redlf769df52009-03-24 22:27:57 +00007191
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007192/// \brief Perform semantic analysis of the given friend type declaration.
7193///
7194/// \returns A friend declaration that.
7195FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7196 TypeSourceInfo *TSInfo) {
7197 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7198
7199 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007200 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007201
Douglas Gregor3b4abb62010-04-07 17:57:12 +00007202 if (!getLangOptions().CPlusPlus0x) {
7203 // C++03 [class.friend]p2:
7204 // An elaborated-type-specifier shall be used in a friend declaration
7205 // for a class.*
7206 //
7207 // * The class-key of the elaborated-type-specifier is required.
7208 if (!ActiveTemplateInstantiations.empty()) {
7209 // Do not complain about the form of friend template types during
7210 // template instantiation; we will already have complained when the
7211 // template was declared.
7212 } else if (!T->isElaboratedTypeSpecifier()) {
7213 // If we evaluated the type to a record type, suggest putting
7214 // a tag in front.
7215 if (const RecordType *RT = T->getAs<RecordType>()) {
7216 RecordDecl *RD = RT->getDecl();
7217
7218 std::string InsertionText = std::string(" ") + RD->getKindName();
7219
7220 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7221 << (unsigned) RD->getTagKind()
7222 << T
7223 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7224 InsertionText);
7225 } else {
7226 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7227 << T
7228 << SourceRange(FriendLoc, TypeRange.getEnd());
7229 }
7230 } else if (T->getAs<EnumType>()) {
7231 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007232 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007233 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007234 }
7235 }
7236
Douglas Gregor3b4abb62010-04-07 17:57:12 +00007237 // C++0x [class.friend]p3:
7238 // If the type specifier in a friend declaration designates a (possibly
7239 // cv-qualified) class type, that class is declared as a friend; otherwise,
7240 // the friend declaration is ignored.
7241
7242 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7243 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007244
7245 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7246}
7247
John McCallace48cd2010-10-19 01:40:49 +00007248/// Handle a friend tag declaration where the scope specifier was
7249/// templated.
7250Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7251 unsigned TagSpec, SourceLocation TagLoc,
7252 CXXScopeSpec &SS,
7253 IdentifierInfo *Name, SourceLocation NameLoc,
7254 AttributeList *Attr,
7255 MultiTemplateParamsArg TempParamLists) {
7256 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7257
7258 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00007259 bool Invalid = false;
7260
7261 if (TemplateParameterList *TemplateParams
7262 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7263 TempParamLists.get(),
7264 TempParamLists.size(),
7265 /*friend*/ true,
7266 isExplicitSpecialization,
7267 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00007268 if (TemplateParams->size() > 0) {
7269 // This is a declaration of a class template.
7270 if (Invalid)
7271 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007272
John McCallace48cd2010-10-19 01:40:49 +00007273 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7274 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007275 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007276 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007277 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00007278 } else {
7279 // The "template<>" header is extraneous.
7280 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7281 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7282 isExplicitSpecialization = true;
7283 }
7284 }
7285
7286 if (Invalid) return 0;
7287
7288 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7289
7290 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007291 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00007292 if (TempParamLists.get()[I]->size()) {
7293 isAllExplicitSpecializations = false;
7294 break;
7295 }
7296 }
7297
7298 // FIXME: don't ignore attributes.
7299
7300 // If it's explicit specializations all the way down, just forget
7301 // about the template header and build an appropriate non-templated
7302 // friend. TODO: for source fidelity, remember the headers.
7303 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007304 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00007305 ElaboratedTypeKeyword Keyword
7306 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007307 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007308 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00007309 if (T.isNull())
7310 return 0;
7311
7312 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7313 if (isa<DependentNameType>(T)) {
7314 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7315 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007316 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007317 TL.setNameLoc(NameLoc);
7318 } else {
7319 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7320 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007321 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007322 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7323 }
7324
7325 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7326 TSI, FriendLoc);
7327 Friend->setAccess(AS_public);
7328 CurContext->addDecl(Friend);
7329 return Friend;
7330 }
7331
7332 // Handle the case of a templated-scope friend class. e.g.
7333 // template <class T> class A<T>::B;
7334 // FIXME: we don't support these right now.
7335 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7336 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7337 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7338 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7339 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007340 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00007341 TL.setNameLoc(NameLoc);
7342
7343 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7344 TSI, FriendLoc);
7345 Friend->setAccess(AS_public);
7346 Friend->setUnsupportedFriend(true);
7347 CurContext->addDecl(Friend);
7348 return Friend;
7349}
7350
7351
John McCall11083da2009-09-16 22:47:08 +00007352/// Handle a friend type declaration. This works in tandem with
7353/// ActOnTag.
7354///
7355/// Notes on friend class templates:
7356///
7357/// We generally treat friend class declarations as if they were
7358/// declaring a class. So, for example, the elaborated type specifier
7359/// in a friend declaration is required to obey the restrictions of a
7360/// class-head (i.e. no typedefs in the scope chain), template
7361/// parameters are required to match up with simple template-ids, &c.
7362/// However, unlike when declaring a template specialization, it's
7363/// okay to refer to a template specialization without an empty
7364/// template parameter declaration, e.g.
7365/// friend class A<T>::B<unsigned>;
7366/// We permit this as a special case; if there are any template
7367/// parameters present at all, require proper matching, i.e.
7368/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00007369Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00007370 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007371 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00007372
7373 assert(DS.isFriendSpecified());
7374 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7375
John McCall11083da2009-09-16 22:47:08 +00007376 // Try to convert the decl specifier to a type. This works for
7377 // friend templates because ActOnTag never produces a ClassTemplateDecl
7378 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00007379 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00007380 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7381 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00007382 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00007383 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007384
Douglas Gregor6c110f32010-12-16 01:14:37 +00007385 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7386 return 0;
7387
John McCall11083da2009-09-16 22:47:08 +00007388 // This is definitely an error in C++98. It's probably meant to
7389 // be forbidden in C++0x, too, but the specification is just
7390 // poorly written.
7391 //
7392 // The problem is with declarations like the following:
7393 // template <T> friend A<T>::foo;
7394 // where deciding whether a class C is a friend or not now hinges
7395 // on whether there exists an instantiation of A that causes
7396 // 'foo' to equal C. There are restrictions on class-heads
7397 // (which we declare (by fiat) elaborated friend declarations to
7398 // be) that makes this tractable.
7399 //
7400 // FIXME: handle "template <> friend class A<T>;", which
7401 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00007402 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00007403 Diag(Loc, diag::err_tagless_friend_type_template)
7404 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007405 return 0;
John McCall11083da2009-09-16 22:47:08 +00007406 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007407
John McCallaa74a0c2009-08-28 07:59:38 +00007408 // C++98 [class.friend]p1: A friend of a class is a function
7409 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00007410 // This is fixed in DR77, which just barely didn't make the C++03
7411 // deadline. It's also a very silly restriction that seriously
7412 // affects inner classes and which nobody else seems to implement;
7413 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00007414 //
7415 // But note that we could warn about it: it's always useless to
7416 // friend one of your own members (it's not, however, worthless to
7417 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00007418
John McCall11083da2009-09-16 22:47:08 +00007419 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007420 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00007421 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007422 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00007423 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00007424 TSI,
John McCall11083da2009-09-16 22:47:08 +00007425 DS.getFriendSpecLoc());
7426 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007427 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7428
7429 if (!D)
John McCall48871652010-08-21 09:40:31 +00007430 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007431
John McCall11083da2009-09-16 22:47:08 +00007432 D->setAccess(AS_public);
7433 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00007434
John McCall48871652010-08-21 09:40:31 +00007435 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00007436}
7437
John McCallde3fd222010-10-12 23:13:28 +00007438Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7439 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007440 const DeclSpec &DS = D.getDeclSpec();
7441
7442 assert(DS.isFriendSpecified());
7443 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7444
7445 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00007446 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7447 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00007448
7449 // C++ [class.friend]p1
7450 // A friend of a class is a function or class....
7451 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00007452 // It *doesn't* see through dependent types, which is correct
7453 // according to [temp.arg.type]p3:
7454 // If a declaration acquires a function type through a
7455 // type dependent on a template-parameter and this causes
7456 // a declaration that does not use the syntactic form of a
7457 // function declarator to have a function type, the program
7458 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00007459 if (!T->isFunctionType()) {
7460 Diag(Loc, diag::err_unexpected_friend);
7461
7462 // It might be worthwhile to try to recover by creating an
7463 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00007464 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007465 }
7466
7467 // C++ [namespace.memdef]p3
7468 // - If a friend declaration in a non-local class first declares a
7469 // class or function, the friend class or function is a member
7470 // of the innermost enclosing namespace.
7471 // - The name of the friend is not found by simple name lookup
7472 // until a matching declaration is provided in that namespace
7473 // scope (either before or after the class declaration granting
7474 // friendship).
7475 // - If a friend function is called, its name may be found by the
7476 // name lookup that considers functions from namespaces and
7477 // classes associated with the types of the function arguments.
7478 // - When looking for a prior declaration of a class or a function
7479 // declared as a friend, scopes outside the innermost enclosing
7480 // namespace scope are not considered.
7481
John McCallde3fd222010-10-12 23:13:28 +00007482 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007483 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7484 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00007485 assert(Name);
7486
Douglas Gregor6c110f32010-12-16 01:14:37 +00007487 // Check for unexpanded parameter packs.
7488 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7489 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7490 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7491 return 0;
7492
John McCall07e91c02009-08-06 02:15:43 +00007493 // The context we found the declaration in, or in which we should
7494 // create the declaration.
7495 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00007496 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007497 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00007498 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00007499
John McCallde3fd222010-10-12 23:13:28 +00007500 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00007501
John McCallde3fd222010-10-12 23:13:28 +00007502 // There are four cases here.
7503 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00007504 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00007505 // there as appropriate.
7506 // Recover from invalid scope qualifiers as if they just weren't there.
7507 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00007508 // C++0x [namespace.memdef]p3:
7509 // If the name in a friend declaration is neither qualified nor
7510 // a template-id and the declaration is a function or an
7511 // elaborated-type-specifier, the lookup to determine whether
7512 // the entity has been previously declared shall not consider
7513 // any scopes outside the innermost enclosing namespace.
7514 // C++0x [class.friend]p11:
7515 // If a friend declaration appears in a local class and the name
7516 // specified is an unqualified name, a prior declaration is
7517 // looked up without considering scopes that are outside the
7518 // innermost enclosing non-class scope. For a friend function
7519 // declaration, if there is no prior declaration, the program is
7520 // ill-formed.
7521 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00007522 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00007523
John McCallf7cfb222010-10-13 05:45:15 +00007524 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00007525 DC = CurContext;
7526 while (true) {
7527 // Skip class contexts. If someone can cite chapter and verse
7528 // for this behavior, that would be nice --- it's what GCC and
7529 // EDG do, and it seems like a reasonable intent, but the spec
7530 // really only says that checks for unqualified existing
7531 // declarations should stop at the nearest enclosing namespace,
7532 // not that they should only consider the nearest enclosing
7533 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007534 while (DC->isRecord())
7535 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00007536
John McCall1f82f242009-11-18 22:49:29 +00007537 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00007538
7539 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00007540 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00007541 break;
John McCallf7cfb222010-10-13 05:45:15 +00007542
John McCallf4776592010-10-14 22:22:28 +00007543 if (isTemplateId) {
7544 if (isa<TranslationUnitDecl>(DC)) break;
7545 } else {
7546 if (DC->isFileContext()) break;
7547 }
John McCall07e91c02009-08-06 02:15:43 +00007548 DC = DC->getParent();
7549 }
7550
7551 // C++ [class.friend]p1: A friend of a class is a function or
7552 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00007553 // C++0x changes this for both friend types and functions.
7554 // Most C++ 98 compilers do seem to give an error here, so
7555 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00007556 if (!Previous.empty() && DC->Equals(CurContext)
7557 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00007558 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00007559
John McCallccbc0322010-10-13 06:22:15 +00007560 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00007561
John McCallde3fd222010-10-12 23:13:28 +00007562 // - There's a non-dependent scope specifier, in which case we
7563 // compute it and do a previous lookup there for a function
7564 // or function template.
7565 } else if (!SS.getScopeRep()->isDependent()) {
7566 DC = computeDeclContext(SS);
7567 if (!DC) return 0;
7568
7569 if (RequireCompleteDeclContext(SS, DC)) return 0;
7570
7571 LookupQualifiedName(Previous, DC);
7572
7573 // Ignore things found implicitly in the wrong scope.
7574 // TODO: better diagnostics for this case. Suggesting the right
7575 // qualified scope would be nice...
7576 LookupResult::Filter F = Previous.makeFilter();
7577 while (F.hasNext()) {
7578 NamedDecl *D = F.next();
7579 if (!DC->InEnclosingNamespaceSetOf(
7580 D->getDeclContext()->getRedeclContext()))
7581 F.erase();
7582 }
7583 F.done();
7584
7585 if (Previous.empty()) {
7586 D.setInvalidType();
7587 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7588 return 0;
7589 }
7590
7591 // C++ [class.friend]p1: A friend of a class is a function or
7592 // class that is not a member of the class . . .
7593 if (DC->Equals(CurContext))
7594 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7595
7596 // - There's a scope specifier that does not match any template
7597 // parameter lists, in which case we use some arbitrary context,
7598 // create a method or method template, and wait for instantiation.
7599 // - There's a scope specifier that does match some template
7600 // parameter lists, which we don't handle right now.
7601 } else {
7602 DC = CurContext;
7603 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00007604 }
7605
John McCallf7cfb222010-10-13 05:45:15 +00007606 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00007607 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00007608 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7609 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7610 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00007611 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00007612 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7613 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00007614 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007615 }
John McCall07e91c02009-08-06 02:15:43 +00007616 }
7617
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007618 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00007619 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007620 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00007621 IsDefinition,
7622 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00007623 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00007624
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007625 assert(ND->getDeclContext() == DC);
7626 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00007627
John McCall759e32b2009-08-31 22:39:49 +00007628 // Add the function declaration to the appropriate lookup tables,
7629 // adjusting the redeclarations list as necessary. We don't
7630 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00007631 //
John McCall759e32b2009-08-31 22:39:49 +00007632 // Also update the scope-based lookup if the target context's
7633 // lookup context is in lexical scope.
7634 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007635 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007636 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007637 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007638 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007639 }
John McCallaa74a0c2009-08-28 07:59:38 +00007640
7641 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007642 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00007643 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00007644 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00007645 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00007646
John McCallde3fd222010-10-12 23:13:28 +00007647 if (ND->isInvalidDecl())
7648 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00007649 else {
7650 FunctionDecl *FD;
7651 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7652 FD = FTD->getTemplatedDecl();
7653 else
7654 FD = cast<FunctionDecl>(ND);
7655
7656 // Mark templated-scope function declarations as unsupported.
7657 if (FD->getNumTemplateParameterLists())
7658 FrD->setUnsupportedFriend(true);
7659 }
John McCallde3fd222010-10-12 23:13:28 +00007660
John McCall48871652010-08-21 09:40:31 +00007661 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00007662}
7663
John McCall48871652010-08-21 09:40:31 +00007664void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7665 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00007666
Sebastian Redlf769df52009-03-24 22:27:57 +00007667 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7668 if (!Fn) {
7669 Diag(DelLoc, diag::err_deleted_non_function);
7670 return;
7671 }
7672 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7673 Diag(DelLoc, diag::err_deleted_decl_not_first);
7674 Diag(Prev->getLocation(), diag::note_previous_declaration);
7675 // If the declaration wasn't the first, we delete the function anyway for
7676 // recovery.
7677 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007678 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00007679}
Sebastian Redl4c018662009-04-27 21:33:24 +00007680
7681static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00007682 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00007683 Stmt *SubStmt = *CI;
7684 if (!SubStmt)
7685 continue;
7686 if (isa<ReturnStmt>(SubStmt))
7687 Self.Diag(SubStmt->getSourceRange().getBegin(),
7688 diag::err_return_in_constructor_handler);
7689 if (!isa<Expr>(SubStmt))
7690 SearchForReturnInStmt(Self, SubStmt);
7691 }
7692}
7693
7694void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7695 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7696 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7697 SearchForReturnInStmt(*this, Handler);
7698 }
7699}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007700
Mike Stump11289f42009-09-09 15:08:12 +00007701bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007702 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00007703 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7704 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007705
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007706 if (Context.hasSameType(NewTy, OldTy) ||
7707 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007708 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007709
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007710 // Check if the return types are covariant
7711 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007712
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007713 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007714 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7715 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007716 NewClassTy = NewPT->getPointeeType();
7717 OldClassTy = OldPT->getPointeeType();
7718 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007719 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7720 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7721 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7722 NewClassTy = NewRT->getPointeeType();
7723 OldClassTy = OldRT->getPointeeType();
7724 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007725 }
7726 }
Mike Stump11289f42009-09-09 15:08:12 +00007727
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007728 // The return types aren't either both pointers or references to a class type.
7729 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007730 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007731 diag::err_different_return_type_for_overriding_virtual_function)
7732 << New->getDeclName() << NewTy << OldTy;
7733 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007734
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007735 return true;
7736 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007737
Anders Carlssone60365b2009-12-31 18:34:24 +00007738 // C++ [class.virtual]p6:
7739 // If the return type of D::f differs from the return type of B::f, the
7740 // class type in the return type of D::f shall be complete at the point of
7741 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007742 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7743 if (!RT->isBeingDefined() &&
7744 RequireCompleteType(New->getLocation(), NewClassTy,
7745 PDiag(diag::err_covariant_return_incomplete)
7746 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007747 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007748 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007749
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007750 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007751 // Check if the new class derives from the old class.
7752 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7753 Diag(New->getLocation(),
7754 diag::err_covariant_return_not_derived)
7755 << New->getDeclName() << NewTy << OldTy;
7756 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7757 return true;
7758 }
Mike Stump11289f42009-09-09 15:08:12 +00007759
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007760 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007761 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007762 diag::err_covariant_return_inaccessible_base,
7763 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7764 // FIXME: Should this point to the return type?
7765 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00007766 // FIXME: this note won't trigger for delayed access control
7767 // diagnostics, and it's impossible to get an undelayed error
7768 // here from access control during the original parse because
7769 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007770 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7771 return true;
7772 }
7773 }
Mike Stump11289f42009-09-09 15:08:12 +00007774
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007775 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007776 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007777 Diag(New->getLocation(),
7778 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007779 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007780 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7781 return true;
7782 };
Mike Stump11289f42009-09-09 15:08:12 +00007783
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007784
7785 // The new class type must have the same or less qualifiers as the old type.
7786 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7787 Diag(New->getLocation(),
7788 diag::err_covariant_return_type_class_type_more_qualified)
7789 << New->getDeclName() << NewTy << OldTy;
7790 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7791 return true;
7792 };
Mike Stump11289f42009-09-09 15:08:12 +00007793
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007794 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007795}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007796
Douglas Gregor21920e372009-12-01 17:24:26 +00007797/// \brief Mark the given method pure.
7798///
7799/// \param Method the method to be marked pure.
7800///
7801/// \param InitRange the source range that covers the "0" initializer.
7802bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00007803 SourceLocation EndLoc = InitRange.getEnd();
7804 if (EndLoc.isValid())
7805 Method->setRangeEnd(EndLoc);
7806
Douglas Gregor21920e372009-12-01 17:24:26 +00007807 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7808 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00007809 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00007810 }
Douglas Gregor21920e372009-12-01 17:24:26 +00007811
7812 if (!Method->isInvalidDecl())
7813 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7814 << Method->getDeclName() << InitRange;
7815 return true;
7816}
7817
John McCall1f4ee7b2009-12-19 09:28:58 +00007818/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7819/// an initializer for the out-of-line declaration 'Dcl'. The scope
7820/// is a fresh scope pushed for just this purpose.
7821///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007822/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7823/// static data member of class X, names should be looked up in the scope of
7824/// class X.
John McCall48871652010-08-21 09:40:31 +00007825void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007826 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00007827 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007828
John McCall1f4ee7b2009-12-19 09:28:58 +00007829 // We should only get called for declarations with scope specifiers, like:
7830 // int foo::bar;
7831 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007832 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007833}
7834
7835/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007836/// initializer for the out-of-line declaration 'D'.
7837void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007838 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00007839 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007840
John McCall1f4ee7b2009-12-19 09:28:58 +00007841 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007842 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007843}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007844
7845/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7846/// C++ if/switch/while/for statement.
7847/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007848DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007849 // C++ 6.4p2:
7850 // The declarator shall not specify a function or an array.
7851 // The type-specifier-seq shall not contain typedef and shall not declare a
7852 // new class or enumeration.
7853 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7854 "Parser allowed 'typedef' as storage class of condition decl.");
7855
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007856 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007857 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7858 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007859
7860 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7861 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7862 // would be created and CXXConditionDeclExpr wants a VarDecl.
7863 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7864 << D.getSourceRange();
7865 return DeclResult();
7866 } else if (OwnedTag && OwnedTag->isDefinition()) {
7867 // The type-specifier-seq shall not declare a new class or enumeration.
7868 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7869 }
7870
John McCall48871652010-08-21 09:40:31 +00007871 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007872 if (!Dcl)
7873 return DeclResult();
7874
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007875 return Dcl;
7876}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007877
Douglas Gregor88d292c2010-05-13 16:44:06 +00007878void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7879 bool DefinitionRequired) {
7880 // Ignore any vtable uses in unevaluated operands or for classes that do
7881 // not have a vtable.
7882 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7883 CurContext->isDependentContext() ||
7884 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007885 return;
7886
Douglas Gregor88d292c2010-05-13 16:44:06 +00007887 // Try to insert this class into the map.
7888 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7889 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7890 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7891 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007892 // If we already had an entry, check to see if we are promoting this vtable
7893 // to required a definition. If so, we need to reappend to the VTableUses
7894 // list, since we may have already processed the first entry.
7895 if (DefinitionRequired && !Pos.first->second) {
7896 Pos.first->second = true;
7897 } else {
7898 // Otherwise, we can early exit.
7899 return;
7900 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007901 }
7902
7903 // Local classes need to have their virtual members marked
7904 // immediately. For all other classes, we mark their virtual members
7905 // at the end of the translation unit.
7906 if (Class->isLocalClass())
7907 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007908 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007909 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007910}
7911
Douglas Gregor88d292c2010-05-13 16:44:06 +00007912bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007913 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007914 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007915
Douglas Gregor88d292c2010-05-13 16:44:06 +00007916 // Note: The VTableUses vector could grow as a result of marking
7917 // the members of a class as "used", so we check the size each
7918 // time through the loop and prefer indices (with are stable) to
7919 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00007920 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00007921 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007922 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007923 if (!Class)
7924 continue;
7925
7926 SourceLocation Loc = VTableUses[I].second;
7927
7928 // If this class has a key function, but that key function is
7929 // defined in another translation unit, we don't need to emit the
7930 // vtable even though we're using it.
7931 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007932 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007933 switch (KeyFunction->getTemplateSpecializationKind()) {
7934 case TSK_Undeclared:
7935 case TSK_ExplicitSpecialization:
7936 case TSK_ExplicitInstantiationDeclaration:
7937 // The key function is in another translation unit.
7938 continue;
7939
7940 case TSK_ExplicitInstantiationDefinition:
7941 case TSK_ImplicitInstantiation:
7942 // We will be instantiating the key function.
7943 break;
7944 }
7945 } else if (!KeyFunction) {
7946 // If we have a class with no key function that is the subject
7947 // of an explicit instantiation declaration, suppress the
7948 // vtable; it will live with the explicit instantiation
7949 // definition.
7950 bool IsExplicitInstantiationDeclaration
7951 = Class->getTemplateSpecializationKind()
7952 == TSK_ExplicitInstantiationDeclaration;
7953 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7954 REnd = Class->redecls_end();
7955 R != REnd; ++R) {
7956 TemplateSpecializationKind TSK
7957 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7958 if (TSK == TSK_ExplicitInstantiationDeclaration)
7959 IsExplicitInstantiationDeclaration = true;
7960 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7961 IsExplicitInstantiationDeclaration = false;
7962 break;
7963 }
7964 }
7965
7966 if (IsExplicitInstantiationDeclaration)
7967 continue;
7968 }
7969
7970 // Mark all of the virtual members of this class as referenced, so
7971 // that we can build a vtable. Then, tell the AST consumer that a
7972 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00007973 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00007974 MarkVirtualMembersReferenced(Loc, Class);
7975 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7976 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7977
7978 // Optionally warn if we're emitting a weak vtable.
7979 if (Class->getLinkage() == ExternalLinkage &&
7980 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007981 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007982 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7983 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007984 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007985 VTableUses.clear();
7986
Douglas Gregor97509692011-04-22 22:25:37 +00007987 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007988}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007989
Rafael Espindola5b334082010-03-26 00:36:59 +00007990void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7991 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007992 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7993 e = RD->method_end(); i != e; ++i) {
7994 CXXMethodDecl *MD = *i;
7995
7996 // C++ [basic.def.odr]p2:
7997 // [...] A virtual member function is used if it is not pure. [...]
7998 if (MD->isVirtual() && !MD->isPure())
7999 MarkDeclarationReferenced(Loc, MD);
8000 }
Rafael Espindola5b334082010-03-26 00:36:59 +00008001
8002 // Only classes that have virtual bases need a VTT.
8003 if (RD->getNumVBases() == 0)
8004 return;
8005
8006 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
8007 e = RD->bases_end(); i != e; ++i) {
8008 const CXXRecordDecl *Base =
8009 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00008010 if (Base->getNumVBases() == 0)
8011 continue;
8012 MarkVirtualMembersReferenced(Loc, Base);
8013 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00008014}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008015
8016/// SetIvarInitializers - This routine builds initialization ASTs for the
8017/// Objective-C implementation whose ivars need be initialized.
8018void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
8019 if (!getLangOptions().CPlusPlus)
8020 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00008021 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008022 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
8023 CollectIvarsToConstructOrDestruct(OID, ivars);
8024 if (ivars.empty())
8025 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00008026 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008027 for (unsigned i = 0; i < ivars.size(); i++) {
8028 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00008029 if (Field->isInvalidDecl())
8030 continue;
8031
Alexis Hunt1d792652011-01-08 20:30:50 +00008032 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008033 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
8034 InitializationKind InitKind =
8035 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
8036
8037 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00008038 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00008039 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00008040 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008041 // Note, MemberInit could actually come back empty if no initialization
8042 // is required (e.g., because it would call a trivial default constructor)
8043 if (!MemberInit.get() || MemberInit.isInvalid())
8044 continue;
John McCallacf0ee52010-10-08 02:01:28 +00008045
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008046 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00008047 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
8048 SourceLocation(),
8049 MemberInit.takeAs<Expr>(),
8050 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008051 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00008052
8053 // Be sure that the destructor is accessible and is marked as referenced.
8054 if (const RecordType *RecordTy
8055 = Context.getBaseElementType(Field->getType())
8056 ->getAs<RecordType>()) {
8057 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00008058 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00008059 MarkDeclarationReferenced(Field->getLocation(), Destructor);
8060 CheckDestructorAccess(Field->getLocation(), Destructor,
8061 PDiag(diag::err_access_dtor_ivar)
8062 << Context.getBaseElementType(Field->getType()));
8063 }
8064 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00008065 }
8066 ObjCImplementation->setIvarInitializers(Context,
8067 AllToInit.data(), AllToInit.size());
8068 }
8069}
Alexis Hunt6118d662011-05-04 05:57:24 +00008070
Alexis Hunt27a761d2011-05-04 23:29:54 +00008071static
8072void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
8073 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
8074 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
8075 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
8076 Sema &S) {
8077 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8078 CE = Current.end();
8079 if (Ctor->isInvalidDecl())
8080 return;
8081
8082 const FunctionDecl *FNTarget = 0;
8083 CXXConstructorDecl *Target;
8084
8085 // We ignore the result here since if we don't have a body, Target will be
8086 // null below.
8087 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
8088 Target
8089= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
8090
8091 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
8092 // Avoid dereferencing a null pointer here.
8093 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
8094
8095 if (!Current.insert(Canonical))
8096 return;
8097
8098 // We know that beyond here, we aren't chaining into a cycle.
8099 if (!Target || !Target->isDelegatingConstructor() ||
8100 Target->isInvalidDecl() || Valid.count(TCanonical)) {
8101 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8102 Valid.insert(*CI);
8103 Current.clear();
8104 // We've hit a cycle.
8105 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
8106 Current.count(TCanonical)) {
8107 // If we haven't diagnosed this cycle yet, do so now.
8108 if (!Invalid.count(TCanonical)) {
8109 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00008110 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00008111 << Ctor;
8112
8113 // Don't add a note for a function delegating directo to itself.
8114 if (TCanonical != Canonical)
8115 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
8116
8117 CXXConstructorDecl *C = Target;
8118 while (C->getCanonicalDecl() != Canonical) {
8119 (void)C->getTargetConstructor()->hasBody(FNTarget);
8120 assert(FNTarget && "Ctor cycle through bodiless function");
8121
8122 C
8123 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
8124 S.Diag(C->getLocation(), diag::note_which_delegates_to);
8125 }
8126 }
8127
8128 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8129 Invalid.insert(*CI);
8130 Current.clear();
8131 } else {
8132 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
8133 }
8134}
8135
8136
Alexis Hunt6118d662011-05-04 05:57:24 +00008137void Sema::CheckDelegatingCtorCycles() {
8138 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
8139
Alexis Hunt27a761d2011-05-04 23:29:54 +00008140 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8141 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00008142
8143 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00008144 I = DelegatingCtorDecls.begin(),
8145 E = DelegatingCtorDecls.end();
8146 I != E; ++I) {
8147 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00008148 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00008149
8150 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
8151 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00008152}