blob: bd4aac8985c6ba79a12fd1eb6cf749fef34f471a [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Anders Carlssoned961f92009-08-25 02:29:20 +0000114bool
John McCall9ae2f072010-08-23 23:25:46 +0000115Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000116 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000117 if (RequireCompleteType(Param->getLocation(), Param->getType(),
118 diag::err_typecheck_decl_incomplete_type)) {
119 Param->setInvalidDecl();
120 return true;
121 }
122
Anders Carlssoned961f92009-08-25 02:29:20 +0000123 // C++ [dcl.fct.default]p5
124 // A default argument expression is implicitly converted (clause
125 // 4) to the parameter type. The default argument expression has
126 // the same semantic constraints as the initializer expression in
127 // a declaration of a variable of the parameter type, using the
128 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000129 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
130 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000131 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
132 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000133 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000134 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000135 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000136 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000137 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000138 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000139
John McCallb4eb64d2010-10-08 02:01:28 +0000140 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000141 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlssoned961f92009-08-25 02:29:20 +0000143 // Okay: add the default argument to the parameter
144 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000146 // We have already instantiated this parameter; provide each of the
147 // instantiations with the uninstantiated default argument.
148 UnparsedDefaultArgInstantiationsMap::iterator InstPos
149 = UnparsedDefaultArgInstantiations.find(Param);
150 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
151 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
152 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
153
154 // We're done tracking this parameter's instantiations.
155 UnparsedDefaultArgInstantiations.erase(InstPos);
156 }
157
Anders Carlsson9351c172009-08-25 03:18:48 +0000158 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000159}
160
Chris Lattner8123a952008-04-10 02:22:51 +0000161/// ActOnParamDefaultArgument - Check whether the default argument
162/// provided for a function parameter is well-formed. If so, attach it
163/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000164void
John McCalld226f652010-08-21 09:40:31 +0000165Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000166 Expr *DefaultArg) {
167 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000168 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000169
John McCalld226f652010-08-21 09:40:31 +0000170 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000171 UnparsedDefaultArgLocs.erase(Param);
172
Chris Lattner3d1cee32008-04-08 05:04:30 +0000173 // Default arguments are only permitted in C++
174 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000175 Diag(EqualLoc, diag::err_param_default_argument)
176 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000177 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000178 return;
179 }
180
Douglas Gregor6f526752010-12-16 08:48:57 +0000181 // Check for unexpanded parameter packs.
182 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
183 Param->setInvalidDecl();
184 return;
185 }
186
Anders Carlsson66e30672009-08-25 01:02:06 +0000187 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000188 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
189 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000190 Param->setInvalidDecl();
191 return;
192 }
Mike Stump1eb44332009-09-09 15:08:12 +0000193
John McCall9ae2f072010-08-23 23:25:46 +0000194 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000195}
196
Douglas Gregor61366e92008-12-24 00:01:03 +0000197/// ActOnParamUnparsedDefaultArgument - We've seen a default
198/// argument for a function parameter, but we can't parse it yet
199/// because we're inside a class definition. Note that this default
200/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000201void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000202 SourceLocation EqualLoc,
203 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000204 if (!param)
205 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000206
John McCalld226f652010-08-21 09:40:31 +0000207 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000208 if (Param)
209 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Anders Carlsson5e300d12009-06-12 16:51:40 +0000211 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000212}
213
Douglas Gregor72b505b2008-12-16 21:30:33 +0000214/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
215/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000216void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000217 if (!param)
218 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
John McCalld226f652010-08-21 09:40:31 +0000220 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Anders Carlsson5e300d12009-06-12 16:51:40 +0000222 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Anders Carlsson5e300d12009-06-12 16:51:40 +0000224 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000225}
226
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000227/// CheckExtraCXXDefaultArguments - Check for any extra default
228/// arguments in the declarator, which is not a function declaration
229/// or definition and therefore is not permitted to have default
230/// arguments. This routine should be invoked for every declarator
231/// that is not a function declaration or definition.
232void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
233 // C++ [dcl.fct.default]p3
234 // A default argument expression shall be specified only in the
235 // parameter-declaration-clause of a function declaration or in a
236 // template-parameter (14.1). It shall not be specified for a
237 // parameter pack. If it is specified in a
238 // parameter-declaration-clause, it shall not occur within a
239 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000240 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000241 DeclaratorChunk &chunk = D.getTypeObject(i);
242 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000243 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
244 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000245 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000246 if (Param->hasUnparsedDefaultArg()) {
247 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000248 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
249 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
250 delete Toks;
251 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000252 } else if (Param->getDefaultArg()) {
253 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
254 << Param->getDefaultArg()->getSourceRange();
255 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000256 }
257 }
258 }
259 }
260}
261
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262// MergeCXXFunctionDecl - Merge two declarations of the same C++
263// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000264// type. Subroutine of MergeFunctionDecl. Returns true if there was an
265// error, false otherwise.
266bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
267 bool Invalid = false;
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000270 // For non-template functions, default arguments can be added in
271 // later declarations of a function in the same
272 // scope. Declarations in different scopes have completely
273 // distinct sets of default arguments. That is, declarations in
274 // inner scopes do not acquire default arguments from
275 // declarations in outer scopes, and vice versa. In a given
276 // function declaration, all parameters subsequent to a
277 // parameter with a default argument shall have default
278 // arguments supplied in this or previous declarations. A
279 // default argument shall not be redefined by a later
280 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000281 //
282 // C++ [dcl.fct.default]p6:
283 // Except for member functions of class templates, the default arguments
284 // in a member function definition that appears outside of the class
285 // definition are added to the set of default arguments provided by the
286 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
288 ParmVarDecl *OldParam = Old->getParamDecl(p);
289 ParmVarDecl *NewParam = New->getParamDecl(p);
290
Douglas Gregor6cc15182009-09-11 18:44:32 +0000291 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000292
Francois Pichet8d051e02011-04-10 03:03:52 +0000293 unsigned DiagDefaultParamID =
294 diag::err_param_default_argument_redefinition;
295
296 // MSVC accepts that default parameters be redefined for member functions
297 // of template class. The new default parameter's value is ignored.
298 Invalid = true;
299 if (getLangOptions().Microsoft) {
300 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
301 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000302 // Merge the old default argument into the new parameter.
303 NewParam->setHasInheritedDefaultArg();
304 if (OldParam->hasUninstantiatedDefaultArg())
305 NewParam->setUninstantiatedDefaultArg(
306 OldParam->getUninstantiatedDefaultArg());
307 else
308 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000309 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000310 Invalid = false;
311 }
312 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000313
Francois Pichet8cf90492011-04-10 04:58:30 +0000314 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
315 // hint here. Alternatively, we could walk the type-source information
316 // for NewParam to find the last source location in the type... but it
317 // isn't worth the effort right now. This is the kind of test case that
318 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000319 // int f(int);
320 // void g(int (*fp)(int) = f);
321 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000322 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000323 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000324
325 // Look for the function declaration where the default argument was
326 // actually written, which may be a declaration prior to Old.
327 for (FunctionDecl *Older = Old->getPreviousDeclaration();
328 Older; Older = Older->getPreviousDeclaration()) {
329 if (!Older->getParamDecl(p)->hasDefaultArg())
330 break;
331
332 OldParam = Older->getParamDecl(p);
333 }
334
335 Diag(OldParam->getLocation(), diag::note_previous_definition)
336 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000337 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000338 // Merge the old default argument into the new parameter.
339 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000340 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000341 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000342 if (OldParam->hasUninstantiatedDefaultArg())
343 NewParam->setUninstantiatedDefaultArg(
344 OldParam->getUninstantiatedDefaultArg());
345 else
John McCall3d6c1782010-05-04 01:53:42 +0000346 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000347 } else if (NewParam->hasDefaultArg()) {
348 if (New->getDescribedFunctionTemplate()) {
349 // Paragraph 4, quoted above, only applies to non-template functions.
350 Diag(NewParam->getLocation(),
351 diag::err_param_default_argument_template_redecl)
352 << NewParam->getDefaultArgRange();
353 Diag(Old->getLocation(), diag::note_template_prev_declaration)
354 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000355 } else if (New->getTemplateSpecializationKind()
356 != TSK_ImplicitInstantiation &&
357 New->getTemplateSpecializationKind() != TSK_Undeclared) {
358 // C++ [temp.expr.spec]p21:
359 // Default function arguments shall not be specified in a declaration
360 // or a definition for one of the following explicit specializations:
361 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000362 // - the explicit specialization of a member function template;
363 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000364 // template where the class template specialization to which the
365 // member function specialization belongs is implicitly
366 // instantiated.
367 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
368 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
369 << New->getDeclName()
370 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000371 } else if (New->getDeclContext()->isDependentContext()) {
372 // C++ [dcl.fct.default]p6 (DR217):
373 // Default arguments for a member function of a class template shall
374 // be specified on the initial declaration of the member function
375 // within the class template.
376 //
377 // Reading the tea leaves a bit in DR217 and its reference to DR205
378 // leads me to the conclusion that one cannot add default function
379 // arguments for an out-of-line definition of a member function of a
380 // dependent type.
381 int WhichKind = 2;
382 if (CXXRecordDecl *Record
383 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
384 if (Record->getDescribedClassTemplate())
385 WhichKind = 0;
386 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
387 WhichKind = 1;
388 else
389 WhichKind = 2;
390 }
391
392 Diag(NewParam->getLocation(),
393 diag::err_param_default_argument_member_template_redecl)
394 << WhichKind
395 << NewParam->getDefaultArgRange();
396 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 }
398 }
399
Douglas Gregore13ad832010-02-12 07:32:17 +0000400 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000401 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000402
Douglas Gregorcda9c672009-02-16 17:45:42 +0000403 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000404}
405
Sebastian Redl60618fa2011-03-12 11:50:43 +0000406/// \brief Merge the exception specifications of two variable declarations.
407///
408/// This is called when there's a redeclaration of a VarDecl. The function
409/// checks if the redeclaration might have an exception specification and
410/// validates compatibility and merges the specs if necessary.
411void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
412 // Shortcut if exceptions are disabled.
413 if (!getLangOptions().CXXExceptions)
414 return;
415
416 assert(Context.hasSameType(New->getType(), Old->getType()) &&
417 "Should only be called if types are otherwise the same.");
418
419 QualType NewType = New->getType();
420 QualType OldType = Old->getType();
421
422 // We're only interested in pointers and references to functions, as well
423 // as pointers to member functions.
424 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
425 NewType = R->getPointeeType();
426 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
427 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
428 NewType = P->getPointeeType();
429 OldType = OldType->getAs<PointerType>()->getPointeeType();
430 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
431 NewType = M->getPointeeType();
432 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
433 }
434
435 if (!NewType->isFunctionProtoType())
436 return;
437
438 // There's lots of special cases for functions. For function pointers, system
439 // libraries are hopefully not as broken so that we don't need these
440 // workarounds.
441 if (CheckEquivalentExceptionSpec(
442 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
443 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
444 New->setInvalidDecl();
445 }
446}
447
Chris Lattner3d1cee32008-04-08 05:04:30 +0000448/// CheckCXXDefaultArguments - Verify that the default arguments for a
449/// function declaration are well-formed according to C++
450/// [dcl.fct.default].
451void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
452 unsigned NumParams = FD->getNumParams();
453 unsigned p;
454
455 // Find first parameter with a default argument
456 for (p = 0; p < NumParams; ++p) {
457 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000458 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000459 break;
460 }
461
462 // C++ [dcl.fct.default]p4:
463 // In a given function declaration, all parameters
464 // subsequent to a parameter with a default argument shall
465 // have default arguments supplied in this or previous
466 // declarations. A default argument shall not be redefined
467 // by a later declaration (not even to the same value).
468 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000469 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000470 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000471 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000472 if (Param->isInvalidDecl())
473 /* We already complained about this parameter. */;
474 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000475 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000476 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000477 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000478 else
Mike Stump1eb44332009-09-09 15:08:12 +0000479 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000480 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner3d1cee32008-04-08 05:04:30 +0000482 LastMissingDefaultArg = p;
483 }
484 }
485
486 if (LastMissingDefaultArg > 0) {
487 // Some default arguments were missing. Clear out all of the
488 // default arguments up to (and including) the last missing
489 // default argument, so that we leave the function parameters
490 // in a semantically valid state.
491 for (p = 0; p <= LastMissingDefaultArg; ++p) {
492 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000493 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000494 Param->setDefaultArg(0);
495 }
496 }
497 }
498}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000499
Douglas Gregorb48fe382008-10-31 09:07:45 +0000500/// isCurrentClassName - Determine whether the identifier II is the
501/// name of the class type currently being defined. In the case of
502/// nested classes, this will only return true if II is the name of
503/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000504bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
505 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000506 assert(getLangOptions().CPlusPlus && "No class names in C!");
507
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000508 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000509 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000510 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000511 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
512 } else
513 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
514
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000515 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000516 return &II == CurDecl->getIdentifier();
517 else
518 return false;
519}
520
Mike Stump1eb44332009-09-09 15:08:12 +0000521/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000522///
523/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
524/// and returns NULL otherwise.
525CXXBaseSpecifier *
526Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
527 SourceRange SpecifierRange,
528 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000529 TypeSourceInfo *TInfo,
530 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000531 QualType BaseType = TInfo->getType();
532
Douglas Gregor2943aed2009-03-03 04:44:36 +0000533 // C++ [class.union]p1:
534 // A union shall not have base classes.
535 if (Class->isUnion()) {
536 Diag(Class->getLocation(), diag::err_base_clause_on_union)
537 << SpecifierRange;
538 return 0;
539 }
540
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000541 if (EllipsisLoc.isValid() &&
542 !TInfo->getType()->containsUnexpandedParameterPack()) {
543 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
544 << TInfo->getTypeLoc().getSourceRange();
545 EllipsisLoc = SourceLocation();
546 }
547
Douglas Gregor2943aed2009-03-03 04:44:36 +0000548 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000549 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000550 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000551 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000552
553 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000554
555 // Base specifiers must be record types.
556 if (!BaseType->isRecordType()) {
557 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
558 return 0;
559 }
560
561 // C++ [class.union]p1:
562 // A union shall not be used as a base class.
563 if (BaseType->isUnionType()) {
564 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
565 return 0;
566 }
567
568 // C++ [class.derived]p2:
569 // The class-name in a base-specifier shall not be an incompletely
570 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000571 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000572 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000573 << SpecifierRange)) {
574 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575 return 0;
John McCall572fc622010-08-17 07:23:57 +0000576 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577
Eli Friedman1d954f62009-08-15 21:55:26 +0000578 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000579 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000580 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000581 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000583 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
584 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000585
Anders Carlsson1d209272011-03-25 14:55:14 +0000586 // C++ [class]p3:
587 // If a class is marked final and it appears as a base-type-specifier in
588 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000589 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000590 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
591 << CXXBaseDecl->getDeclName();
592 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
593 << CXXBaseDecl->getDeclName();
594 return 0;
595 }
596
John McCall572fc622010-08-17 07:23:57 +0000597 if (BaseDecl->isInvalidDecl())
598 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000599
600 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000601 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000602 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000603 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000604}
605
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000606/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
607/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000608/// example:
609/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000610/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000611BaseResult
John McCalld226f652010-08-21 09:40:31 +0000612Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000613 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000614 ParsedType basetype, SourceLocation BaseLoc,
615 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000616 if (!classdecl)
617 return true;
618
Douglas Gregor40808ce2009-03-09 23:48:35 +0000619 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000620 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000621 if (!Class)
622 return true;
623
Nick Lewycky56062202010-07-26 16:56:01 +0000624 TypeSourceInfo *TInfo = 0;
625 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000626
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000627 if (EllipsisLoc.isInvalid() &&
628 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000629 UPPC_BaseType))
630 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000631
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000633 Virtual, Access, TInfo,
634 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregor2943aed2009-03-03 04:44:36 +0000637 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000639
Douglas Gregor2943aed2009-03-03 04:44:36 +0000640/// \brief Performs the actual work of attaching the given base class
641/// specifiers to a C++ class.
642bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
643 unsigned NumBases) {
644 if (NumBases == 0)
645 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000646
647 // Used to keep track of which base types we have already seen, so
648 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000649 // that the key is always the unqualified canonical type of the base
650 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000651 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
652
653 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000654 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000655 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000656 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000657 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000658 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000659 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000660 if (!Class->hasObjectMember()) {
661 if (const RecordType *FDTTy =
662 NewBaseType.getTypePtr()->getAs<RecordType>())
663 if (FDTTy->getDecl()->hasObjectMember())
664 Class->setHasObjectMember(true);
665 }
666
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000667 if (KnownBaseTypes[NewBaseType]) {
668 // C++ [class.mi]p3:
669 // A class shall not be specified as a direct base class of a
670 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000671 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000672 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000673 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000674 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000675
676 // Delete the duplicate base class specifier; we're going to
677 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000678 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000679
680 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000681 } else {
682 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000683 KnownBaseTypes[NewBaseType] = Bases[idx];
684 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000685 }
686 }
687
688 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000689 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000690
691 // Delete the remaining (good) base class specifiers, since their
692 // data has been copied into the CXXRecordDecl.
693 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000694 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000695
696 return Invalid;
697}
698
699/// ActOnBaseSpecifiers - Attach the given base specifiers to the
700/// class, after checking whether there are any duplicate base
701/// classes.
John McCalld226f652010-08-21 09:40:31 +0000702void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000703 unsigned NumBases) {
704 if (!ClassDecl || !Bases || !NumBases)
705 return;
706
707 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000708 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000709 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000710}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000711
John McCall3cb0ebd2010-03-10 03:28:59 +0000712static CXXRecordDecl *GetClassForType(QualType T) {
713 if (const RecordType *RT = T->getAs<RecordType>())
714 return cast<CXXRecordDecl>(RT->getDecl());
715 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
716 return ICT->getDecl();
717 else
718 return 0;
719}
720
Douglas Gregora8f32e02009-10-06 17:59:45 +0000721/// \brief Determine whether the type \p Derived is a C++ class that is
722/// derived from the type \p Base.
723bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
724 if (!getLangOptions().CPlusPlus)
725 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000726
727 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
728 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000729 return false;
730
John McCall3cb0ebd2010-03-10 03:28:59 +0000731 CXXRecordDecl *BaseRD = GetClassForType(Base);
732 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000733 return false;
734
John McCall86ff3082010-02-04 22:26:26 +0000735 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
736 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000737}
738
739/// \brief Determine whether the type \p Derived is a C++ class that is
740/// derived from the type \p Base.
741bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
742 if (!getLangOptions().CPlusPlus)
743 return false;
744
John McCall3cb0ebd2010-03-10 03:28:59 +0000745 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
746 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000747 return false;
748
John McCall3cb0ebd2010-03-10 03:28:59 +0000749 CXXRecordDecl *BaseRD = GetClassForType(Base);
750 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000751 return false;
752
Douglas Gregora8f32e02009-10-06 17:59:45 +0000753 return DerivedRD->isDerivedFrom(BaseRD, Paths);
754}
755
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000756void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000757 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000758 assert(BasePathArray.empty() && "Base path array must be empty!");
759 assert(Paths.isRecordingPaths() && "Must record paths!");
760
761 const CXXBasePath &Path = Paths.front();
762
763 // We first go backward and check if we have a virtual base.
764 // FIXME: It would be better if CXXBasePath had the base specifier for
765 // the nearest virtual base.
766 unsigned Start = 0;
767 for (unsigned I = Path.size(); I != 0; --I) {
768 if (Path[I - 1].Base->isVirtual()) {
769 Start = I - 1;
770 break;
771 }
772 }
773
774 // Now add all bases.
775 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000776 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000777}
778
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000779/// \brief Determine whether the given base path includes a virtual
780/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000781bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
782 for (CXXCastPath::const_iterator B = BasePath.begin(),
783 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000784 B != BEnd; ++B)
785 if ((*B)->isVirtual())
786 return true;
787
788 return false;
789}
790
Douglas Gregora8f32e02009-10-06 17:59:45 +0000791/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
792/// conversion (where Derived and Base are class types) is
793/// well-formed, meaning that the conversion is unambiguous (and
794/// that all of the base classes are accessible). Returns true
795/// and emits a diagnostic if the code is ill-formed, returns false
796/// otherwise. Loc is the location where this routine should point to
797/// if there is an error, and Range is the source range to highlight
798/// if there is an error.
799bool
800Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000801 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000802 unsigned AmbigiousBaseConvID,
803 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000804 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000805 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000806 // First, determine whether the path from Derived to Base is
807 // ambiguous. This is slightly more expensive than checking whether
808 // the Derived to Base conversion exists, because here we need to
809 // explore multiple paths to determine if there is an ambiguity.
810 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
811 /*DetectVirtual=*/false);
812 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
813 assert(DerivationOkay &&
814 "Can only be used with a derived-to-base conversion");
815 (void)DerivationOkay;
816
817 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000818 if (InaccessibleBaseID) {
819 // Check that the base class can be accessed.
820 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
821 InaccessibleBaseID)) {
822 case AR_inaccessible:
823 return true;
824 case AR_accessible:
825 case AR_dependent:
826 case AR_delayed:
827 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000828 }
John McCall6b2accb2010-02-10 09:31:12 +0000829 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000830
831 // Build a base path if necessary.
832 if (BasePath)
833 BuildBasePathArray(Paths, *BasePath);
834 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835 }
836
837 // We know that the derived-to-base conversion is ambiguous, and
838 // we're going to produce a diagnostic. Perform the derived-to-base
839 // search just one more time to compute all of the possible paths so
840 // that we can print them out. This is more expensive than any of
841 // the previous derived-to-base checks we've done, but at this point
842 // performance isn't as much of an issue.
843 Paths.clear();
844 Paths.setRecordingPaths(true);
845 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
846 assert(StillOkay && "Can only be used with a derived-to-base conversion");
847 (void)StillOkay;
848
849 // Build up a textual representation of the ambiguous paths, e.g.,
850 // D -> B -> A, that will be used to illustrate the ambiguous
851 // conversions in the diagnostic. We only print one of the paths
852 // to each base class subobject.
853 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
854
855 Diag(Loc, AmbigiousBaseConvID)
856 << Derived << Base << PathDisplayStr << Range << Name;
857 return true;
858}
859
860bool
861Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000862 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000863 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000864 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000865 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000866 IgnoreAccess ? 0
867 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000868 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000869 Loc, Range, DeclarationName(),
870 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000871}
872
873
874/// @brief Builds a string representing ambiguous paths from a
875/// specific derived class to different subobjects of the same base
876/// class.
877///
878/// This function builds a string that can be used in error messages
879/// to show the different paths that one can take through the
880/// inheritance hierarchy to go from the derived class to different
881/// subobjects of a base class. The result looks something like this:
882/// @code
883/// struct D -> struct B -> struct A
884/// struct D -> struct C -> struct A
885/// @endcode
886std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
887 std::string PathDisplayStr;
888 std::set<unsigned> DisplayedPaths;
889 for (CXXBasePaths::paths_iterator Path = Paths.begin();
890 Path != Paths.end(); ++Path) {
891 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
892 // We haven't displayed a path to this particular base
893 // class subobject yet.
894 PathDisplayStr += "\n ";
895 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
896 for (CXXBasePath::const_iterator Element = Path->begin();
897 Element != Path->end(); ++Element)
898 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
899 }
900 }
901
902 return PathDisplayStr;
903}
904
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000905//===----------------------------------------------------------------------===//
906// C++ class member Handling
907//===----------------------------------------------------------------------===//
908
Abramo Bagnara6206d532010-06-05 05:09:32 +0000909/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000910Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
911 SourceLocation ASLoc,
912 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000913 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000914 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000915 ASLoc, ColonLoc);
916 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000917 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000918}
919
Anders Carlsson9e682d92011-01-20 05:57:14 +0000920/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000921void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000922 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
923 if (!MD || !MD->isVirtual())
924 return;
925
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000926 if (MD->isDependentContext())
927 return;
928
Anders Carlsson9e682d92011-01-20 05:57:14 +0000929 // C++0x [class.virtual]p3:
930 // If a virtual function is marked with the virt-specifier override and does
931 // not override a member function of a base class,
932 // the program is ill-formed.
933 bool HasOverriddenMethods =
934 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000935 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000936 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000937 diag::err_function_marked_override_not_overriding)
938 << MD->getDeclName();
939 return;
940 }
941}
942
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000943/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
944/// function overrides a virtual member function marked 'final', according to
945/// C++0x [class.virtual]p3.
946bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
947 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000948 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +0000949 return false;
950
951 Diag(New->getLocation(), diag::err_final_function_overridden)
952 << New->getDeclName();
953 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
954 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000955}
956
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000957/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
958/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
959/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000960/// any.
John McCalld226f652010-08-21 09:40:31 +0000961Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000962Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000963 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000964 ExprTy *BW, const VirtSpecifiers &VS,
965 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld1a78462009-11-24 23:38:44 +0000966 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000967 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000968 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
969 DeclarationName Name = NameInfo.getName();
970 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000971
972 // For anonymous bitfields, the location should point to the type.
973 if (Loc.isInvalid())
974 Loc = D.getSourceRange().getBegin();
975
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000976 Expr *BitWidth = static_cast<Expr*>(BW);
977 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000978
John McCall4bde1e12010-06-04 08:34:12 +0000979 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000980 assert(!DS.isFriendSpecified());
981
John McCall4bde1e12010-06-04 08:34:12 +0000982 bool isFunc = false;
983 if (D.isFunctionDeclarator())
984 isFunc = true;
985 else if (D.getNumTypeObjects() == 0 &&
986 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000987 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000988 isFunc = TDType->isFunctionType();
989 }
990
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000991 // C++ 9.2p6: A member shall not be declared to have automatic storage
992 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000993 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
994 // data members and cannot be applied to names declared const or static,
995 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000996 switch (DS.getStorageClassSpec()) {
997 case DeclSpec::SCS_unspecified:
998 case DeclSpec::SCS_typedef:
999 case DeclSpec::SCS_static:
1000 // FALL THROUGH.
1001 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001002 case DeclSpec::SCS_mutable:
1003 if (isFunc) {
1004 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001005 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001006 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001007 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Sebastian Redla11f42f2008-11-17 23:24:37 +00001009 // FIXME: It would be nicer if the keyword was ignored only for this
1010 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001011 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001012 }
1013 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001014 default:
1015 if (DS.getStorageClassSpecLoc().isValid())
1016 Diag(DS.getStorageClassSpecLoc(),
1017 diag::err_storageclass_invalid_for_member);
1018 else
1019 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1020 D.getMutableDeclSpec().ClearStorageClassSpecs();
1021 }
1022
Sebastian Redl669d5d72008-11-14 23:42:31 +00001023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001025 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001026
1027 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001028 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001029 CXXScopeSpec &SS = D.getCXXScopeSpec();
1030
1031
1032 if (SS.isSet() && !SS.isInvalid()) {
1033 // The user provided a superfluous scope specifier inside a class
1034 // definition:
1035 //
1036 // class X {
1037 // int X::member;
1038 // };
1039 DeclContext *DC = 0;
1040 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1041 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1042 << Name << FixItHint::CreateRemoval(SS.getRange());
1043 else
1044 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1045 << Name << SS.getRange();
1046
1047 SS.clear();
1048 }
1049
Douglas Gregor37b372b2009-08-20 22:52:58 +00001050 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001051 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001052 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1053 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001054 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001055 } else {
John McCalld226f652010-08-21 09:40:31 +00001056 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001057 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001058 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001059 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001060
1061 // Non-instance-fields can't have a bitfield.
1062 if (BitWidth) {
1063 if (Member->isInvalidDecl()) {
1064 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001065 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001066 // C++ 9.6p3: A bit-field shall not be a static member.
1067 // "static member 'A' cannot be a bit-field"
1068 Diag(Loc, diag::err_static_not_bitfield)
1069 << Name << BitWidth->getSourceRange();
1070 } else if (isa<TypedefDecl>(Member)) {
1071 // "typedef member 'x' cannot be a bit-field"
1072 Diag(Loc, diag::err_typedef_not_bitfield)
1073 << Name << BitWidth->getSourceRange();
1074 } else {
1075 // A function typedef ("typedef int f(); f a;").
1076 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1077 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001078 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001079 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Chris Lattner8b963ef2009-03-05 23:01:03 +00001082 BitWidth = 0;
1083 Member->setInvalidDecl();
1084 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001085
1086 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Douglas Gregor37b372b2009-08-20 22:52:58 +00001088 // If we have declared a member function template, set the access of the
1089 // templated declaration as well.
1090 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1091 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001092 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001093
Anders Carlssonaae5af22011-01-20 04:34:22 +00001094 if (VS.isOverrideSpecified()) {
1095 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1096 if (!MD || !MD->isVirtual()) {
1097 Diag(Member->getLocStart(),
1098 diag::override_keyword_only_allowed_on_virtual_member_functions)
1099 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001100 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001101 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001102 }
1103 if (VS.isFinalSpecified()) {
1104 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1105 if (!MD || !MD->isVirtual()) {
1106 Diag(Member->getLocStart(),
1107 diag::override_keyword_only_allowed_on_virtual_member_functions)
1108 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001109 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001110 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001111 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001112
Douglas Gregorf5251602011-03-08 17:10:18 +00001113 if (VS.getLastLocation().isValid()) {
1114 // Update the end location of a method that has a virt-specifiers.
1115 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1116 MD->setRangeEnd(VS.getLastLocation());
1117 }
1118
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001119 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001120
Douglas Gregor10bd3682008-11-17 22:58:34 +00001121 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001122
Douglas Gregor021c3b32009-03-11 23:00:04 +00001123 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001124 AddInitializerToDecl(Member, Init, false,
1125 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redle2b68332009-04-12 17:16:29 +00001126 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001127 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001128
Richard Smith483b9f32011-02-21 20:05:19 +00001129 FinalizeDeclaration(Member);
1130
John McCallb25b2952011-02-15 07:12:36 +00001131 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001132 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001133 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001134}
1135
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001136/// \brief Find the direct and/or virtual base specifiers that
1137/// correspond to the given base type, for use in base initialization
1138/// within a constructor.
1139static bool FindBaseInitializer(Sema &SemaRef,
1140 CXXRecordDecl *ClassDecl,
1141 QualType BaseType,
1142 const CXXBaseSpecifier *&DirectBaseSpec,
1143 const CXXBaseSpecifier *&VirtualBaseSpec) {
1144 // First, check for a direct base class.
1145 DirectBaseSpec = 0;
1146 for (CXXRecordDecl::base_class_const_iterator Base
1147 = ClassDecl->bases_begin();
1148 Base != ClassDecl->bases_end(); ++Base) {
1149 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1150 // We found a direct base of this type. That's what we're
1151 // initializing.
1152 DirectBaseSpec = &*Base;
1153 break;
1154 }
1155 }
1156
1157 // Check for a virtual base class.
1158 // FIXME: We might be able to short-circuit this if we know in advance that
1159 // there are no virtual bases.
1160 VirtualBaseSpec = 0;
1161 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1162 // We haven't found a base yet; search the class hierarchy for a
1163 // virtual base class.
1164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1165 /*DetectVirtual=*/false);
1166 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1167 BaseType, Paths)) {
1168 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1169 Path != Paths.end(); ++Path) {
1170 if (Path->back().Base->isVirtual()) {
1171 VirtualBaseSpec = Path->back().Base;
1172 break;
1173 }
1174 }
1175 }
1176 }
1177
1178 return DirectBaseSpec || VirtualBaseSpec;
1179}
1180
Douglas Gregor7ad83902008-11-05 04:29:56 +00001181/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001182MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001183Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001184 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001185 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001186 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001187 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001188 SourceLocation IdLoc,
1189 SourceLocation LParenLoc,
1190 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001191 SourceLocation RParenLoc,
1192 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001193 if (!ConstructorD)
1194 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001196 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
1198 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001199 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001200 if (!Constructor) {
1201 // The user wrote a constructor initializer on a function that is
1202 // not a C++ constructor. Ignore the error for now, because we may
1203 // have more member initializers coming; we'll diagnose it just
1204 // once in ActOnMemInitializers.
1205 return true;
1206 }
1207
1208 CXXRecordDecl *ClassDecl = Constructor->getParent();
1209
1210 // C++ [class.base.init]p2:
1211 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001212 // constructor's class and, if not found in that scope, are looked
1213 // up in the scope containing the constructor's definition.
1214 // [Note: if the constructor's class contains a member with the
1215 // same name as a direct or virtual base class of the class, a
1216 // mem-initializer-id naming the member or base class and composed
1217 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001218 // mem-initializer-id for the hidden base class may be specified
1219 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001220 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001221 // Look for a member, first.
1222 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001223 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001224 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001225 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001226 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001227
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001228 if (Member) {
1229 if (EllipsisLoc.isValid())
1230 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1231 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1232
Francois Pichet00eb3f92010-12-04 09:14:42 +00001233 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001234 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001235 }
1236
Francois Pichet00eb3f92010-12-04 09:14:42 +00001237 // Handle anonymous union case.
1238 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001239 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1240 if (EllipsisLoc.isValid())
1241 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1242 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1243
Francois Pichet00eb3f92010-12-04 09:14:42 +00001244 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1245 NumArgs, IdLoc,
1246 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001247 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001248 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001249 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001250 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001251 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001252 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001253
1254 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001255 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001256 } else {
1257 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1258 LookupParsedName(R, S, &SS);
1259
1260 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1261 if (!TyD) {
1262 if (R.isAmbiguous()) return true;
1263
John McCallfd225442010-04-09 19:01:14 +00001264 // We don't want access-control diagnostics here.
1265 R.suppressDiagnostics();
1266
Douglas Gregor7a886e12010-01-19 06:46:48 +00001267 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1268 bool NotUnknownSpecialization = false;
1269 DeclContext *DC = computeDeclContext(SS, false);
1270 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1271 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1272
1273 if (!NotUnknownSpecialization) {
1274 // When the scope specifier can refer to a member of an unknown
1275 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001276 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1277 SS.getWithLocInContext(Context),
1278 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001279 if (BaseType.isNull())
1280 return true;
1281
Douglas Gregor7a886e12010-01-19 06:46:48 +00001282 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001283 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001284 }
1285 }
1286
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001287 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001288 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001289 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1290 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001291 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001292 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001293 // We have found a non-static data member with a similar
1294 // name to what was typed; complain and initialize that
1295 // member.
1296 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1297 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001298 << FixItHint::CreateReplacement(R.getNameLoc(),
1299 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001300 Diag(Member->getLocation(), diag::note_previous_decl)
1301 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001302
1303 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1304 LParenLoc, RParenLoc);
1305 }
1306 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1307 const CXXBaseSpecifier *DirectBaseSpec;
1308 const CXXBaseSpecifier *VirtualBaseSpec;
1309 if (FindBaseInitializer(*this, ClassDecl,
1310 Context.getTypeDeclType(Type),
1311 DirectBaseSpec, VirtualBaseSpec)) {
1312 // We have found a direct or virtual base class with a
1313 // similar name to what was typed; complain and initialize
1314 // that base class.
1315 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1316 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001317 << FixItHint::CreateReplacement(R.getNameLoc(),
1318 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001319
1320 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1321 : VirtualBaseSpec;
1322 Diag(BaseSpec->getSourceRange().getBegin(),
1323 diag::note_base_class_specified_here)
1324 << BaseSpec->getType()
1325 << BaseSpec->getSourceRange();
1326
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001327 TyD = Type;
1328 }
1329 }
1330 }
1331
Douglas Gregor7a886e12010-01-19 06:46:48 +00001332 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001333 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1334 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1335 return true;
1336 }
John McCall2b194412009-12-21 10:41:20 +00001337 }
1338
Douglas Gregor7a886e12010-01-19 06:46:48 +00001339 if (BaseType.isNull()) {
1340 BaseType = Context.getTypeDeclType(TyD);
1341 if (SS.isSet()) {
1342 NestedNameSpecifier *Qualifier =
1343 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001344
Douglas Gregor7a886e12010-01-19 06:46:48 +00001345 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001346 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001347 }
John McCall2b194412009-12-21 10:41:20 +00001348 }
1349 }
Mike Stump1eb44332009-09-09 15:08:12 +00001350
John McCalla93c9342009-12-07 02:54:59 +00001351 if (!TInfo)
1352 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001353
John McCalla93c9342009-12-07 02:54:59 +00001354 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001355 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001356}
1357
John McCallb4190042009-11-04 23:02:40 +00001358/// Checks an initializer expression for use of uninitialized fields, such as
1359/// containing the field that is being initialized. Returns true if there is an
1360/// uninitialized field was used an updates the SourceLocation parameter; false
1361/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001362static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001363 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001364 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001365 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1366
Nick Lewycky43ad1822010-06-15 07:32:55 +00001367 if (isa<CallExpr>(S)) {
1368 // Do not descend into function calls or constructors, as the use
1369 // of an uninitialized field may be valid. One would have to inspect
1370 // the contents of the function/ctor to determine if it is safe or not.
1371 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1372 // may be safe, depending on what the function/ctor does.
1373 return false;
1374 }
1375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1376 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001377
1378 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1379 // The member expression points to a static data member.
1380 assert(VD->isStaticDataMember() &&
1381 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001382 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001383 return false;
1384 }
1385
1386 if (isa<EnumConstantDecl>(RhsField)) {
1387 // The member expression points to an enum.
1388 return false;
1389 }
1390
John McCallb4190042009-11-04 23:02:40 +00001391 if (RhsField == LhsField) {
1392 // Initializing a field with itself. Throw a warning.
1393 // But wait; there are exceptions!
1394 // Exception #1: The field may not belong to this record.
1395 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001396 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001397 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1398 // Even though the field matches, it does not belong to this record.
1399 return false;
1400 }
1401 // None of the exceptions triggered; return true to indicate an
1402 // uninitialized field was used.
1403 *L = ME->getMemberLoc();
1404 return true;
1405 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001406 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001407 // sizeof/alignof doesn't reference contents, do not warn.
1408 return false;
1409 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1410 // address-of doesn't reference contents (the pointer may be dereferenced
1411 // in the same expression but it would be rare; and weird).
1412 if (UOE->getOpcode() == UO_AddrOf)
1413 return false;
John McCallb4190042009-11-04 23:02:40 +00001414 }
John McCall7502c1d2011-02-13 04:07:26 +00001415 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001416 if (!*it) {
1417 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001418 continue;
1419 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001420 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1421 return true;
John McCallb4190042009-11-04 23:02:40 +00001422 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001423 return false;
John McCallb4190042009-11-04 23:02:40 +00001424}
1425
John McCallf312b1e2010-08-26 23:41:50 +00001426MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001427Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001428 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001429 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001430 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001431 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1432 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1433 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001434 "Member must be a FieldDecl or IndirectFieldDecl");
1435
Douglas Gregor464b2f02010-11-05 22:21:31 +00001436 if (Member->isInvalidDecl())
1437 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001438
John McCallb4190042009-11-04 23:02:40 +00001439 // Diagnose value-uses of fields to initialize themselves, e.g.
1440 // foo(foo)
1441 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001442 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001443 for (unsigned i = 0; i < NumArgs; ++i) {
1444 SourceLocation L;
1445 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1446 // FIXME: Return true in the case when other fields are used before being
1447 // uninitialized. For example, let this field be the i'th field. When
1448 // initializing the i'th field, throw a warning if any of the >= i'th
1449 // fields are used, as they are not yet initialized.
1450 // Right now we are only handling the case where the i'th field uses
1451 // itself in its initializer.
1452 Diag(L, diag::warn_field_is_uninit);
1453 }
1454 }
1455
Eli Friedman59c04372009-07-29 19:44:27 +00001456 bool HasDependentArg = false;
1457 for (unsigned i = 0; i < NumArgs; i++)
1458 HasDependentArg |= Args[i]->isTypeDependent();
1459
Chandler Carruth894aed92010-12-06 09:23:57 +00001460 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001461 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001462 // Can't check initialization for a member of dependent type or when
1463 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001464 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1465 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001466
1467 // Erase any temporaries within this evaluation context; we're not
1468 // going to track them in the AST, since we'll be rebuilding the
1469 // ASTs during template instantiation.
1470 ExprTemporaries.erase(
1471 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1472 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001473 } else {
1474 // Initialize the member.
1475 InitializedEntity MemberEntity =
1476 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1477 : InitializedEntity::InitializeMember(IndirectMember, 0);
1478 InitializationKind Kind =
1479 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001480
Chandler Carruth894aed92010-12-06 09:23:57 +00001481 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1482
1483 ExprResult MemberInit =
1484 InitSeq.Perform(*this, MemberEntity, Kind,
1485 MultiExprArg(*this, Args, NumArgs), 0);
1486 if (MemberInit.isInvalid())
1487 return true;
1488
1489 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1490
1491 // C++0x [class.base.init]p7:
1492 // The initialization of each base and member constitutes a
1493 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001494 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001495 if (MemberInit.isInvalid())
1496 return true;
1497
1498 // If we are in a dependent context, template instantiation will
1499 // perform this type-checking again. Just save the arguments that we
1500 // received in a ParenListExpr.
1501 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1502 // of the information that we have about the member
1503 // initializer. However, deconstructing the ASTs is a dicey process,
1504 // and this approach is far more likely to get the corner cases right.
1505 if (CurContext->isDependentContext())
1506 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1507 RParenLoc);
1508 else
1509 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001510 }
1511
Chandler Carruth894aed92010-12-06 09:23:57 +00001512 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001513 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001514 IdLoc, LParenLoc, Init,
1515 RParenLoc);
1516 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001517 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001518 IdLoc, LParenLoc, Init,
1519 RParenLoc);
1520 }
Eli Friedman59c04372009-07-29 19:44:27 +00001521}
1522
John McCallf312b1e2010-08-26 23:41:50 +00001523MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001524Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1525 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001526 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001527 SourceLocation LParenLoc,
1528 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001529 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001530 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1531 if (!LangOpts.CPlusPlus0x)
1532 return Diag(Loc, diag::err_delegation_0x_only)
1533 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001534
Sean Hunt41717662011-02-26 19:13:13 +00001535 // Initialize the object.
1536 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1537 QualType(ClassDecl->getTypeForDecl(), 0));
1538 InitializationKind Kind =
1539 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1540
1541 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1542
1543 ExprResult DelegationInit =
1544 InitSeq.Perform(*this, DelegationEntity, Kind,
1545 MultiExprArg(*this, Args, NumArgs), 0);
1546 if (DelegationInit.isInvalid())
1547 return true;
1548
1549 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1550 CXXConstructorDecl *Constructor = ConExpr->getConstructor();
1551 assert(Constructor && "Delegating constructor with no target?");
1552
1553 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1554
1555 // C++0x [class.base.init]p7:
1556 // The initialization of each base and member constitutes a
1557 // full-expression.
1558 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1559 if (DelegationInit.isInvalid())
1560 return true;
1561
1562 // If we are in a dependent context, template instantiation will
1563 // perform this type-checking again. Just save the arguments that we
1564 // received in a ParenListExpr.
1565 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1566 // of the information that we have about the base
1567 // initializer. However, deconstructing the ASTs is a dicey process,
1568 // and this approach is far more likely to get the corner cases right.
1569 if (CurContext->isDependentContext()) {
1570 ExprResult Init
1571 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1572 NumArgs, RParenLoc));
1573 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1574 Constructor, Init.takeAs<Expr>(),
1575 RParenLoc);
1576 }
1577
1578 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1579 DelegationInit.takeAs<Expr>(),
1580 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001581}
1582
1583MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001584Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001585 Expr **Args, unsigned NumArgs,
1586 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001587 CXXRecordDecl *ClassDecl,
1588 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001589 bool HasDependentArg = false;
1590 for (unsigned i = 0; i < NumArgs; i++)
1591 HasDependentArg |= Args[i]->isTypeDependent();
1592
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001593 SourceLocation BaseLoc
1594 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1595
1596 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1597 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1598 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1599
1600 // C++ [class.base.init]p2:
1601 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001602 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001603 // of that class, the mem-initializer is ill-formed. A
1604 // mem-initializer-list can initialize a base class using any
1605 // name that denotes that base class type.
1606 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1607
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001608 if (EllipsisLoc.isValid()) {
1609 // This is a pack expansion.
1610 if (!BaseType->containsUnexpandedParameterPack()) {
1611 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1612 << SourceRange(BaseLoc, RParenLoc);
1613
1614 EllipsisLoc = SourceLocation();
1615 }
1616 } else {
1617 // Check for any unexpanded parameter packs.
1618 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1619 return true;
1620
1621 for (unsigned I = 0; I != NumArgs; ++I)
1622 if (DiagnoseUnexpandedParameterPack(Args[I]))
1623 return true;
1624 }
1625
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001626 // Check for direct and virtual base classes.
1627 const CXXBaseSpecifier *DirectBaseSpec = 0;
1628 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1629 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001630 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1631 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001632 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1633 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001634
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001635 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1636 VirtualBaseSpec);
1637
1638 // C++ [base.class.init]p2:
1639 // Unless the mem-initializer-id names a nonstatic data member of the
1640 // constructor's class or a direct or virtual base of that class, the
1641 // mem-initializer is ill-formed.
1642 if (!DirectBaseSpec && !VirtualBaseSpec) {
1643 // If the class has any dependent bases, then it's possible that
1644 // one of those types will resolve to the same type as
1645 // BaseType. Therefore, just treat this as a dependent base
1646 // class initialization. FIXME: Should we try to check the
1647 // initialization anyway? It seems odd.
1648 if (ClassDecl->hasAnyDependentBases())
1649 Dependent = true;
1650 else
1651 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1652 << BaseType << Context.getTypeDeclType(ClassDecl)
1653 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1654 }
1655 }
1656
1657 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001658 // Can't check initialization for a base of dependent type or when
1659 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001660 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001661 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1662 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001663
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001664 // Erase any temporaries within this evaluation context; we're not
1665 // going to track them in the AST, since we'll be rebuilding the
1666 // ASTs during template instantiation.
1667 ExprTemporaries.erase(
1668 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1669 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Sean Huntcbb67482011-01-08 20:30:50 +00001671 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001672 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001673 LParenLoc,
1674 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001675 RParenLoc,
1676 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001677 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001678
1679 // C++ [base.class.init]p2:
1680 // If a mem-initializer-id is ambiguous because it designates both
1681 // a direct non-virtual base class and an inherited virtual base
1682 // class, the mem-initializer is ill-formed.
1683 if (DirectBaseSpec && VirtualBaseSpec)
1684 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001685 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001686
1687 CXXBaseSpecifier *BaseSpec
1688 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1689 if (!BaseSpec)
1690 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1691
1692 // Initialize the base.
1693 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001694 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001695 InitializationKind Kind =
1696 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1697
1698 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1699
John McCall60d7b3a2010-08-24 06:29:42 +00001700 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001701 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001702 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001703 if (BaseInit.isInvalid())
1704 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001705
1706 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001707
1708 // C++0x [class.base.init]p7:
1709 // The initialization of each base and member constitutes a
1710 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001711 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001712 if (BaseInit.isInvalid())
1713 return true;
1714
1715 // If we are in a dependent context, template instantiation will
1716 // perform this type-checking again. Just save the arguments that we
1717 // received in a ParenListExpr.
1718 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1719 // of the information that we have about the base
1720 // initializer. However, deconstructing the ASTs is a dicey process,
1721 // and this approach is far more likely to get the corner cases right.
1722 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001723 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001724 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1725 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001726 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001727 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001728 LParenLoc,
1729 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001730 RParenLoc,
1731 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001732 }
1733
Sean Huntcbb67482011-01-08 20:30:50 +00001734 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001735 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001736 LParenLoc,
1737 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001738 RParenLoc,
1739 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001740}
1741
Anders Carlssone5ef7402010-04-23 03:10:23 +00001742/// ImplicitInitializerKind - How an implicit base or member initializer should
1743/// initialize its base or member.
1744enum ImplicitInitializerKind {
1745 IIK_Default,
1746 IIK_Copy,
1747 IIK_Move
1748};
1749
Anders Carlssondefefd22010-04-23 02:00:02 +00001750static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001751BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001752 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001753 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001754 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001755 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001756 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001757 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1758 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001759
John McCall60d7b3a2010-08-24 06:29:42 +00001760 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001761
1762 switch (ImplicitInitKind) {
1763 case IIK_Default: {
1764 InitializationKind InitKind
1765 = InitializationKind::CreateDefault(Constructor->getLocation());
1766 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1767 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001768 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001769 break;
1770 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001771
Anders Carlssone5ef7402010-04-23 03:10:23 +00001772 case IIK_Copy: {
1773 ParmVarDecl *Param = Constructor->getParamDecl(0);
1774 QualType ParamType = Param->getType().getNonReferenceType();
1775
1776 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001777 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001778 Constructor->getLocation(), ParamType,
1779 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001780
Anders Carlssonc7957502010-04-24 22:02:54 +00001781 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001782 QualType ArgTy =
1783 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1784 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001785
1786 CXXCastPath BasePath;
1787 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001788 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1789 CK_UncheckedDerivedToBase,
1790 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001791
Anders Carlssone5ef7402010-04-23 03:10:23 +00001792 InitializationKind InitKind
1793 = InitializationKind::CreateDirect(Constructor->getLocation(),
1794 SourceLocation(), SourceLocation());
1795 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1796 &CopyCtorArg, 1);
1797 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001798 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001799 break;
1800 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001801
Anders Carlssone5ef7402010-04-23 03:10:23 +00001802 case IIK_Move:
1803 assert(false && "Unhandled initializer kind!");
1804 }
John McCall9ae2f072010-08-23 23:25:46 +00001805
Douglas Gregor53c374f2010-12-07 00:41:46 +00001806 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001807 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001808 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001809
Anders Carlssondefefd22010-04-23 02:00:02 +00001810 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001811 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001812 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1813 SourceLocation()),
1814 BaseSpec->isVirtual(),
1815 SourceLocation(),
1816 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001817 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001818 SourceLocation());
1819
Anders Carlssondefefd22010-04-23 02:00:02 +00001820 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001821}
1822
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001823static bool
1824BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001825 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001826 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001827 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001828 if (Field->isInvalidDecl())
1829 return true;
1830
Chandler Carruthf186b542010-06-29 23:50:44 +00001831 SourceLocation Loc = Constructor->getLocation();
1832
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001833 if (ImplicitInitKind == IIK_Copy) {
1834 ParmVarDecl *Param = Constructor->getParamDecl(0);
1835 QualType ParamType = Param->getType().getNonReferenceType();
1836
1837 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001838 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001839 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001840
1841 // Build a reference to this field within the parameter.
1842 CXXScopeSpec SS;
1843 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1844 Sema::LookupMemberName);
1845 MemberLookup.addDecl(Field, AS_public);
1846 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001847 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001848 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001849 ParamType, Loc,
1850 /*IsArrow=*/false,
1851 SS,
1852 /*FirstQualifierInScope=*/0,
1853 MemberLookup,
1854 /*TemplateArgs=*/0);
1855 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001856 return true;
1857
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001858 // When the field we are copying is an array, create index variables for
1859 // each dimension of the array. We use these index variables to subscript
1860 // the source array, and other clients (e.g., CodeGen) will perform the
1861 // necessary iteration with these index variables.
1862 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1863 QualType BaseType = Field->getType();
1864 QualType SizeType = SemaRef.Context.getSizeType();
1865 while (const ConstantArrayType *Array
1866 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1867 // Create the iteration variable for this array index.
1868 IdentifierInfo *IterationVarName = 0;
1869 {
1870 llvm::SmallString<8> Str;
1871 llvm::raw_svector_ostream OS(Str);
1872 OS << "__i" << IndexVariables.size();
1873 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1874 }
1875 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001876 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001877 IterationVarName, SizeType,
1878 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001879 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001880 IndexVariables.push_back(IterationVar);
1881
1882 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001883 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001884 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001885 assert(!IterationVarRef.isInvalid() &&
1886 "Reference to invented variable cannot fail!");
1887
1888 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001889 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001890 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001891 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001892 Loc);
1893 if (CopyCtorArg.isInvalid())
1894 return true;
1895
1896 BaseType = Array->getElementType();
1897 }
1898
1899 // Construct the entity that we will be initializing. For an array, this
1900 // will be first element in the array, which may require several levels
1901 // of array-subscript entities.
1902 llvm::SmallVector<InitializedEntity, 4> Entities;
1903 Entities.reserve(1 + IndexVariables.size());
1904 Entities.push_back(InitializedEntity::InitializeMember(Field));
1905 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1906 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1907 0,
1908 Entities.back()));
1909
1910 // Direct-initialize to use the copy constructor.
1911 InitializationKind InitKind =
1912 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1913
1914 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1915 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1916 &CopyCtorArgE, 1);
1917
John McCall60d7b3a2010-08-24 06:29:42 +00001918 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001919 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001920 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001921 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001922 if (MemberInit.isInvalid())
1923 return true;
1924
1925 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001926 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001927 MemberInit.takeAs<Expr>(), Loc,
1928 IndexVariables.data(),
1929 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001930 return false;
1931 }
1932
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001933 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1934
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001935 QualType FieldBaseElementType =
1936 SemaRef.Context.getBaseElementType(Field->getType());
1937
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001938 if (FieldBaseElementType->isRecordType()) {
1939 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001940 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001941 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001942
1943 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001944 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001945 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001946
Douglas Gregor53c374f2010-12-07 00:41:46 +00001947 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001948 if (MemberInit.isInvalid())
1949 return true;
1950
1951 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001952 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001953 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001954 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001955 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001956 return false;
1957 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001958
1959 if (FieldBaseElementType->isReferenceType()) {
1960 SemaRef.Diag(Constructor->getLocation(),
1961 diag::err_uninitialized_member_in_ctor)
1962 << (int)Constructor->isImplicit()
1963 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1964 << 0 << Field->getDeclName();
1965 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1966 return true;
1967 }
1968
1969 if (FieldBaseElementType.isConstQualified()) {
1970 SemaRef.Diag(Constructor->getLocation(),
1971 diag::err_uninitialized_member_in_ctor)
1972 << (int)Constructor->isImplicit()
1973 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1974 << 1 << Field->getDeclName();
1975 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1976 return true;
1977 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001978
1979 // Nothing to initialize.
1980 CXXMemberInit = 0;
1981 return false;
1982}
John McCallf1860e52010-05-20 23:23:51 +00001983
1984namespace {
1985struct BaseAndFieldInfo {
1986 Sema &S;
1987 CXXConstructorDecl *Ctor;
1988 bool AnyErrorsInInits;
1989 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001990 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1991 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001992
1993 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1994 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1995 // FIXME: Handle implicit move constructors.
1996 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1997 IIK = IIK_Copy;
1998 else
1999 IIK = IIK_Default;
2000 }
2001};
2002}
2003
2004static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2005 FieldDecl *Top, FieldDecl *Field) {
2006
Chandler Carruthe861c602010-06-30 02:59:29 +00002007 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002008 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002009 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002010 return false;
2011 }
2012
2013 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2014 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2015 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002016 CXXRecordDecl *FieldClassDecl
2017 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002018
2019 // Even though union members never have non-trivial default
2020 // constructions in C++03, we still build member initializers for aggregate
2021 // record types which can be union members, and C++0x allows non-trivial
2022 // default constructors for union members, so we ensure that only one
2023 // member is initialized for these.
2024 if (FieldClassDecl->isUnion()) {
2025 // First check for an explicit initializer for one field.
2026 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2027 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002028 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002029 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002030
2031 // Once we've initialized a field of an anonymous union, the union
2032 // field in the class is also initialized, so exit immediately.
2033 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002034 } else if ((*FA)->isAnonymousStructOrUnion()) {
2035 if (CollectFieldInitializer(Info, Top, *FA))
2036 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002037 }
2038 }
2039
2040 // Fallthrough and construct a default initializer for the union as
2041 // a whole, which can call its default constructor if such a thing exists
2042 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2043 // behavior going forward with C++0x, when anonymous unions there are
2044 // finalized, we should revisit this.
2045 } else {
2046 // For structs, we simply descend through to initialize all members where
2047 // necessary.
2048 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2049 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2050 if (CollectFieldInitializer(Info, Top, *FA))
2051 return true;
2052 }
2053 }
John McCallf1860e52010-05-20 23:23:51 +00002054 }
2055
2056 // Don't try to build an implicit initializer if there were semantic
2057 // errors in any of the initializers (and therefore we might be
2058 // missing some that the user actually wrote).
2059 if (Info.AnyErrorsInInits)
2060 return false;
2061
Sean Huntcbb67482011-01-08 20:30:50 +00002062 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002063 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2064 return true;
John McCallf1860e52010-05-20 23:23:51 +00002065
Francois Pichet00eb3f92010-12-04 09:14:42 +00002066 if (Init)
2067 Info.AllToInit.push_back(Init);
2068
John McCallf1860e52010-05-20 23:23:51 +00002069 return false;
2070}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002071
Eli Friedman80c30da2009-11-09 19:20:36 +00002072bool
Sean Huntcbb67482011-01-08 20:30:50 +00002073Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2074 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002075 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002076 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002077 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002078 // Just store the initializers as written, they will be checked during
2079 // instantiation.
2080 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002081 Constructor->setNumCtorInitializers(NumInitializers);
2082 CXXCtorInitializer **baseOrMemberInitializers =
2083 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002084 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002085 NumInitializers * sizeof(CXXCtorInitializer*));
2086 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002087 }
2088
2089 return false;
2090 }
2091
John McCallf1860e52010-05-20 23:23:51 +00002092 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002093
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002094 // We need to build the initializer AST according to order of construction
2095 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002096 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002097 if (!ClassDecl)
2098 return true;
2099
Eli Friedman80c30da2009-11-09 19:20:36 +00002100 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002102 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002103 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002104
2105 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002106 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002107 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002108 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002109 }
2110
Anders Carlsson711f34a2010-04-21 19:52:01 +00002111 // Keep track of the direct virtual bases.
2112 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2113 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2114 E = ClassDecl->bases_end(); I != E; ++I) {
2115 if (I->isVirtual())
2116 DirectVBases.insert(I);
2117 }
2118
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002119 // Push virtual bases before others.
2120 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2121 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2122
Sean Huntcbb67482011-01-08 20:30:50 +00002123 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002124 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2125 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002126 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002127 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002128 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002129 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002130 VBase, IsInheritedVirtualBase,
2131 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002132 HadError = true;
2133 continue;
2134 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002135
John McCallf1860e52010-05-20 23:23:51 +00002136 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002137 }
2138 }
Mike Stump1eb44332009-09-09 15:08:12 +00002139
John McCallf1860e52010-05-20 23:23:51 +00002140 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002141 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2142 E = ClassDecl->bases_end(); Base != E; ++Base) {
2143 // Virtuals are in the virtual base list and already constructed.
2144 if (Base->isVirtual())
2145 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Sean Huntcbb67482011-01-08 20:30:50 +00002147 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002148 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2149 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002150 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002151 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002152 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002153 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002154 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002155 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002156 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002157 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002158
John McCallf1860e52010-05-20 23:23:51 +00002159 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002160 }
2161 }
Mike Stump1eb44332009-09-09 15:08:12 +00002162
John McCallf1860e52010-05-20 23:23:51 +00002163 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002164 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002165 E = ClassDecl->field_end(); Field != E; ++Field) {
2166 if ((*Field)->getType()->isIncompleteArrayType()) {
2167 assert(ClassDecl->hasFlexibleArrayMember() &&
2168 "Incomplete array type is not valid");
2169 continue;
2170 }
John McCallf1860e52010-05-20 23:23:51 +00002171 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002172 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002173 }
Mike Stump1eb44332009-09-09 15:08:12 +00002174
John McCallf1860e52010-05-20 23:23:51 +00002175 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002176 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002177 Constructor->setNumCtorInitializers(NumInitializers);
2178 CXXCtorInitializer **baseOrMemberInitializers =
2179 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002180 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002181 NumInitializers * sizeof(CXXCtorInitializer*));
2182 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002183
John McCallef027fe2010-03-16 21:39:52 +00002184 // Constructors implicitly reference the base and member
2185 // destructors.
2186 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2187 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002188 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002189
2190 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002191}
2192
Eli Friedman6347f422009-07-21 19:28:10 +00002193static void *GetKeyForTopLevelField(FieldDecl *Field) {
2194 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002195 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002196 if (RT->getDecl()->isAnonymousStructOrUnion())
2197 return static_cast<void *>(RT->getDecl());
2198 }
2199 return static_cast<void *>(Field);
2200}
2201
Anders Carlssonea356fb2010-04-02 05:42:15 +00002202static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002203 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002204}
2205
Anders Carlssonea356fb2010-04-02 05:42:15 +00002206static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002207 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002208 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002209 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002210
Eli Friedman6347f422009-07-21 19:28:10 +00002211 // For fields injected into the class via declaration of an anonymous union,
2212 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002213 FieldDecl *Field = Member->getAnyMember();
2214
John McCall3c3ccdb2010-04-10 09:28:51 +00002215 // If the field is a member of an anonymous struct or union, our key
2216 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002217 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002218 if (RD->isAnonymousStructOrUnion()) {
2219 while (true) {
2220 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2221 if (Parent->isAnonymousStructOrUnion())
2222 RD = Parent;
2223 else
2224 break;
2225 }
2226
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002227 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002228 }
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002230 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002231}
2232
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002233static void
2234DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002235 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002236 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002237 unsigned NumInits) {
2238 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002239 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002241 // Don't check initializers order unless the warning is enabled at the
2242 // location of at least one initializer.
2243 bool ShouldCheckOrder = false;
2244 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002245 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002246 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2247 Init->getSourceLocation())
2248 != Diagnostic::Ignored) {
2249 ShouldCheckOrder = true;
2250 break;
2251 }
2252 }
2253 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002254 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002255
John McCalld6ca8da2010-04-10 07:37:23 +00002256 // Build the list of bases and members in the order that they'll
2257 // actually be initialized. The explicit initializers should be in
2258 // this same order but may be missing things.
2259 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Anders Carlsson071d6102010-04-02 03:38:04 +00002261 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2262
John McCalld6ca8da2010-04-10 07:37:23 +00002263 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002264 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002265 ClassDecl->vbases_begin(),
2266 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002267 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002268
John McCalld6ca8da2010-04-10 07:37:23 +00002269 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002270 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002271 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002272 if (Base->isVirtual())
2273 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002274 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002275 }
Mike Stump1eb44332009-09-09 15:08:12 +00002276
John McCalld6ca8da2010-04-10 07:37:23 +00002277 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002278 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2279 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002280 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002281
John McCalld6ca8da2010-04-10 07:37:23 +00002282 unsigned NumIdealInits = IdealInitKeys.size();
2283 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002284
Sean Huntcbb67482011-01-08 20:30:50 +00002285 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002286 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002287 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002288 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002289
2290 // Scan forward to try to find this initializer in the idealized
2291 // initializers list.
2292 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2293 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002294 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002295
2296 // If we didn't find this initializer, it must be because we
2297 // scanned past it on a previous iteration. That can only
2298 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002299 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002300 Sema::SemaDiagnosticBuilder D =
2301 SemaRef.Diag(PrevInit->getSourceLocation(),
2302 diag::warn_initializer_out_of_order);
2303
Francois Pichet00eb3f92010-12-04 09:14:42 +00002304 if (PrevInit->isAnyMemberInitializer())
2305 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002306 else
2307 D << 1 << PrevInit->getBaseClassInfo()->getType();
2308
Francois Pichet00eb3f92010-12-04 09:14:42 +00002309 if (Init->isAnyMemberInitializer())
2310 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002311 else
2312 D << 1 << Init->getBaseClassInfo()->getType();
2313
2314 // Move back to the initializer's location in the ideal list.
2315 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2316 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002317 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002318
2319 assert(IdealIndex != NumIdealInits &&
2320 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002321 }
John McCalld6ca8da2010-04-10 07:37:23 +00002322
2323 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002324 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002325}
2326
John McCall3c3ccdb2010-04-10 09:28:51 +00002327namespace {
2328bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002329 CXXCtorInitializer *Init,
2330 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002331 if (!PrevInit) {
2332 PrevInit = Init;
2333 return false;
2334 }
2335
2336 if (FieldDecl *Field = Init->getMember())
2337 S.Diag(Init->getSourceLocation(),
2338 diag::err_multiple_mem_initialization)
2339 << Field->getDeclName()
2340 << Init->getSourceRange();
2341 else {
John McCallf4c73712011-01-19 06:33:43 +00002342 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002343 assert(BaseClass && "neither field nor base");
2344 S.Diag(Init->getSourceLocation(),
2345 diag::err_multiple_base_initialization)
2346 << QualType(BaseClass, 0)
2347 << Init->getSourceRange();
2348 }
2349 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2350 << 0 << PrevInit->getSourceRange();
2351
2352 return true;
2353}
2354
Sean Huntcbb67482011-01-08 20:30:50 +00002355typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002356typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2357
2358bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002359 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002360 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002361 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002362 RecordDecl *Parent = Field->getParent();
2363 if (!Parent->isAnonymousStructOrUnion())
2364 return false;
2365
2366 NamedDecl *Child = Field;
2367 do {
2368 if (Parent->isUnion()) {
2369 UnionEntry &En = Unions[Parent];
2370 if (En.first && En.first != Child) {
2371 S.Diag(Init->getSourceLocation(),
2372 diag::err_multiple_mem_union_initialization)
2373 << Field->getDeclName()
2374 << Init->getSourceRange();
2375 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2376 << 0 << En.second->getSourceRange();
2377 return true;
2378 } else if (!En.first) {
2379 En.first = Child;
2380 En.second = Init;
2381 }
2382 }
2383
2384 Child = Parent;
2385 Parent = cast<RecordDecl>(Parent->getDeclContext());
2386 } while (Parent->isAnonymousStructOrUnion());
2387
2388 return false;
2389}
2390}
2391
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002392/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002393void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002394 SourceLocation ColonLoc,
2395 MemInitTy **meminits, unsigned NumMemInits,
2396 bool AnyErrors) {
2397 if (!ConstructorDecl)
2398 return;
2399
2400 AdjustDeclIfTemplate(ConstructorDecl);
2401
2402 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002403 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002404
2405 if (!Constructor) {
2406 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2407 return;
2408 }
2409
Sean Huntcbb67482011-01-08 20:30:50 +00002410 CXXCtorInitializer **MemInits =
2411 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002412
2413 // Mapping for the duplicate initializers check.
2414 // For member initializers, this is keyed with a FieldDecl*.
2415 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002416 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002417
2418 // Mapping for the inconsistent anonymous-union initializers check.
2419 RedundantUnionMap MemberUnions;
2420
Anders Carlssonea356fb2010-04-02 05:42:15 +00002421 bool HadError = false;
2422 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002423 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002424
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002425 // Set the source order index.
2426 Init->setSourceOrder(i);
2427
Francois Pichet00eb3f92010-12-04 09:14:42 +00002428 if (Init->isAnyMemberInitializer()) {
2429 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002430 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2431 CheckRedundantUnionInit(*this, Init, MemberUnions))
2432 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002433 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002434 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2435 if (CheckRedundantInit(*this, Init, Members[Key]))
2436 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002437 } else {
2438 assert(Init->isDelegatingInitializer());
2439 // This must be the only initializer
2440 if (i != 0 || NumMemInits > 1) {
2441 Diag(MemInits[0]->getSourceLocation(),
2442 diag::err_delegating_initializer_alone)
2443 << MemInits[0]->getSourceRange();
2444 HadError = true;
2445 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002446 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002447 }
2448
Anders Carlssonea356fb2010-04-02 05:42:15 +00002449 if (HadError)
2450 return;
2451
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002452 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002453
Sean Huntcbb67482011-01-08 20:30:50 +00002454 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002455}
2456
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002457void
John McCallef027fe2010-03-16 21:39:52 +00002458Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2459 CXXRecordDecl *ClassDecl) {
2460 // Ignore dependent contexts.
2461 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002462 return;
John McCall58e6f342010-03-16 05:22:47 +00002463
2464 // FIXME: all the access-control diagnostics are positioned on the
2465 // field/base declaration. That's probably good; that said, the
2466 // user might reasonably want to know why the destructor is being
2467 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002468
Anders Carlsson9f853df2009-11-17 04:44:12 +00002469 // Non-static data members.
2470 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2471 E = ClassDecl->field_end(); I != E; ++I) {
2472 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002473 if (Field->isInvalidDecl())
2474 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002475 QualType FieldType = Context.getBaseElementType(Field->getType());
2476
2477 const RecordType* RT = FieldType->getAs<RecordType>();
2478 if (!RT)
2479 continue;
2480
2481 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002482 if (FieldClassDecl->isInvalidDecl())
2483 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002484 if (FieldClassDecl->hasTrivialDestructor())
2485 continue;
2486
Douglas Gregordb89f282010-07-01 22:47:18 +00002487 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002488 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002489 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002490 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002491 << Field->getDeclName()
2492 << FieldType);
2493
John McCallef027fe2010-03-16 21:39:52 +00002494 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002495 }
2496
John McCall58e6f342010-03-16 05:22:47 +00002497 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2498
Anders Carlsson9f853df2009-11-17 04:44:12 +00002499 // Bases.
2500 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2501 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002502 // Bases are always records in a well-formed non-dependent class.
2503 const RecordType *RT = Base->getType()->getAs<RecordType>();
2504
2505 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002506 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002507 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002508
John McCall58e6f342010-03-16 05:22:47 +00002509 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002510 // If our base class is invalid, we probably can't get its dtor anyway.
2511 if (BaseClassDecl->isInvalidDecl())
2512 continue;
2513 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002514 if (BaseClassDecl->hasTrivialDestructor())
2515 continue;
John McCall58e6f342010-03-16 05:22:47 +00002516
Douglas Gregordb89f282010-07-01 22:47:18 +00002517 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002518 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002519
2520 // FIXME: caret should be on the start of the class name
2521 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002522 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002523 << Base->getType()
2524 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002525
John McCallef027fe2010-03-16 21:39:52 +00002526 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002527 }
2528
2529 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002530 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2531 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002532
2533 // Bases are always records in a well-formed non-dependent class.
2534 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2535
2536 // Ignore direct virtual bases.
2537 if (DirectVirtualBases.count(RT))
2538 continue;
2539
John McCall58e6f342010-03-16 05:22:47 +00002540 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002541 // If our base class is invalid, we probably can't get its dtor anyway.
2542 if (BaseClassDecl->isInvalidDecl())
2543 continue;
2544 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002545 if (BaseClassDecl->hasTrivialDestructor())
2546 continue;
John McCall58e6f342010-03-16 05:22:47 +00002547
Douglas Gregordb89f282010-07-01 22:47:18 +00002548 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002549 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002550 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002551 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002552 << VBase->getType());
2553
John McCallef027fe2010-03-16 21:39:52 +00002554 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002555 }
2556}
2557
John McCalld226f652010-08-21 09:40:31 +00002558void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002559 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002560 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Mike Stump1eb44332009-09-09 15:08:12 +00002562 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002563 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002564 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002565}
2566
Mike Stump1eb44332009-09-09 15:08:12 +00002567bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002568 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002569 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002570 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002571 else
John McCall94c3b562010-08-18 09:41:07 +00002572 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002573}
2574
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002575bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002576 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002577 if (!getLangOptions().CPlusPlus)
2578 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Anders Carlsson11f21a02009-03-23 19:10:31 +00002580 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002581 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Ted Kremenek6217b802009-07-29 21:53:49 +00002583 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002584 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002585 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002586 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002588 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002589 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002590 }
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Ted Kremenek6217b802009-07-29 21:53:49 +00002592 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002593 if (!RT)
2594 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002595
John McCall86ff3082010-02-04 22:26:26 +00002596 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002597
John McCall94c3b562010-08-18 09:41:07 +00002598 // We can't answer whether something is abstract until it has a
2599 // definition. If it's currently being defined, we'll walk back
2600 // over all the declarations when we have a full definition.
2601 const CXXRecordDecl *Def = RD->getDefinition();
2602 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002603 return false;
2604
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002605 if (!RD->isAbstract())
2606 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002608 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002609 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002610
John McCall94c3b562010-08-18 09:41:07 +00002611 return true;
2612}
2613
2614void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2615 // Check if we've already emitted the list of pure virtual functions
2616 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002617 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002618 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002620 CXXFinalOverriderMap FinalOverriders;
2621 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002623 // Keep a set of seen pure methods so we won't diagnose the same method
2624 // more than once.
2625 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2626
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002627 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2628 MEnd = FinalOverriders.end();
2629 M != MEnd;
2630 ++M) {
2631 for (OverridingMethods::iterator SO = M->second.begin(),
2632 SOEnd = M->second.end();
2633 SO != SOEnd; ++SO) {
2634 // C++ [class.abstract]p4:
2635 // A class is abstract if it contains or inherits at least one
2636 // pure virtual function for which the final overrider is pure
2637 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002639 //
2640 if (SO->second.size() != 1)
2641 continue;
2642
2643 if (!SO->second.front().Method->isPure())
2644 continue;
2645
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002646 if (!SeenPureMethods.insert(SO->second.front().Method))
2647 continue;
2648
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002649 Diag(SO->second.front().Method->getLocation(),
2650 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002651 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002652 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002653 }
2654
2655 if (!PureVirtualClassDiagSet)
2656 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2657 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002658}
2659
Anders Carlsson8211eff2009-03-24 01:19:16 +00002660namespace {
John McCall94c3b562010-08-18 09:41:07 +00002661struct AbstractUsageInfo {
2662 Sema &S;
2663 CXXRecordDecl *Record;
2664 CanQualType AbstractType;
2665 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002666
John McCall94c3b562010-08-18 09:41:07 +00002667 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2668 : S(S), Record(Record),
2669 AbstractType(S.Context.getCanonicalType(
2670 S.Context.getTypeDeclType(Record))),
2671 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002672
John McCall94c3b562010-08-18 09:41:07 +00002673 void DiagnoseAbstractType() {
2674 if (Invalid) return;
2675 S.DiagnoseAbstractType(Record);
2676 Invalid = true;
2677 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002678
John McCall94c3b562010-08-18 09:41:07 +00002679 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2680};
2681
2682struct CheckAbstractUsage {
2683 AbstractUsageInfo &Info;
2684 const NamedDecl *Ctx;
2685
2686 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2687 : Info(Info), Ctx(Ctx) {}
2688
2689 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2690 switch (TL.getTypeLocClass()) {
2691#define ABSTRACT_TYPELOC(CLASS, PARENT)
2692#define TYPELOC(CLASS, PARENT) \
2693 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2694#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002695 }
John McCall94c3b562010-08-18 09:41:07 +00002696 }
Mike Stump1eb44332009-09-09 15:08:12 +00002697
John McCall94c3b562010-08-18 09:41:07 +00002698 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2699 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2700 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002701 if (!TL.getArg(I))
2702 continue;
2703
John McCall94c3b562010-08-18 09:41:07 +00002704 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2705 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002706 }
John McCall94c3b562010-08-18 09:41:07 +00002707 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002708
John McCall94c3b562010-08-18 09:41:07 +00002709 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2710 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2711 }
Mike Stump1eb44332009-09-09 15:08:12 +00002712
John McCall94c3b562010-08-18 09:41:07 +00002713 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2714 // Visit the type parameters from a permissive context.
2715 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2716 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2717 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2718 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2719 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2720 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002721 }
John McCall94c3b562010-08-18 09:41:07 +00002722 }
Mike Stump1eb44332009-09-09 15:08:12 +00002723
John McCall94c3b562010-08-18 09:41:07 +00002724 // Visit pointee types from a permissive context.
2725#define CheckPolymorphic(Type) \
2726 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2727 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2728 }
2729 CheckPolymorphic(PointerTypeLoc)
2730 CheckPolymorphic(ReferenceTypeLoc)
2731 CheckPolymorphic(MemberPointerTypeLoc)
2732 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002733
John McCall94c3b562010-08-18 09:41:07 +00002734 /// Handle all the types we haven't given a more specific
2735 /// implementation for above.
2736 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2737 // Every other kind of type that we haven't called out already
2738 // that has an inner type is either (1) sugar or (2) contains that
2739 // inner type in some way as a subobject.
2740 if (TypeLoc Next = TL.getNextTypeLoc())
2741 return Visit(Next, Sel);
2742
2743 // If there's no inner type and we're in a permissive context,
2744 // don't diagnose.
2745 if (Sel == Sema::AbstractNone) return;
2746
2747 // Check whether the type matches the abstract type.
2748 QualType T = TL.getType();
2749 if (T->isArrayType()) {
2750 Sel = Sema::AbstractArrayType;
2751 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002752 }
John McCall94c3b562010-08-18 09:41:07 +00002753 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2754 if (CT != Info.AbstractType) return;
2755
2756 // It matched; do some magic.
2757 if (Sel == Sema::AbstractArrayType) {
2758 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2759 << T << TL.getSourceRange();
2760 } else {
2761 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2762 << Sel << T << TL.getSourceRange();
2763 }
2764 Info.DiagnoseAbstractType();
2765 }
2766};
2767
2768void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2769 Sema::AbstractDiagSelID Sel) {
2770 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2771}
2772
2773}
2774
2775/// Check for invalid uses of an abstract type in a method declaration.
2776static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2777 CXXMethodDecl *MD) {
2778 // No need to do the check on definitions, which require that
2779 // the return/param types be complete.
2780 if (MD->isThisDeclarationADefinition())
2781 return;
2782
2783 // For safety's sake, just ignore it if we don't have type source
2784 // information. This should never happen for non-implicit methods,
2785 // but...
2786 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2787 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2788}
2789
2790/// Check for invalid uses of an abstract type within a class definition.
2791static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2792 CXXRecordDecl *RD) {
2793 for (CXXRecordDecl::decl_iterator
2794 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2795 Decl *D = *I;
2796 if (D->isImplicit()) continue;
2797
2798 // Methods and method templates.
2799 if (isa<CXXMethodDecl>(D)) {
2800 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2801 } else if (isa<FunctionTemplateDecl>(D)) {
2802 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2803 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2804
2805 // Fields and static variables.
2806 } else if (isa<FieldDecl>(D)) {
2807 FieldDecl *FD = cast<FieldDecl>(D);
2808 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2809 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2810 } else if (isa<VarDecl>(D)) {
2811 VarDecl *VD = cast<VarDecl>(D);
2812 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2813 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2814
2815 // Nested classes and class templates.
2816 } else if (isa<CXXRecordDecl>(D)) {
2817 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2818 } else if (isa<ClassTemplateDecl>(D)) {
2819 CheckAbstractClassUsage(Info,
2820 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2821 }
2822 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002823}
2824
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002825/// \brief Perform semantic checks on a class definition that has been
2826/// completing, introducing implicitly-declared members, checking for
2827/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002828void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002829 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002830 return;
2831
John McCall94c3b562010-08-18 09:41:07 +00002832 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2833 AbstractUsageInfo Info(*this, Record);
2834 CheckAbstractClassUsage(Info, Record);
2835 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002836
2837 // If this is not an aggregate type and has no user-declared constructor,
2838 // complain about any non-static data members of reference or const scalar
2839 // type, since they will never get initializers.
2840 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2841 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2842 bool Complained = false;
2843 for (RecordDecl::field_iterator F = Record->field_begin(),
2844 FEnd = Record->field_end();
2845 F != FEnd; ++F) {
2846 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002847 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002848 if (!Complained) {
2849 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2850 << Record->getTagKind() << Record;
2851 Complained = true;
2852 }
2853
2854 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2855 << F->getType()->isReferenceType()
2856 << F->getDeclName();
2857 }
2858 }
2859 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002860
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002861 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002862 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002863
2864 if (Record->getIdentifier()) {
2865 // C++ [class.mem]p13:
2866 // If T is the name of a class, then each of the following shall have a
2867 // name different from T:
2868 // - every member of every anonymous union that is a member of class T.
2869 //
2870 // C++ [class.mem]p14:
2871 // In addition, if class T has a user-declared constructor (12.1), every
2872 // non-static data member of class T shall have a name different from T.
2873 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002874 R.first != R.second; ++R.first) {
2875 NamedDecl *D = *R.first;
2876 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2877 isa<IndirectFieldDecl>(D)) {
2878 Diag(D->getLocation(), diag::err_member_name_of_class)
2879 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002880 break;
2881 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002882 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002883 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002884
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002885 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002886 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002887 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002888 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002889 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2890 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2891 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002892
2893 // See if a method overloads virtual methods in a base
2894 /// class without overriding any.
2895 if (!Record->isDependentType()) {
2896 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2897 MEnd = Record->method_end();
2898 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002899 if (!(*M)->isStatic())
2900 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002901 }
2902 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002903
2904 // Declare inherited constructors. We do this eagerly here because:
2905 // - The standard requires an eager diagnostic for conflicting inherited
2906 // constructors from different classes.
2907 // - The lazy declaration of the other implicit constructors is so as to not
2908 // waste space and performance on classes that are not meant to be
2909 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2910 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002911 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002912}
2913
2914/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00002915namespace {
2916 struct FindHiddenVirtualMethodData {
2917 Sema *S;
2918 CXXMethodDecl *Method;
2919 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2920 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2921 };
2922}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002923
2924/// \brief Member lookup function that determines whether a given C++
2925/// method overloads virtual methods in a base class without overriding any,
2926/// to be used with CXXRecordDecl::lookupInBases().
2927static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2928 CXXBasePath &Path,
2929 void *UserData) {
2930 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2931
2932 FindHiddenVirtualMethodData &Data
2933 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2934
2935 DeclarationName Name = Data.Method->getDeclName();
2936 assert(Name.getNameKind() == DeclarationName::Identifier);
2937
2938 bool foundSameNameMethod = false;
2939 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2940 for (Path.Decls = BaseRecord->lookup(Name);
2941 Path.Decls.first != Path.Decls.second;
2942 ++Path.Decls.first) {
2943 NamedDecl *D = *Path.Decls.first;
2944 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002945 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002946 foundSameNameMethod = true;
2947 // Interested only in hidden virtual methods.
2948 if (!MD->isVirtual())
2949 continue;
2950 // If the method we are checking overrides a method from its base
2951 // don't warn about the other overloaded methods.
2952 if (!Data.S->IsOverload(Data.Method, MD, false))
2953 return true;
2954 // Collect the overload only if its hidden.
2955 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2956 overloadedMethods.push_back(MD);
2957 }
2958 }
2959
2960 if (foundSameNameMethod)
2961 Data.OverloadedMethods.append(overloadedMethods.begin(),
2962 overloadedMethods.end());
2963 return foundSameNameMethod;
2964}
2965
2966/// \brief See if a method overloads virtual methods in a base class without
2967/// overriding any.
2968void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2969 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2970 MD->getLocation()) == Diagnostic::Ignored)
2971 return;
2972 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2973 return;
2974
2975 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2976 /*bool RecordPaths=*/false,
2977 /*bool DetectVirtual=*/false);
2978 FindHiddenVirtualMethodData Data;
2979 Data.Method = MD;
2980 Data.S = this;
2981
2982 // Keep the base methods that were overriden or introduced in the subclass
2983 // by 'using' in a set. A base method not in this set is hidden.
2984 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2985 res.first != res.second; ++res.first) {
2986 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2987 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2988 E = MD->end_overridden_methods();
2989 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002990 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002991 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2992 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002993 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002994 }
2995
2996 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2997 !Data.OverloadedMethods.empty()) {
2998 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2999 << MD << (Data.OverloadedMethods.size() > 1);
3000
3001 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3002 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3003 Diag(overloadedMD->getLocation(),
3004 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3005 }
3006 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003007}
3008
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003009void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00003010 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003011 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003012 SourceLocation RBrac,
3013 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003014 if (!TagDecl)
3015 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Douglas Gregor42af25f2009-05-11 19:58:34 +00003017 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003018
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003019 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00003020 // strict aliasing violation!
3021 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003022 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00003023
Douglas Gregor23c94db2010-07-02 17:43:08 +00003024 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00003025 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003026}
3027
Douglas Gregord92ec472010-07-01 05:10:53 +00003028namespace {
3029 /// \brief Helper class that collects exception specifications for
3030 /// implicitly-declared special member functions.
3031 class ImplicitExceptionSpecification {
3032 ASTContext &Context;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003033 // We order exception specifications thus:
3034 // noexcept is the most restrictive, but is only used in C++0x.
3035 // throw() comes next.
3036 // Then a throw(collected exceptions)
3037 // Finally no specification.
3038 // throw(...) is used instead if any called function uses it.
3039 ExceptionSpecificationType ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003040 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3041 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003042
3043 void ClearExceptions() {
3044 ExceptionsSeen.clear();
3045 Exceptions.clear();
3046 }
3047
Douglas Gregord92ec472010-07-01 05:10:53 +00003048 public:
3049 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redl60618fa2011-03-12 11:50:43 +00003050 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3051 if (!Context.getLangOptions().CPlusPlus0x)
3052 ComputedEST = EST_DynamicNone;
Douglas Gregord92ec472010-07-01 05:10:53 +00003053 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003054
3055 /// \brief Get the computed exception specification type.
3056 ExceptionSpecificationType getExceptionSpecType() const {
3057 assert(ComputedEST != EST_ComputedNoexcept &&
3058 "noexcept(expr) should not be a possible result");
3059 return ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003060 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003061
Douglas Gregord92ec472010-07-01 05:10:53 +00003062 /// \brief The number of exceptions in the exception specification.
3063 unsigned size() const { return Exceptions.size(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003064
Douglas Gregord92ec472010-07-01 05:10:53 +00003065 /// \brief The set of exceptions in the exception specification.
3066 const QualType *data() const { return Exceptions.data(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003067
3068 /// \brief Integrate another called method into the collected data.
Douglas Gregord92ec472010-07-01 05:10:53 +00003069 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00003070 // If we have an MSAny spec already, don't bother.
3071 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregord92ec472010-07-01 05:10:53 +00003072 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003073
Douglas Gregord92ec472010-07-01 05:10:53 +00003074 const FunctionProtoType *Proto
3075 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003076
3077 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3078
Douglas Gregord92ec472010-07-01 05:10:53 +00003079 // If this function can throw any exceptions, make a note of that.
Sebastian Redl60618fa2011-03-12 11:50:43 +00003080 if (EST == EST_MSAny || EST == EST_None) {
3081 ClearExceptions();
3082 ComputedEST = EST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003083 return;
3084 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003085
3086 // If this function has a basic noexcept, it doesn't affect the outcome.
3087 if (EST == EST_BasicNoexcept)
3088 return;
3089
3090 // If we have a throw-all spec at this point, ignore the function.
3091 if (ComputedEST == EST_None)
3092 return;
3093
3094 // If we're still at noexcept(true) and there's a nothrow() callee,
3095 // change to that specification.
3096 if (EST == EST_DynamicNone) {
3097 if (ComputedEST == EST_BasicNoexcept)
3098 ComputedEST = EST_DynamicNone;
3099 return;
3100 }
3101
3102 // Check out noexcept specs.
3103 if (EST == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003104 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +00003105 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3106 "Must have noexcept result for EST_ComputedNoexcept.");
3107 assert(NR != FunctionProtoType::NR_Dependent &&
3108 "Should not generate implicit declarations for dependent cases, "
3109 "and don't know how to handle them anyway.");
3110
3111 // noexcept(false) -> no spec on the new function
3112 if (NR == FunctionProtoType::NR_Throw) {
3113 ClearExceptions();
3114 ComputedEST = EST_None;
3115 }
3116 // noexcept(true) won't change anything either.
3117 return;
3118 }
3119
3120 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3121 assert(ComputedEST != EST_None &&
3122 "Shouldn't collect exceptions when throw-all is guaranteed.");
3123 ComputedEST = EST_Dynamic;
Douglas Gregord92ec472010-07-01 05:10:53 +00003124 // Record the exceptions in this function's exception specification.
3125 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3126 EEnd = Proto->exception_end();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003127 E != EEnd; ++E)
Douglas Gregord92ec472010-07-01 05:10:53 +00003128 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3129 Exceptions.push_back(*E);
3130 }
3131 };
3132}
3133
3134
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003135/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3136/// special functions, such as the default constructor, copy
3137/// constructor, or destructor, to the given C++ class (C++
3138/// [special]p1). This routine can only be executed just before the
3139/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003140void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00003141 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00003142 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003143
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00003144 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00003145 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003146
Douglas Gregora376d102010-07-02 21:50:04 +00003147 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3148 ++ASTContext::NumImplicitCopyAssignmentOperators;
3149
3150 // If we have a dynamic class, then the copy assignment operator may be
3151 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3152 // it shows up in the right place in the vtable and that we diagnose
3153 // problems with the implicit exception specification.
3154 if (ClassDecl->isDynamicClass())
3155 DeclareImplicitCopyAssignment(ClassDecl);
3156 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003157
Douglas Gregor4923aa22010-07-02 20:37:36 +00003158 if (!ClassDecl->hasUserDeclaredDestructor()) {
3159 ++ASTContext::NumImplicitDestructors;
3160
3161 // If we have a dynamic class, then the destructor may be virtual, so we
3162 // have to declare the destructor immediately. This ensures that, e.g., it
3163 // shows up in the right place in the vtable and that we diagnose problems
3164 // with the implicit exception specification.
3165 if (ClassDecl->isDynamicClass())
3166 DeclareImplicitDestructor(ClassDecl);
3167 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003168}
3169
Francois Pichet8387e2a2011-04-22 22:18:13 +00003170void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3171 if (!D)
3172 return;
3173
3174 int NumParamList = D->getNumTemplateParameterLists();
3175 for (int i = 0; i < NumParamList; i++) {
3176 TemplateParameterList* Params = D->getTemplateParameterList(i);
3177 for (TemplateParameterList::iterator Param = Params->begin(),
3178 ParamEnd = Params->end();
3179 Param != ParamEnd; ++Param) {
3180 NamedDecl *Named = cast<NamedDecl>(*Param);
3181 if (Named->getDeclName()) {
3182 S->AddDecl(Named);
3183 IdResolver.AddDecl(Named);
3184 }
3185 }
3186 }
3187}
3188
John McCalld226f652010-08-21 09:40:31 +00003189void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003190 if (!D)
3191 return;
3192
3193 TemplateParameterList *Params = 0;
3194 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3195 Params = Template->getTemplateParameters();
3196 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3197 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3198 Params = PartialSpec->getTemplateParameters();
3199 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003200 return;
3201
Douglas Gregor6569d682009-05-27 23:11:45 +00003202 for (TemplateParameterList::iterator Param = Params->begin(),
3203 ParamEnd = Params->end();
3204 Param != ParamEnd; ++Param) {
3205 NamedDecl *Named = cast<NamedDecl>(*Param);
3206 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003207 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003208 IdResolver.AddDecl(Named);
3209 }
3210 }
3211}
3212
John McCalld226f652010-08-21 09:40:31 +00003213void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003214 if (!RecordD) return;
3215 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003216 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003217 PushDeclContext(S, Record);
3218}
3219
John McCalld226f652010-08-21 09:40:31 +00003220void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003221 if (!RecordD) return;
3222 PopDeclContext();
3223}
3224
Douglas Gregor72b505b2008-12-16 21:30:33 +00003225/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3226/// parsing a top-level (non-nested) C++ class, and we are now
3227/// parsing those parts of the given Method declaration that could
3228/// not be parsed earlier (C++ [class.mem]p2), such as default
3229/// arguments. This action should enter the scope of the given
3230/// Method declaration as if we had just parsed the qualified method
3231/// name. However, it should not bring the parameters into scope;
3232/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003233void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003234}
3235
3236/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3237/// C++ method declaration. We're (re-)introducing the given
3238/// function parameter into scope for use in parsing later parts of
3239/// the method declaration. For example, we could see an
3240/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003241void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003242 if (!ParamD)
3243 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003244
John McCalld226f652010-08-21 09:40:31 +00003245 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003246
3247 // If this parameter has an unparsed default argument, clear it out
3248 // to make way for the parsed default argument.
3249 if (Param->hasUnparsedDefaultArg())
3250 Param->setDefaultArg(0);
3251
John McCalld226f652010-08-21 09:40:31 +00003252 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003253 if (Param->getDeclName())
3254 IdResolver.AddDecl(Param);
3255}
3256
3257/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3258/// processing the delayed method declaration for Method. The method
3259/// declaration is now considered finished. There may be a separate
3260/// ActOnStartOfFunctionDef action later (not necessarily
3261/// immediately!) for this method, if it was also defined inside the
3262/// class body.
John McCalld226f652010-08-21 09:40:31 +00003263void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003264 if (!MethodD)
3265 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003267 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003268
John McCalld226f652010-08-21 09:40:31 +00003269 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003270
3271 // Now that we have our default arguments, check the constructor
3272 // again. It could produce additional diagnostics or affect whether
3273 // the class has implicitly-declared destructors, among other
3274 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003275 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3276 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003277
3278 // Check the default arguments, which we may have added.
3279 if (!Method->isInvalidDecl())
3280 CheckCXXDefaultArguments(Method);
3281}
3282
Douglas Gregor42a552f2008-11-05 20:51:48 +00003283/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003284/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003285/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003286/// emit diagnostics and set the invalid bit to true. In any case, the type
3287/// will be updated to reflect a well-formed type for the constructor and
3288/// returned.
3289QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003290 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003291 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003292
3293 // C++ [class.ctor]p3:
3294 // A constructor shall not be virtual (10.3) or static (9.4). A
3295 // constructor can be invoked for a const, volatile or const
3296 // volatile object. A constructor shall not be declared const,
3297 // volatile, or const volatile (9.3.2).
3298 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003299 if (!D.isInvalidType())
3300 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3301 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3302 << SourceRange(D.getIdentifierLoc());
3303 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003304 }
John McCalld931b082010-08-26 03:08:43 +00003305 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003306 if (!D.isInvalidType())
3307 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3308 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3309 << SourceRange(D.getIdentifierLoc());
3310 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003311 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003312 }
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003314 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003315 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003316 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003317 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3318 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003319 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003320 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3321 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003322 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003323 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3324 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003325 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003326 }
Mike Stump1eb44332009-09-09 15:08:12 +00003327
Douglas Gregorc938c162011-01-26 05:01:58 +00003328 // C++0x [class.ctor]p4:
3329 // A constructor shall not be declared with a ref-qualifier.
3330 if (FTI.hasRefQualifier()) {
3331 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3332 << FTI.RefQualifierIsLValueRef
3333 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3334 D.setInvalidType();
3335 }
3336
Douglas Gregor42a552f2008-11-05 20:51:48 +00003337 // Rebuild the function type "R" without any type qualifiers (in
3338 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003339 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003340 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003341 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3342 return R;
3343
3344 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3345 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003346 EPI.RefQualifier = RQ_None;
3347
Chris Lattner65401802009-04-25 08:28:21 +00003348 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003349 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003350}
3351
Douglas Gregor72b505b2008-12-16 21:30:33 +00003352/// CheckConstructor - Checks a fully-formed constructor for
3353/// well-formedness, issuing any diagnostics required. Returns true if
3354/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003355void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003356 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003357 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3358 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003359 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003360
3361 // C++ [class.copy]p3:
3362 // A declaration of a constructor for a class X is ill-formed if
3363 // its first parameter is of type (optionally cv-qualified) X and
3364 // either there are no other parameters or else all other
3365 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003366 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003367 ((Constructor->getNumParams() == 1) ||
3368 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003369 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3370 Constructor->getTemplateSpecializationKind()
3371 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003372 QualType ParamType = Constructor->getParamDecl(0)->getType();
3373 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3374 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003375 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003376 const char *ConstRef
3377 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3378 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003379 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003380 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003381
3382 // FIXME: Rather that making the constructor invalid, we should endeavor
3383 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003384 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003385 }
3386 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003387}
3388
John McCall15442822010-08-04 01:04:25 +00003389/// CheckDestructor - Checks a fully-formed destructor definition for
3390/// well-formedness, issuing any diagnostics required. Returns true
3391/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003392bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003393 CXXRecordDecl *RD = Destructor->getParent();
3394
3395 if (Destructor->isVirtual()) {
3396 SourceLocation Loc;
3397
3398 if (!Destructor->isImplicit())
3399 Loc = Destructor->getLocation();
3400 else
3401 Loc = RD->getLocation();
3402
3403 // If we have a virtual destructor, look up the deallocation function
3404 FunctionDecl *OperatorDelete = 0;
3405 DeclarationName Name =
3406 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003407 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003408 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003409
3410 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003411
3412 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003413 }
Anders Carlsson37909802009-11-30 21:24:50 +00003414
3415 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003416}
3417
Mike Stump1eb44332009-09-09 15:08:12 +00003418static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003419FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3420 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3421 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003422 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003423}
3424
Douglas Gregor42a552f2008-11-05 20:51:48 +00003425/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3426/// the well-formednes of the destructor declarator @p D with type @p
3427/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003428/// emit diagnostics and set the declarator to invalid. Even if this happens,
3429/// will be updated to reflect a well-formed type for the destructor and
3430/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003431QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003432 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003433 // C++ [class.dtor]p1:
3434 // [...] A typedef-name that names a class is a class-name
3435 // (7.1.3); however, a typedef-name that names a class shall not
3436 // be used as the identifier in the declarator for a destructor
3437 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003438 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00003439 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00003440 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00003441 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003442
3443 // C++ [class.dtor]p2:
3444 // A destructor is used to destroy objects of its class type. A
3445 // destructor takes no parameters, and no return type can be
3446 // specified for it (not even void). The address of a destructor
3447 // shall not be taken. A destructor shall not be static. A
3448 // destructor can be invoked for a const, volatile or const
3449 // volatile object. A destructor shall not be declared const,
3450 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003451 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003452 if (!D.isInvalidType())
3453 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3454 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003455 << SourceRange(D.getIdentifierLoc())
3456 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3457
John McCalld931b082010-08-26 03:08:43 +00003458 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003459 }
Chris Lattner65401802009-04-25 08:28:21 +00003460 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003461 // Destructors don't have return types, but the parser will
3462 // happily parse something like:
3463 //
3464 // class X {
3465 // float ~X();
3466 // };
3467 //
3468 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003469 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3470 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3471 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003472 }
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003474 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003475 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003476 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003477 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3478 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003479 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003480 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3481 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003482 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003483 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3484 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003485 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003486 }
3487
Douglas Gregorc938c162011-01-26 05:01:58 +00003488 // C++0x [class.dtor]p2:
3489 // A destructor shall not be declared with a ref-qualifier.
3490 if (FTI.hasRefQualifier()) {
3491 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3492 << FTI.RefQualifierIsLValueRef
3493 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3494 D.setInvalidType();
3495 }
3496
Douglas Gregor42a552f2008-11-05 20:51:48 +00003497 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003498 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003499 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3500
3501 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003502 FTI.freeArgs();
3503 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003504 }
3505
Mike Stump1eb44332009-09-09 15:08:12 +00003506 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003507 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003508 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003509 D.setInvalidType();
3510 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003511
3512 // Rebuild the function type "R" without any type qualifiers or
3513 // parameters (in case any of the errors above fired) and with
3514 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003515 // types.
John McCalle23cf432010-12-14 08:05:40 +00003516 if (!D.isInvalidType())
3517 return R;
3518
Douglas Gregord92ec472010-07-01 05:10:53 +00003519 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003520 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3521 EPI.Variadic = false;
3522 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003523 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003524 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003525}
3526
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003527/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3528/// well-formednes of the conversion function declarator @p D with
3529/// type @p R. If there are any errors in the declarator, this routine
3530/// will emit diagnostics and return true. Otherwise, it will return
3531/// false. Either way, the type @p R will be updated to reflect a
3532/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003533void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003534 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003535 // C++ [class.conv.fct]p1:
3536 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003537 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003538 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003539 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003540 if (!D.isInvalidType())
3541 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3542 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3543 << SourceRange(D.getIdentifierLoc());
3544 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003545 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003546 }
John McCalla3f81372010-04-13 00:04:31 +00003547
3548 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3549
Chris Lattner6e475012009-04-25 08:35:12 +00003550 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003551 // Conversion functions don't have return types, but the parser will
3552 // happily parse something like:
3553 //
3554 // class X {
3555 // float operator bool();
3556 // };
3557 //
3558 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003559 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3560 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3561 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003562 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003563 }
3564
John McCalla3f81372010-04-13 00:04:31 +00003565 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3566
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003567 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003568 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003569 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3570
3571 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003572 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003573 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003574 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003575 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003576 D.setInvalidType();
3577 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003578
John McCalla3f81372010-04-13 00:04:31 +00003579 // Diagnose "&operator bool()" and other such nonsense. This
3580 // is actually a gcc extension which we don't support.
3581 if (Proto->getResultType() != ConvType) {
3582 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3583 << Proto->getResultType();
3584 D.setInvalidType();
3585 ConvType = Proto->getResultType();
3586 }
3587
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003588 // C++ [class.conv.fct]p4:
3589 // The conversion-type-id shall not represent a function type nor
3590 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003591 if (ConvType->isArrayType()) {
3592 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3593 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003594 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003595 } else if (ConvType->isFunctionType()) {
3596 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3597 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003598 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003599 }
3600
3601 // Rebuild the function type "R" without any parameters (in case any
3602 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003603 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003604 if (D.isInvalidType())
3605 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003606
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003607 // C++0x explicit conversion operators.
3608 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003609 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003610 diag::warn_explicit_conversion_functions)
3611 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003612}
3613
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003614/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3615/// the declaration of the given C++ conversion function. This routine
3616/// is responsible for recording the conversion function in the C++
3617/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003618Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003619 assert(Conversion && "Expected to receive a conversion function declaration");
3620
Douglas Gregor9d350972008-12-12 08:25:50 +00003621 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003622
3623 // Make sure we aren't redeclaring the conversion function.
3624 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003625
3626 // C++ [class.conv.fct]p1:
3627 // [...] A conversion function is never used to convert a
3628 // (possibly cv-qualified) object to the (possibly cv-qualified)
3629 // same object type (or a reference to it), to a (possibly
3630 // cv-qualified) base class of that type (or a reference to it),
3631 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003632 // FIXME: Suppress this warning if the conversion function ends up being a
3633 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003634 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003635 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003636 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003637 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003638 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3639 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003640 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003641 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003642 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3643 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003644 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003645 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003646 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003647 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003648 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003649 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003650 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003651 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003652 }
3653
Douglas Gregore80622f2010-09-29 04:25:11 +00003654 if (FunctionTemplateDecl *ConversionTemplate
3655 = Conversion->getDescribedFunctionTemplate())
3656 return ConversionTemplate;
3657
John McCalld226f652010-08-21 09:40:31 +00003658 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003659}
3660
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003661//===----------------------------------------------------------------------===//
3662// Namespace Handling
3663//===----------------------------------------------------------------------===//
3664
John McCallea318642010-08-26 09:15:37 +00003665
3666
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003667/// ActOnStartNamespaceDef - This is called at the start of a namespace
3668/// definition.
John McCalld226f652010-08-21 09:40:31 +00003669Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003670 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003671 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00003672 SourceLocation IdentLoc,
3673 IdentifierInfo *II,
3674 SourceLocation LBrace,
3675 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003676 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3677 // For anonymous namespace, take the location of the left brace.
3678 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00003679 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003680 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003681 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003682
3683 Scope *DeclRegionScope = NamespcScope->getParent();
3684
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003685 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3686
John McCall90f14502010-12-10 02:59:44 +00003687 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3688 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003689
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003690 if (II) {
3691 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003692 // The identifier in an original-namespace-definition shall not
3693 // have been previously defined in the declarative region in
3694 // which the original-namespace-definition appears. The
3695 // identifier in an original-namespace-definition is the name of
3696 // the namespace. Subsequently in that declarative region, it is
3697 // treated as an original-namespace-name.
3698 //
3699 // Since namespace names are unique in their scope, and we don't
3700 // look through using directives, just
3701 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3702 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Douglas Gregor44b43212008-12-11 16:49:14 +00003704 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3705 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003706 if (Namespc->isInline() != OrigNS->isInline()) {
3707 // inline-ness must match
3708 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3709 << Namespc->isInline();
3710 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3711 Namespc->setInvalidDecl();
3712 // Recover by ignoring the new namespace's inline status.
3713 Namespc->setInline(OrigNS->isInline());
3714 }
3715
Douglas Gregor44b43212008-12-11 16:49:14 +00003716 // Attach this namespace decl to the chain of extended namespace
3717 // definitions.
3718 OrigNS->setNextNamespace(Namespc);
3719 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003720
Mike Stump1eb44332009-09-09 15:08:12 +00003721 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003722 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003723 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003724 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003725 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003726 } else if (PrevDecl) {
3727 // This is an invalid name redefinition.
3728 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3729 << Namespc->getDeclName();
3730 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3731 Namespc->setInvalidDecl();
3732 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003733 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003734 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003735 // This is the first "real" definition of the namespace "std", so update
3736 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003737 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003738 // We had already defined a dummy namespace "std". Link this new
3739 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003740 StdNS->setNextNamespace(Namespc);
3741 StdNS->setLocation(IdentLoc);
3742 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003743 }
3744
3745 // Make our StdNamespace cache point at the first real definition of the
3746 // "std" namespace.
3747 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003748 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003749
3750 PushOnScopeChains(Namespc, DeclRegionScope);
3751 } else {
John McCall9aeed322009-10-01 00:25:31 +00003752 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003753 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003754
3755 // Link the anonymous namespace into its parent.
3756 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003757 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003758 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3759 PrevDecl = TU->getAnonymousNamespace();
3760 TU->setAnonymousNamespace(Namespc);
3761 } else {
3762 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3763 PrevDecl = ND->getAnonymousNamespace();
3764 ND->setAnonymousNamespace(Namespc);
3765 }
3766
3767 // Link the anonymous namespace with its previous declaration.
3768 if (PrevDecl) {
3769 assert(PrevDecl->isAnonymousNamespace());
3770 assert(!PrevDecl->getNextNamespace());
3771 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3772 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003773
3774 if (Namespc->isInline() != PrevDecl->isInline()) {
3775 // inline-ness must match
3776 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3777 << Namespc->isInline();
3778 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3779 Namespc->setInvalidDecl();
3780 // Recover by ignoring the new namespace's inline status.
3781 Namespc->setInline(PrevDecl->isInline());
3782 }
John McCall5fdd7642009-12-16 02:06:49 +00003783 }
John McCall9aeed322009-10-01 00:25:31 +00003784
Douglas Gregora4181472010-03-24 00:46:35 +00003785 CurContext->addDecl(Namespc);
3786
John McCall9aeed322009-10-01 00:25:31 +00003787 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3788 // behaves as if it were replaced by
3789 // namespace unique { /* empty body */ }
3790 // using namespace unique;
3791 // namespace unique { namespace-body }
3792 // where all occurrences of 'unique' in a translation unit are
3793 // replaced by the same identifier and this identifier differs
3794 // from all other identifiers in the entire program.
3795
3796 // We just create the namespace with an empty name and then add an
3797 // implicit using declaration, just like the standard suggests.
3798 //
3799 // CodeGen enforces the "universally unique" aspect by giving all
3800 // declarations semantically contained within an anonymous
3801 // namespace internal linkage.
3802
John McCall5fdd7642009-12-16 02:06:49 +00003803 if (!PrevDecl) {
3804 UsingDirectiveDecl* UD
3805 = UsingDirectiveDecl::Create(Context, CurContext,
3806 /* 'using' */ LBrace,
3807 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00003808 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00003809 /* identifier */ SourceLocation(),
3810 Namespc,
3811 /* Ancestor */ CurContext);
3812 UD->setImplicit();
3813 CurContext->addDecl(UD);
3814 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003815 }
3816
3817 // Although we could have an invalid decl (i.e. the namespace name is a
3818 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003819 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3820 // for the namespace has the declarations that showed up in that particular
3821 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003822 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003823 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003824}
3825
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003826/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3827/// is a namespace alias, returns the namespace it points to.
3828static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3829 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3830 return AD->getNamespace();
3831 return dyn_cast_or_null<NamespaceDecl>(D);
3832}
3833
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003834/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3835/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003836void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003837 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3838 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003839 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003840 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003841 if (Namespc->hasAttr<VisibilityAttr>())
3842 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003843}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003844
John McCall384aff82010-08-25 07:42:41 +00003845CXXRecordDecl *Sema::getStdBadAlloc() const {
3846 return cast_or_null<CXXRecordDecl>(
3847 StdBadAlloc.get(Context.getExternalSource()));
3848}
3849
3850NamespaceDecl *Sema::getStdNamespace() const {
3851 return cast_or_null<NamespaceDecl>(
3852 StdNamespace.get(Context.getExternalSource()));
3853}
3854
Douglas Gregor66992202010-06-29 17:53:46 +00003855/// \brief Retrieve the special "std" namespace, which may require us to
3856/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003857NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003858 if (!StdNamespace) {
3859 // The "std" namespace has not yet been defined, so build one implicitly.
3860 StdNamespace = NamespaceDecl::Create(Context,
3861 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003862 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00003863 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003864 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003865 }
3866
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003867 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003868}
3869
Douglas Gregor9172aa62011-03-26 22:25:30 +00003870/// \brief Determine whether a using statement is in a context where it will be
3871/// apply in all contexts.
3872static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3873 switch (CurContext->getDeclKind()) {
3874 case Decl::TranslationUnit:
3875 return true;
3876 case Decl::LinkageSpec:
3877 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3878 default:
3879 return false;
3880 }
3881}
3882
John McCalld226f652010-08-21 09:40:31 +00003883Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003884 SourceLocation UsingLoc,
3885 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003886 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003887 SourceLocation IdentLoc,
3888 IdentifierInfo *NamespcName,
3889 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003890 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3891 assert(NamespcName && "Invalid NamespcName.");
3892 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003893
3894 // This can only happen along a recovery path.
3895 while (S->getFlags() & Scope::TemplateParamScope)
3896 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003897 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003898
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003899 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003900 NestedNameSpecifier *Qualifier = 0;
3901 if (SS.isSet())
3902 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3903
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003904 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003905 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3906 LookupParsedName(R, S, &SS);
3907 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003908 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003909
Douglas Gregor66992202010-06-29 17:53:46 +00003910 if (R.empty()) {
3911 // Allow "using namespace std;" or "using namespace ::std;" even if
3912 // "std" hasn't been defined yet, for GCC compatibility.
3913 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3914 NamespcName->isStr("std")) {
3915 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003916 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003917 R.resolveKind();
3918 }
3919 // Otherwise, attempt typo correction.
3920 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3921 CTC_NoKeywords, 0)) {
3922 if (R.getAsSingle<NamespaceDecl>() ||
3923 R.getAsSingle<NamespaceAliasDecl>()) {
3924 if (DeclContext *DC = computeDeclContext(SS, false))
3925 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3926 << NamespcName << DC << Corrected << SS.getRange()
3927 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3928 else
3929 Diag(IdentLoc, diag::err_using_directive_suggest)
3930 << NamespcName << Corrected
3931 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3932 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3933 << Corrected;
3934
3935 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003936 } else {
3937 R.clear();
3938 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003939 }
3940 }
3941 }
3942
John McCallf36e02d2009-10-09 21:13:30 +00003943 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003944 NamedDecl *Named = R.getFoundDecl();
3945 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3946 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003947 // C++ [namespace.udir]p1:
3948 // A using-directive specifies that the names in the nominated
3949 // namespace can be used in the scope in which the
3950 // using-directive appears after the using-directive. During
3951 // unqualified name lookup (3.4.1), the names appear as if they
3952 // were declared in the nearest enclosing namespace which
3953 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003954 // namespace. [Note: in this context, "contains" means "contains
3955 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003956
3957 // Find enclosing context containing both using-directive and
3958 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003959 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003960 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3961 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3962 CommonAncestor = CommonAncestor->getParent();
3963
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003964 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00003965 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003966 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003967
Douglas Gregor9172aa62011-03-26 22:25:30 +00003968 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00003969 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003970 Diag(IdentLoc, diag::warn_using_directive_in_header);
3971 }
3972
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003973 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003974 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003975 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003976 }
3977
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003978 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003979 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003980}
3981
3982void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3983 // If scope has associated entity, then using directive is at namespace
3984 // or translation unit scope. We add UsingDirectiveDecls, into
3985 // it's lookup structure.
3986 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003987 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003988 else
3989 // Otherwise it is block-sope. using-directives will affect lookup
3990 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003991 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003992}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003993
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003994
John McCalld226f652010-08-21 09:40:31 +00003995Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003996 AccessSpecifier AS,
3997 bool HasUsingKeyword,
3998 SourceLocation UsingLoc,
3999 CXXScopeSpec &SS,
4000 UnqualifiedId &Name,
4001 AttributeList *AttrList,
4002 bool IsTypeName,
4003 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004004 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Douglas Gregor12c118a2009-11-04 16:30:06 +00004006 switch (Name.getKind()) {
4007 case UnqualifiedId::IK_Identifier:
4008 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00004009 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004010 case UnqualifiedId::IK_ConversionFunctionId:
4011 break;
4012
4013 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00004014 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00004015 // C++0x inherited constructors.
4016 if (getLangOptions().CPlusPlus0x) break;
4017
Douglas Gregor12c118a2009-11-04 16:30:06 +00004018 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4019 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004020 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004021
4022 case UnqualifiedId::IK_DestructorName:
4023 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4024 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004025 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004026
4027 case UnqualifiedId::IK_TemplateId:
4028 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4029 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00004030 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004031 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004032
4033 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4034 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00004035 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00004036 return 0;
John McCall604e7f12009-12-08 07:46:18 +00004037
John McCall60fa3cf2009-12-11 02:10:03 +00004038 // Warn about using declarations.
4039 // TODO: store that the declaration was written without 'using' and
4040 // talk about access decls instead of using decls in the
4041 // diagnostics.
4042 if (!HasUsingKeyword) {
4043 UsingLoc = Name.getSourceRange().getBegin();
4044
4045 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00004046 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00004047 }
4048
Douglas Gregor56c04582010-12-16 00:46:58 +00004049 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4050 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4051 return 0;
4052
John McCall9488ea12009-11-17 05:59:44 +00004053 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004054 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004055 /* IsInstantiation */ false,
4056 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00004057 if (UD)
4058 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00004059
John McCalld226f652010-08-21 09:40:31 +00004060 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00004061}
4062
Douglas Gregor09acc982010-07-07 23:08:52 +00004063/// \brief Determine whether a using declaration considers the given
4064/// declarations as "equivalent", e.g., if they are redeclarations of
4065/// the same entity or are both typedefs of the same type.
4066static bool
4067IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4068 bool &SuppressRedeclaration) {
4069 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4070 SuppressRedeclaration = false;
4071 return true;
4072 }
4073
Richard Smith162e1c12011-04-15 14:24:37 +00004074 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4075 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00004076 SuppressRedeclaration = true;
4077 return Context.hasSameType(TD1->getUnderlyingType(),
4078 TD2->getUnderlyingType());
4079 }
4080
4081 return false;
4082}
4083
4084
John McCall9f54ad42009-12-10 09:41:52 +00004085/// Determines whether to create a using shadow decl for a particular
4086/// decl, given the set of decls existing prior to this using lookup.
4087bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4088 const LookupResult &Previous) {
4089 // Diagnose finding a decl which is not from a base class of the
4090 // current class. We do this now because there are cases where this
4091 // function will silently decide not to build a shadow decl, which
4092 // will pre-empt further diagnostics.
4093 //
4094 // We don't need to do this in C++0x because we do the check once on
4095 // the qualifier.
4096 //
4097 // FIXME: diagnose the following if we care enough:
4098 // struct A { int foo; };
4099 // struct B : A { using A::foo; };
4100 // template <class T> struct C : A {};
4101 // template <class T> struct D : C<T> { using B::foo; } // <---
4102 // This is invalid (during instantiation) in C++03 because B::foo
4103 // resolves to the using decl in B, which is not a base class of D<T>.
4104 // We can't diagnose it immediately because C<T> is an unknown
4105 // specialization. The UsingShadowDecl in D<T> then points directly
4106 // to A::foo, which will look well-formed when we instantiate.
4107 // The right solution is to not collapse the shadow-decl chain.
4108 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4109 DeclContext *OrigDC = Orig->getDeclContext();
4110
4111 // Handle enums and anonymous structs.
4112 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4113 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4114 while (OrigRec->isAnonymousStructOrUnion())
4115 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4116
4117 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4118 if (OrigDC == CurContext) {
4119 Diag(Using->getLocation(),
4120 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004121 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004122 Diag(Orig->getLocation(), diag::note_using_decl_target);
4123 return true;
4124 }
4125
Douglas Gregordc355712011-02-25 00:36:19 +00004126 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00004127 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004128 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00004129 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00004130 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004131 Diag(Orig->getLocation(), diag::note_using_decl_target);
4132 return true;
4133 }
4134 }
4135
4136 if (Previous.empty()) return false;
4137
4138 NamedDecl *Target = Orig;
4139 if (isa<UsingShadowDecl>(Target))
4140 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4141
John McCalld7533ec2009-12-11 02:33:26 +00004142 // If the target happens to be one of the previous declarations, we
4143 // don't have a conflict.
4144 //
4145 // FIXME: but we might be increasing its access, in which case we
4146 // should redeclare it.
4147 NamedDecl *NonTag = 0, *Tag = 0;
4148 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4149 I != E; ++I) {
4150 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00004151 bool Result;
4152 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4153 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00004154
4155 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4156 }
4157
John McCall9f54ad42009-12-10 09:41:52 +00004158 if (Target->isFunctionOrFunctionTemplate()) {
4159 FunctionDecl *FD;
4160 if (isa<FunctionTemplateDecl>(Target))
4161 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4162 else
4163 FD = cast<FunctionDecl>(Target);
4164
4165 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00004166 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00004167 case Ovl_Overload:
4168 return false;
4169
4170 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00004171 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004172 break;
4173
4174 // We found a decl with the exact signature.
4175 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004176 // If we're in a record, we want to hide the target, so we
4177 // return true (without a diagnostic) to tell the caller not to
4178 // build a shadow decl.
4179 if (CurContext->isRecord())
4180 return true;
4181
4182 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00004183 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004184 break;
4185 }
4186
4187 Diag(Target->getLocation(), diag::note_using_decl_target);
4188 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4189 return true;
4190 }
4191
4192 // Target is not a function.
4193
John McCall9f54ad42009-12-10 09:41:52 +00004194 if (isa<TagDecl>(Target)) {
4195 // No conflict between a tag and a non-tag.
4196 if (!Tag) return false;
4197
John McCall41ce66f2009-12-10 19:51:03 +00004198 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004199 Diag(Target->getLocation(), diag::note_using_decl_target);
4200 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4201 return true;
4202 }
4203
4204 // No conflict between a tag and a non-tag.
4205 if (!NonTag) return false;
4206
John McCall41ce66f2009-12-10 19:51:03 +00004207 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004208 Diag(Target->getLocation(), diag::note_using_decl_target);
4209 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4210 return true;
4211}
4212
John McCall9488ea12009-11-17 05:59:44 +00004213/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004214UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004215 UsingDecl *UD,
4216 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004217
4218 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004219 NamedDecl *Target = Orig;
4220 if (isa<UsingShadowDecl>(Target)) {
4221 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4222 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004223 }
4224
4225 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004226 = UsingShadowDecl::Create(Context, CurContext,
4227 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004228 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004229
4230 Shadow->setAccess(UD->getAccess());
4231 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4232 Shadow->setInvalidDecl();
4233
John McCall9488ea12009-11-17 05:59:44 +00004234 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004235 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004236 else
John McCall604e7f12009-12-08 07:46:18 +00004237 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004238
John McCall604e7f12009-12-08 07:46:18 +00004239
John McCall9f54ad42009-12-10 09:41:52 +00004240 return Shadow;
4241}
John McCall604e7f12009-12-08 07:46:18 +00004242
John McCall9f54ad42009-12-10 09:41:52 +00004243/// Hides a using shadow declaration. This is required by the current
4244/// using-decl implementation when a resolvable using declaration in a
4245/// class is followed by a declaration which would hide or override
4246/// one or more of the using decl's targets; for example:
4247///
4248/// struct Base { void foo(int); };
4249/// struct Derived : Base {
4250/// using Base::foo;
4251/// void foo(int);
4252/// };
4253///
4254/// The governing language is C++03 [namespace.udecl]p12:
4255///
4256/// When a using-declaration brings names from a base class into a
4257/// derived class scope, member functions in the derived class
4258/// override and/or hide member functions with the same name and
4259/// parameter types in a base class (rather than conflicting).
4260///
4261/// There are two ways to implement this:
4262/// (1) optimistically create shadow decls when they're not hidden
4263/// by existing declarations, or
4264/// (2) don't create any shadow decls (or at least don't make them
4265/// visible) until we've fully parsed/instantiated the class.
4266/// The problem with (1) is that we might have to retroactively remove
4267/// a shadow decl, which requires several O(n) operations because the
4268/// decl structures are (very reasonably) not designed for removal.
4269/// (2) avoids this but is very fiddly and phase-dependent.
4270void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004271 if (Shadow->getDeclName().getNameKind() ==
4272 DeclarationName::CXXConversionFunctionName)
4273 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4274
John McCall9f54ad42009-12-10 09:41:52 +00004275 // Remove it from the DeclContext...
4276 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004277
John McCall9f54ad42009-12-10 09:41:52 +00004278 // ...and the scope, if applicable...
4279 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004280 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004281 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004282 }
4283
John McCall9f54ad42009-12-10 09:41:52 +00004284 // ...and the using decl.
4285 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4286
4287 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004288 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004289}
4290
John McCall7ba107a2009-11-18 02:36:19 +00004291/// Builds a using declaration.
4292///
4293/// \param IsInstantiation - Whether this call arises from an
4294/// instantiation of an unresolved using declaration. We treat
4295/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004296NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4297 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004298 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004299 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004300 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004301 bool IsInstantiation,
4302 bool IsTypeName,
4303 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004304 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004305 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004306 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004307
Anders Carlsson550b14b2009-08-28 05:49:21 +00004308 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004309
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004310 if (SS.isEmpty()) {
4311 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004312 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004313 }
Mike Stump1eb44332009-09-09 15:08:12 +00004314
John McCall9f54ad42009-12-10 09:41:52 +00004315 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004316 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004317 ForRedeclaration);
4318 Previous.setHideTags(false);
4319 if (S) {
4320 LookupName(Previous, S);
4321
4322 // It is really dumb that we have to do this.
4323 LookupResult::Filter F = Previous.makeFilter();
4324 while (F.hasNext()) {
4325 NamedDecl *D = F.next();
4326 if (!isDeclInScope(D, CurContext, S))
4327 F.erase();
4328 }
4329 F.done();
4330 } else {
4331 assert(IsInstantiation && "no scope in non-instantiation");
4332 assert(CurContext->isRecord() && "scope not record in instantiation");
4333 LookupQualifiedName(Previous, CurContext);
4334 }
4335
John McCall9f54ad42009-12-10 09:41:52 +00004336 // Check for invalid redeclarations.
4337 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4338 return 0;
4339
4340 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004341 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4342 return 0;
4343
John McCallaf8e6ed2009-11-12 03:15:40 +00004344 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004345 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00004346 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00004347 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004348 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004349 // FIXME: not all declaration name kinds are legal here
4350 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4351 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00004352 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004353 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004354 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004355 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4356 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004357 }
John McCalled976492009-12-04 22:46:56 +00004358 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004359 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4360 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004361 }
John McCalled976492009-12-04 22:46:56 +00004362 D->setAccess(AS);
4363 CurContext->addDecl(D);
4364
4365 if (!LookupContext) return D;
4366 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004367
John McCall77bb1aa2010-05-01 00:40:08 +00004368 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004369 UD->setInvalidDecl();
4370 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004371 }
4372
Sebastian Redlf677ea32011-02-05 19:23:19 +00004373 // Constructor inheriting using decls get special treatment.
4374 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004375 if (CheckInheritedConstructorUsingDecl(UD))
4376 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004377 return UD;
4378 }
4379
4380 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004381
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004382 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004383
John McCall604e7f12009-12-08 07:46:18 +00004384 // Unlike most lookups, we don't always want to hide tag
4385 // declarations: tag names are visible through the using declaration
4386 // even if hidden by ordinary names, *except* in a dependent context
4387 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004388 if (!IsInstantiation)
4389 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004390
John McCalla24dc2e2009-11-17 02:14:36 +00004391 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004392
John McCallf36e02d2009-10-09 21:13:30 +00004393 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004394 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004395 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004396 UD->setInvalidDecl();
4397 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004398 }
4399
John McCalled976492009-12-04 22:46:56 +00004400 if (R.isAmbiguous()) {
4401 UD->setInvalidDecl();
4402 return UD;
4403 }
Mike Stump1eb44332009-09-09 15:08:12 +00004404
John McCall7ba107a2009-11-18 02:36:19 +00004405 if (IsTypeName) {
4406 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004407 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004408 Diag(IdentLoc, diag::err_using_typename_non_type);
4409 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4410 Diag((*I)->getUnderlyingDecl()->getLocation(),
4411 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004412 UD->setInvalidDecl();
4413 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004414 }
4415 } else {
4416 // If we asked for a non-typename and we got a type, error out,
4417 // but only if this is an instantiation of an unresolved using
4418 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004419 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004420 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4421 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004422 UD->setInvalidDecl();
4423 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004424 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004425 }
4426
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004427 // C++0x N2914 [namespace.udecl]p6:
4428 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004429 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004430 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4431 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004432 UD->setInvalidDecl();
4433 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004434 }
Mike Stump1eb44332009-09-09 15:08:12 +00004435
John McCall9f54ad42009-12-10 09:41:52 +00004436 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4437 if (!CheckUsingShadowDecl(UD, *I, Previous))
4438 BuildUsingShadowDecl(S, UD, *I);
4439 }
John McCall9488ea12009-11-17 05:59:44 +00004440
4441 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004442}
4443
Sebastian Redlf677ea32011-02-05 19:23:19 +00004444/// Additional checks for a using declaration referring to a constructor name.
4445bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4446 if (UD->isTypeName()) {
4447 // FIXME: Cannot specify typename when specifying constructor
4448 return true;
4449 }
4450
Douglas Gregordc355712011-02-25 00:36:19 +00004451 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004452 assert(SourceType &&
4453 "Using decl naming constructor doesn't have type in scope spec.");
4454 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4455
4456 // Check whether the named type is a direct base class.
4457 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4458 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4459 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4460 BaseIt != BaseE; ++BaseIt) {
4461 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4462 if (CanonicalSourceType == BaseType)
4463 break;
4464 }
4465
4466 if (BaseIt == BaseE) {
4467 // Did not find SourceType in the bases.
4468 Diag(UD->getUsingLocation(),
4469 diag::err_using_decl_constructor_not_in_direct_base)
4470 << UD->getNameInfo().getSourceRange()
4471 << QualType(SourceType, 0) << TargetClass;
4472 return true;
4473 }
4474
4475 BaseIt->setInheritConstructors();
4476
4477 return false;
4478}
4479
John McCall9f54ad42009-12-10 09:41:52 +00004480/// Checks that the given using declaration is not an invalid
4481/// redeclaration. Note that this is checking only for the using decl
4482/// itself, not for any ill-formedness among the UsingShadowDecls.
4483bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4484 bool isTypeName,
4485 const CXXScopeSpec &SS,
4486 SourceLocation NameLoc,
4487 const LookupResult &Prev) {
4488 // C++03 [namespace.udecl]p8:
4489 // C++0x [namespace.udecl]p10:
4490 // A using-declaration is a declaration and can therefore be used
4491 // repeatedly where (and only where) multiple declarations are
4492 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004493 //
John McCall8a726212010-11-29 18:01:58 +00004494 // That's in non-member contexts.
4495 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004496 return false;
4497
4498 NestedNameSpecifier *Qual
4499 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4500
4501 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4502 NamedDecl *D = *I;
4503
4504 bool DTypename;
4505 NestedNameSpecifier *DQual;
4506 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4507 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00004508 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004509 } else if (UnresolvedUsingValueDecl *UD
4510 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4511 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00004512 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004513 } else if (UnresolvedUsingTypenameDecl *UD
4514 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4515 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00004516 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004517 } else continue;
4518
4519 // using decls differ if one says 'typename' and the other doesn't.
4520 // FIXME: non-dependent using decls?
4521 if (isTypeName != DTypename) continue;
4522
4523 // using decls differ if they name different scopes (but note that
4524 // template instantiation can cause this check to trigger when it
4525 // didn't before instantiation).
4526 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4527 Context.getCanonicalNestedNameSpecifier(DQual))
4528 continue;
4529
4530 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004531 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004532 return true;
4533 }
4534
4535 return false;
4536}
4537
John McCall604e7f12009-12-08 07:46:18 +00004538
John McCalled976492009-12-04 22:46:56 +00004539/// Checks that the given nested-name qualifier used in a using decl
4540/// in the current context is appropriately related to the current
4541/// scope. If an error is found, diagnoses it and returns true.
4542bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4543 const CXXScopeSpec &SS,
4544 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004545 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004546
John McCall604e7f12009-12-08 07:46:18 +00004547 if (!CurContext->isRecord()) {
4548 // C++03 [namespace.udecl]p3:
4549 // C++0x [namespace.udecl]p8:
4550 // A using-declaration for a class member shall be a member-declaration.
4551
4552 // If we weren't able to compute a valid scope, it must be a
4553 // dependent class scope.
4554 if (!NamedContext || NamedContext->isRecord()) {
4555 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4556 << SS.getRange();
4557 return true;
4558 }
4559
4560 // Otherwise, everything is known to be fine.
4561 return false;
4562 }
4563
4564 // The current scope is a record.
4565
4566 // If the named context is dependent, we can't decide much.
4567 if (!NamedContext) {
4568 // FIXME: in C++0x, we can diagnose if we can prove that the
4569 // nested-name-specifier does not refer to a base class, which is
4570 // still possible in some cases.
4571
4572 // Otherwise we have to conservatively report that things might be
4573 // okay.
4574 return false;
4575 }
4576
4577 if (!NamedContext->isRecord()) {
4578 // Ideally this would point at the last name in the specifier,
4579 // but we don't have that level of source info.
4580 Diag(SS.getRange().getBegin(),
4581 diag::err_using_decl_nested_name_specifier_is_not_class)
4582 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4583 return true;
4584 }
4585
Douglas Gregor6fb07292010-12-21 07:41:49 +00004586 if (!NamedContext->isDependentContext() &&
4587 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4588 return true;
4589
John McCall604e7f12009-12-08 07:46:18 +00004590 if (getLangOptions().CPlusPlus0x) {
4591 // C++0x [namespace.udecl]p3:
4592 // In a using-declaration used as a member-declaration, the
4593 // nested-name-specifier shall name a base class of the class
4594 // being defined.
4595
4596 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4597 cast<CXXRecordDecl>(NamedContext))) {
4598 if (CurContext == NamedContext) {
4599 Diag(NameLoc,
4600 diag::err_using_decl_nested_name_specifier_is_current_class)
4601 << SS.getRange();
4602 return true;
4603 }
4604
4605 Diag(SS.getRange().getBegin(),
4606 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4607 << (NestedNameSpecifier*) SS.getScopeRep()
4608 << cast<CXXRecordDecl>(CurContext)
4609 << SS.getRange();
4610 return true;
4611 }
4612
4613 return false;
4614 }
4615
4616 // C++03 [namespace.udecl]p4:
4617 // A using-declaration used as a member-declaration shall refer
4618 // to a member of a base class of the class being defined [etc.].
4619
4620 // Salient point: SS doesn't have to name a base class as long as
4621 // lookup only finds members from base classes. Therefore we can
4622 // diagnose here only if we can prove that that can't happen,
4623 // i.e. if the class hierarchies provably don't intersect.
4624
4625 // TODO: it would be nice if "definitely valid" results were cached
4626 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4627 // need to be repeated.
4628
4629 struct UserData {
4630 llvm::DenseSet<const CXXRecordDecl*> Bases;
4631
4632 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4633 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4634 Data->Bases.insert(Base);
4635 return true;
4636 }
4637
4638 bool hasDependentBases(const CXXRecordDecl *Class) {
4639 return !Class->forallBases(collect, this);
4640 }
4641
4642 /// Returns true if the base is dependent or is one of the
4643 /// accumulated base classes.
4644 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4645 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4646 return !Data->Bases.count(Base);
4647 }
4648
4649 bool mightShareBases(const CXXRecordDecl *Class) {
4650 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4651 }
4652 };
4653
4654 UserData Data;
4655
4656 // Returns false if we find a dependent base.
4657 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4658 return false;
4659
4660 // Returns false if the class has a dependent base or if it or one
4661 // of its bases is present in the base set of the current context.
4662 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4663 return false;
4664
4665 Diag(SS.getRange().getBegin(),
4666 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4667 << (NestedNameSpecifier*) SS.getScopeRep()
4668 << cast<CXXRecordDecl>(CurContext)
4669 << SS.getRange();
4670
4671 return true;
John McCalled976492009-12-04 22:46:56 +00004672}
4673
Richard Smith162e1c12011-04-15 14:24:37 +00004674Decl *Sema::ActOnAliasDeclaration(Scope *S,
4675 AccessSpecifier AS,
4676 SourceLocation UsingLoc,
4677 UnqualifiedId &Name,
4678 TypeResult Type) {
4679 assert((S->getFlags() & Scope::DeclScope) &&
4680 "got alias-declaration outside of declaration scope");
4681
4682 if (Type.isInvalid())
4683 return 0;
4684
4685 bool Invalid = false;
4686 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4687 TypeSourceInfo *TInfo = 0;
4688 QualType T = GetTypeFromParser(Type.get(), &TInfo);
4689
4690 if (DiagnoseClassNameShadow(CurContext, NameInfo))
4691 return 0;
4692
4693 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
4694 UPPC_DeclarationType))
4695 Invalid = true;
4696
4697 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4698 LookupName(Previous, S);
4699
4700 // Warn about shadowing the name of a template parameter.
4701 if (Previous.isSingleResult() &&
4702 Previous.getFoundDecl()->isTemplateParameter()) {
4703 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4704 Previous.getFoundDecl()))
4705 Invalid = true;
4706 Previous.clear();
4707 }
4708
4709 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4710 "name in alias declaration must be an identifier");
4711 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4712 Name.StartLocation,
4713 Name.Identifier, TInfo);
4714
4715 NewTD->setAccess(AS);
4716
4717 if (Invalid)
4718 NewTD->setInvalidDecl();
4719
4720 bool Redeclaration = false;
4721 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
4722
4723 if (!Redeclaration)
4724 PushOnScopeChains(NewTD, S);
4725
4726 return NewTD;
4727}
4728
John McCalld226f652010-08-21 09:40:31 +00004729Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004730 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004731 SourceLocation AliasLoc,
4732 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004733 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004734 SourceLocation IdentLoc,
4735 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Anders Carlsson81c85c42009-03-28 23:53:49 +00004737 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004738 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4739 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004740
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004741 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004742 NamedDecl *PrevDecl
4743 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4744 ForRedeclaration);
4745 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4746 PrevDecl = 0;
4747
4748 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004749 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004750 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004751 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004752 // FIXME: At some point, we'll want to create the (redundant)
4753 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004754 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004755 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004756 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004757 }
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004759 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4760 diag::err_redefinition_different_kind;
4761 Diag(AliasLoc, DiagID) << Alias;
4762 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004763 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004764 }
4765
John McCalla24dc2e2009-11-17 02:14:36 +00004766 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004767 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004768
John McCallf36e02d2009-10-09 21:13:30 +00004769 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004770 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4771 CTC_NoKeywords, 0)) {
4772 if (R.getAsSingle<NamespaceDecl>() ||
4773 R.getAsSingle<NamespaceAliasDecl>()) {
4774 if (DeclContext *DC = computeDeclContext(SS, false))
4775 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4776 << Ident << DC << Corrected << SS.getRange()
4777 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4778 else
4779 Diag(IdentLoc, diag::err_using_directive_suggest)
4780 << Ident << Corrected
4781 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4782
4783 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4784 << Corrected;
4785
4786 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004787 } else {
4788 R.clear();
4789 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004790 }
4791 }
4792
4793 if (R.empty()) {
4794 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004795 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004796 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004797 }
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004799 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004800 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00004801 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00004802 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004803
John McCall3dbd3d52010-02-16 06:53:13 +00004804 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004805 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004806}
4807
Douglas Gregor39957dc2010-05-01 15:04:51 +00004808namespace {
4809 /// \brief Scoped object used to handle the state changes required in Sema
4810 /// to implicitly define the body of a C++ member function;
4811 class ImplicitlyDefinedFunctionScope {
4812 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004813 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004814
4815 public:
4816 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004817 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004818 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004819 S.PushFunctionScope();
4820 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4821 }
4822
4823 ~ImplicitlyDefinedFunctionScope() {
4824 S.PopExpressionEvaluationContext();
4825 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004826 }
4827 };
4828}
4829
Sebastian Redl751025d2010-09-13 22:02:47 +00004830static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4831 CXXRecordDecl *D) {
4832 ASTContext &Context = Self.Context;
4833 QualType ClassType = Context.getTypeDeclType(D);
4834 DeclarationName ConstructorName
4835 = Context.DeclarationNames.getCXXConstructorName(
4836 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4837
4838 DeclContext::lookup_const_iterator Con, ConEnd;
4839 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4840 Con != ConEnd; ++Con) {
4841 // FIXME: In C++0x, a constructor template can be a default constructor.
4842 if (isa<FunctionTemplateDecl>(*Con))
4843 continue;
4844
4845 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4846 if (Constructor->isDefaultConstructor())
4847 return Constructor;
4848 }
4849 return 0;
4850}
4851
Douglas Gregor23c94db2010-07-02 17:43:08 +00004852CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4853 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004854 // C++ [class.ctor]p5:
4855 // A default constructor for a class X is a constructor of class X
4856 // that can be called without an argument. If there is no
4857 // user-declared constructor for class X, a default constructor is
4858 // implicitly declared. An implicitly-declared default constructor
4859 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004860 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4861 "Should not build implicit default constructor!");
4862
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004863 // C++ [except.spec]p14:
4864 // An implicitly declared special member function (Clause 12) shall have an
4865 // exception-specification. [...]
4866 ImplicitExceptionSpecification ExceptSpec(Context);
4867
Sebastian Redl60618fa2011-03-12 11:50:43 +00004868 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004869 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4870 BEnd = ClassDecl->bases_end();
4871 B != BEnd; ++B) {
4872 if (B->isVirtual()) // Handled below.
4873 continue;
4874
Douglas Gregor18274032010-07-03 00:47:00 +00004875 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4876 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4877 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4878 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004879 else if (CXXConstructorDecl *Constructor
4880 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004881 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004882 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004883 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004884
4885 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004886 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4887 BEnd = ClassDecl->vbases_end();
4888 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004889 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4890 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4891 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4892 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4893 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004894 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004895 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004896 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004897 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004898
4899 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004900 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4901 FEnd = ClassDecl->field_end();
4902 F != FEnd; ++F) {
4903 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004904 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4905 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4906 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4907 ExceptSpec.CalledDecl(
4908 DeclareImplicitDefaultConstructor(FieldClassDecl));
4909 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004910 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004911 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004912 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004913 }
John McCalle23cf432010-12-14 08:05:40 +00004914
4915 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00004916 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00004917 EPI.NumExceptions = ExceptSpec.size();
4918 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00004919
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004920 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004921 CanQualType ClassType
4922 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004923 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00004924 DeclarationName Name
4925 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004926 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00004927 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004928 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004929 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004930 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004931 /*TInfo=*/0,
4932 /*isExplicit=*/false,
4933 /*isInline=*/true,
4934 /*isImplicitlyDeclared=*/true);
4935 DefaultCon->setAccess(AS_public);
4936 DefaultCon->setImplicit();
4937 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004938
4939 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004940 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4941
Douglas Gregor23c94db2010-07-02 17:43:08 +00004942 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004943 PushOnScopeChains(DefaultCon, S, false);
4944 ClassDecl->addDecl(DefaultCon);
4945
Douglas Gregor32df23e2010-07-01 22:02:46 +00004946 return DefaultCon;
4947}
4948
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004949void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4950 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004951 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004952 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004953 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004954
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004955 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004956 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004957
Douglas Gregor39957dc2010-05-01 15:04:51 +00004958 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004959 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004960 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004961 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004962 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004963 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004964 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004965 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004966 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004967
4968 SourceLocation Loc = Constructor->getLocation();
4969 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4970
4971 Constructor->setUsed();
4972 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00004973
4974 if (ASTMutationListener *L = getASTMutationListener()) {
4975 L->CompletedImplicitDefinition(Constructor);
4976 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004977}
4978
Sebastian Redlf677ea32011-02-05 19:23:19 +00004979void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4980 // We start with an initial pass over the base classes to collect those that
4981 // inherit constructors from. If there are none, we can forgo all further
4982 // processing.
4983 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4984 BasesVector BasesToInheritFrom;
4985 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4986 BaseE = ClassDecl->bases_end();
4987 BaseIt != BaseE; ++BaseIt) {
4988 if (BaseIt->getInheritConstructors()) {
4989 QualType Base = BaseIt->getType();
4990 if (Base->isDependentType()) {
4991 // If we inherit constructors from anything that is dependent, just
4992 // abort processing altogether. We'll get another chance for the
4993 // instantiations.
4994 return;
4995 }
4996 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4997 }
4998 }
4999 if (BasesToInheritFrom.empty())
5000 return;
5001
5002 // Now collect the constructors that we already have in the current class.
5003 // Those take precedence over inherited constructors.
5004 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5005 // unless there is a user-declared constructor with the same signature in
5006 // the class where the using-declaration appears.
5007 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5008 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5009 CtorE = ClassDecl->ctor_end();
5010 CtorIt != CtorE; ++CtorIt) {
5011 ExistingConstructors.insert(
5012 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5013 }
5014
5015 Scope *S = getScopeForContext(ClassDecl);
5016 DeclarationName CreatedCtorName =
5017 Context.DeclarationNames.getCXXConstructorName(
5018 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5019
5020 // Now comes the true work.
5021 // First, we keep a map from constructor types to the base that introduced
5022 // them. Needed for finding conflicting constructors. We also keep the
5023 // actually inserted declarations in there, for pretty diagnostics.
5024 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5025 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5026 ConstructorToSourceMap InheritedConstructors;
5027 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5028 BaseE = BasesToInheritFrom.end();
5029 BaseIt != BaseE; ++BaseIt) {
5030 const RecordType *Base = *BaseIt;
5031 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5032 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5033 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5034 CtorE = BaseDecl->ctor_end();
5035 CtorIt != CtorE; ++CtorIt) {
5036 // Find the using declaration for inheriting this base's constructors.
5037 DeclarationName Name =
5038 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5039 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5040 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5041 SourceLocation UsingLoc = UD ? UD->getLocation() :
5042 ClassDecl->getLocation();
5043
5044 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5045 // from the class X named in the using-declaration consists of actual
5046 // constructors and notional constructors that result from the
5047 // transformation of defaulted parameters as follows:
5048 // - all non-template default constructors of X, and
5049 // - for each non-template constructor of X that has at least one
5050 // parameter with a default argument, the set of constructors that
5051 // results from omitting any ellipsis parameter specification and
5052 // successively omitting parameters with a default argument from the
5053 // end of the parameter-type-list.
5054 CXXConstructorDecl *BaseCtor = *CtorIt;
5055 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5056 const FunctionProtoType *BaseCtorType =
5057 BaseCtor->getType()->getAs<FunctionProtoType>();
5058
5059 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5060 maxParams = BaseCtor->getNumParams();
5061 params <= maxParams; ++params) {
5062 // Skip default constructors. They're never inherited.
5063 if (params == 0)
5064 continue;
5065 // Skip copy and move constructors for the same reason.
5066 if (CanBeCopyOrMove && params == 1)
5067 continue;
5068
5069 // Build up a function type for this particular constructor.
5070 // FIXME: The working paper does not consider that the exception spec
5071 // for the inheriting constructor might be larger than that of the
5072 // source. This code doesn't yet, either.
5073 const Type *NewCtorType;
5074 if (params == maxParams)
5075 NewCtorType = BaseCtorType;
5076 else {
5077 llvm::SmallVector<QualType, 16> Args;
5078 for (unsigned i = 0; i < params; ++i) {
5079 Args.push_back(BaseCtorType->getArgType(i));
5080 }
5081 FunctionProtoType::ExtProtoInfo ExtInfo =
5082 BaseCtorType->getExtProtoInfo();
5083 ExtInfo.Variadic = false;
5084 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5085 Args.data(), params, ExtInfo)
5086 .getTypePtr();
5087 }
5088 const Type *CanonicalNewCtorType =
5089 Context.getCanonicalType(NewCtorType);
5090
5091 // Now that we have the type, first check if the class already has a
5092 // constructor with this signature.
5093 if (ExistingConstructors.count(CanonicalNewCtorType))
5094 continue;
5095
5096 // Then we check if we have already declared an inherited constructor
5097 // with this signature.
5098 std::pair<ConstructorToSourceMap::iterator, bool> result =
5099 InheritedConstructors.insert(std::make_pair(
5100 CanonicalNewCtorType,
5101 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5102 if (!result.second) {
5103 // Already in the map. If it came from a different class, that's an
5104 // error. Not if it's from the same.
5105 CanQualType PreviousBase = result.first->second.first;
5106 if (CanonicalBase != PreviousBase) {
5107 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5108 const CXXConstructorDecl *PrevBaseCtor =
5109 PrevCtor->getInheritedConstructor();
5110 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5111
5112 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5113 Diag(BaseCtor->getLocation(),
5114 diag::note_using_decl_constructor_conflict_current_ctor);
5115 Diag(PrevBaseCtor->getLocation(),
5116 diag::note_using_decl_constructor_conflict_previous_ctor);
5117 Diag(PrevCtor->getLocation(),
5118 diag::note_using_decl_constructor_conflict_previous_using);
5119 }
5120 continue;
5121 }
5122
5123 // OK, we're there, now add the constructor.
5124 // C++0x [class.inhctor]p8: [...] that would be performed by a
5125 // user-writtern inline constructor [...]
5126 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5127 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005128 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5129 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005130 /*ImplicitlyDeclared=*/true);
5131 NewCtor->setAccess(BaseCtor->getAccess());
5132
5133 // Build up the parameter decls and add them.
5134 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5135 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005136 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5137 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005138 /*IdentifierInfo=*/0,
5139 BaseCtorType->getArgType(i),
5140 /*TInfo=*/0, SC_None,
5141 SC_None, /*DefaultArg=*/0));
5142 }
5143 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5144 NewCtor->setInheritedConstructor(BaseCtor);
5145
5146 PushOnScopeChains(NewCtor, S, false);
5147 ClassDecl->addDecl(NewCtor);
5148 result.first->second.second = NewCtor;
5149 }
5150 }
5151 }
5152}
5153
Douglas Gregor23c94db2010-07-02 17:43:08 +00005154CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005155 // C++ [class.dtor]p2:
5156 // If a class has no user-declared destructor, a destructor is
5157 // declared implicitly. An implicitly-declared destructor is an
5158 // inline public member of its class.
5159
5160 // C++ [except.spec]p14:
5161 // An implicitly declared special member function (Clause 12) shall have
5162 // an exception-specification.
5163 ImplicitExceptionSpecification ExceptSpec(Context);
5164
5165 // Direct base-class destructors.
5166 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5167 BEnd = ClassDecl->bases_end();
5168 B != BEnd; ++B) {
5169 if (B->isVirtual()) // Handled below.
5170 continue;
5171
5172 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5173 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005174 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005175 }
5176
5177 // Virtual base-class destructors.
5178 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5179 BEnd = ClassDecl->vbases_end();
5180 B != BEnd; ++B) {
5181 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5182 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005183 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005184 }
5185
5186 // Field destructors.
5187 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5188 FEnd = ClassDecl->field_end();
5189 F != FEnd; ++F) {
5190 if (const RecordType *RecordTy
5191 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5192 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005193 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005194 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005195
Douglas Gregor4923aa22010-07-02 20:37:36 +00005196 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00005197 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005198 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005199 EPI.NumExceptions = ExceptSpec.size();
5200 EPI.Exceptions = ExceptSpec.data();
5201 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00005202
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005203 CanQualType ClassType
5204 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005205 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005206 DeclarationName Name
5207 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005208 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005209 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00005210 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5211 /*isInline=*/true,
5212 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005213 Destructor->setAccess(AS_public);
5214 Destructor->setImplicit();
5215 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00005216
5217 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00005218 ++ASTContext::NumImplicitDestructorsDeclared;
5219
5220 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005221 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00005222 PushOnScopeChains(Destructor, S, false);
5223 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005224
5225 // This could be uniqued if it ever proves significant.
5226 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5227
5228 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00005229
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005230 return Destructor;
5231}
5232
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005233void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00005234 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00005235 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005236 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00005237 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005238 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005239
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005240 if (Destructor->isInvalidDecl())
5241 return;
5242
Douglas Gregor39957dc2010-05-01 15:04:51 +00005243 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005244
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005245 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00005246 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5247 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00005248
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005249 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005250 Diag(CurrentLocation, diag::note_member_synthesized_at)
5251 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5252
5253 Destructor->setInvalidDecl();
5254 return;
5255 }
5256
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005257 SourceLocation Loc = Destructor->getLocation();
5258 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5259
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005260 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005261 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005262
5263 if (ASTMutationListener *L = getASTMutationListener()) {
5264 L->CompletedImplicitDefinition(Destructor);
5265 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005266}
5267
Douglas Gregor06a9f362010-05-01 20:49:11 +00005268/// \brief Builds a statement that copies the given entity from \p From to
5269/// \c To.
5270///
5271/// This routine is used to copy the members of a class with an
5272/// implicitly-declared copy assignment operator. When the entities being
5273/// copied are arrays, this routine builds for loops to copy them.
5274///
5275/// \param S The Sema object used for type-checking.
5276///
5277/// \param Loc The location where the implicit copy is being generated.
5278///
5279/// \param T The type of the expressions being copied. Both expressions must
5280/// have this type.
5281///
5282/// \param To The expression we are copying to.
5283///
5284/// \param From The expression we are copying from.
5285///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005286/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5287/// Otherwise, it's a non-static member subobject.
5288///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005289/// \param Depth Internal parameter recording the depth of the recursion.
5290///
5291/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005292static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005293BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005294 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005295 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005296 // C++0x [class.copy]p30:
5297 // Each subobject is assigned in the manner appropriate to its type:
5298 //
5299 // - if the subobject is of class type, the copy assignment operator
5300 // for the class is used (as if by explicit qualification; that is,
5301 // ignoring any possible virtual overriding functions in more derived
5302 // classes);
5303 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5305
5306 // Look for operator=.
5307 DeclarationName Name
5308 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5309 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5310 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5311
5312 // Filter out any result that isn't a copy-assignment operator.
5313 LookupResult::Filter F = OpLookup.makeFilter();
5314 while (F.hasNext()) {
5315 NamedDecl *D = F.next();
5316 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5317 if (Method->isCopyAssignmentOperator())
5318 continue;
5319
5320 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005321 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005322 F.done();
5323
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005324 // Suppress the protected check (C++ [class.protected]) for each of the
5325 // assignment operators we found. This strange dance is required when
5326 // we're assigning via a base classes's copy-assignment operator. To
5327 // ensure that we're getting the right base class subobject (without
5328 // ambiguities), we need to cast "this" to that subobject type; to
5329 // ensure that we don't go through the virtual call mechanism, we need
5330 // to qualify the operator= name with the base class (see below). However,
5331 // this means that if the base class has a protected copy assignment
5332 // operator, the protected member access check will fail. So, we
5333 // rewrite "protected" access to "public" access in this case, since we
5334 // know by construction that we're calling from a derived class.
5335 if (CopyingBaseSubobject) {
5336 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5337 L != LEnd; ++L) {
5338 if (L.getAccess() == AS_protected)
5339 L.setAccess(AS_public);
5340 }
5341 }
5342
Douglas Gregor06a9f362010-05-01 20:49:11 +00005343 // Create the nested-name-specifier that will be used to qualify the
5344 // reference to operator=; this is required to suppress the virtual
5345 // call mechanism.
5346 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00005347 SS.MakeTrivial(S.Context,
5348 NestedNameSpecifier::Create(S.Context, 0, false,
5349 T.getTypePtr()),
5350 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005351
5352 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005353 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005354 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005355 /*FirstQualifierInScope=*/0, OpLookup,
5356 /*TemplateArgs=*/0,
5357 /*SuppressQualifierCheck=*/true);
5358 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005359 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005360
5361 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005362
John McCall60d7b3a2010-08-24 06:29:42 +00005363 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005364 OpEqualRef.takeAs<Expr>(),
5365 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005366 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005367 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005368
5369 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005370 }
John McCallb0207482010-03-16 06:11:48 +00005371
Douglas Gregor06a9f362010-05-01 20:49:11 +00005372 // - if the subobject is of scalar type, the built-in assignment
5373 // operator is used.
5374 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5375 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005376 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005377 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005378 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005379
5380 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005381 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005382
5383 // - if the subobject is an array, each element is assigned, in the
5384 // manner appropriate to the element type;
5385
5386 // Construct a loop over the array bounds, e.g.,
5387 //
5388 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5389 //
5390 // that will copy each of the array elements.
5391 QualType SizeType = S.Context.getSizeType();
5392
5393 // Create the iteration variable.
5394 IdentifierInfo *IterationVarName = 0;
5395 {
5396 llvm::SmallString<8> Str;
5397 llvm::raw_svector_ostream OS(Str);
5398 OS << "__i" << Depth;
5399 IterationVarName = &S.Context.Idents.get(OS.str());
5400 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005401 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005402 IterationVarName, SizeType,
5403 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005404 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005405
5406 // Initialize the iteration variable to zero.
5407 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005408 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005409
5410 // Create a reference to the iteration variable; we'll use this several
5411 // times throughout.
5412 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005413 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005414 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5415
5416 // Create the DeclStmt that holds the iteration variable.
5417 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5418
5419 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005420 llvm::APInt Upper
5421 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005422 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005423 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005424 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5425 BO_NE, S.Context.BoolTy,
5426 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005427
5428 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005429 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005430 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5431 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005432
5433 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005434 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5435 IterationVarRef, Loc));
5436 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5437 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005438
5439 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005440 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5441 To, From, CopyingBaseSubobject,
5442 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005443 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005444 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005445
5446 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005447 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005448 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005449 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005450 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005451}
5452
Douglas Gregora376d102010-07-02 21:50:04 +00005453/// \brief Determine whether the given class has a copy assignment operator
5454/// that accepts a const-qualified argument.
5455static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5456 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5457
5458 if (!Class->hasDeclaredCopyAssignment())
5459 S.DeclareImplicitCopyAssignment(Class);
5460
5461 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5462 DeclarationName OpName
5463 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5464
5465 DeclContext::lookup_const_iterator Op, OpEnd;
5466 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5467 // C++ [class.copy]p9:
5468 // A user-declared copy assignment operator is a non-static non-template
5469 // member function of class X with exactly one parameter of type X, X&,
5470 // const X&, volatile X& or const volatile X&.
5471 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5472 if (!Method)
5473 continue;
5474
5475 if (Method->isStatic())
5476 continue;
5477 if (Method->getPrimaryTemplate())
5478 continue;
5479 const FunctionProtoType *FnType =
5480 Method->getType()->getAs<FunctionProtoType>();
5481 assert(FnType && "Overloaded operator has no prototype.");
5482 // Don't assert on this; an invalid decl might have been left in the AST.
5483 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5484 continue;
5485 bool AcceptsConst = true;
5486 QualType ArgType = FnType->getArgType(0);
5487 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5488 ArgType = Ref->getPointeeType();
5489 // Is it a non-const lvalue reference?
5490 if (!ArgType.isConstQualified())
5491 AcceptsConst = false;
5492 }
5493 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5494 continue;
5495
5496 // We have a single argument of type cv X or cv X&, i.e. we've found the
5497 // copy assignment operator. Return whether it accepts const arguments.
5498 return AcceptsConst;
5499 }
5500 assert(Class->isInvalidDecl() &&
5501 "No copy assignment operator declared in valid code.");
5502 return false;
5503}
5504
Douglas Gregor23c94db2010-07-02 17:43:08 +00005505CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005506 // Note: The following rules are largely analoguous to the copy
5507 // constructor rules. Note that virtual bases are not taken into account
5508 // for determining the argument type of the operator. Note also that
5509 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005510
5511
Douglas Gregord3c35902010-07-01 16:36:15 +00005512 // C++ [class.copy]p10:
5513 // If the class definition does not explicitly declare a copy
5514 // assignment operator, one is declared implicitly.
5515 // The implicitly-defined copy assignment operator for a class X
5516 // will have the form
5517 //
5518 // X& X::operator=(const X&)
5519 //
5520 // if
5521 bool HasConstCopyAssignment = true;
5522
5523 // -- each direct base class B of X has a copy assignment operator
5524 // whose parameter is of type const B&, const volatile B& or B,
5525 // and
5526 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5527 BaseEnd = ClassDecl->bases_end();
5528 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5529 assert(!Base->getType()->isDependentType() &&
5530 "Cannot generate implicit members for class with dependent bases.");
5531 const CXXRecordDecl *BaseClassDecl
5532 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005533 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005534 }
5535
5536 // -- for all the nonstatic data members of X that are of a class
5537 // type M (or array thereof), each such class type has a copy
5538 // assignment operator whose parameter is of type const M&,
5539 // const volatile M& or M.
5540 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5541 FieldEnd = ClassDecl->field_end();
5542 HasConstCopyAssignment && Field != FieldEnd;
5543 ++Field) {
5544 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5545 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5546 const CXXRecordDecl *FieldClassDecl
5547 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005548 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005549 }
5550 }
5551
5552 // Otherwise, the implicitly declared copy assignment operator will
5553 // have the form
5554 //
5555 // X& X::operator=(X&)
5556 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5557 QualType RetType = Context.getLValueReferenceType(ArgType);
5558 if (HasConstCopyAssignment)
5559 ArgType = ArgType.withConst();
5560 ArgType = Context.getLValueReferenceType(ArgType);
5561
Douglas Gregorb87786f2010-07-01 17:48:08 +00005562 // C++ [except.spec]p14:
5563 // An implicitly declared special member function (Clause 12) shall have an
5564 // exception-specification. [...]
5565 ImplicitExceptionSpecification ExceptSpec(Context);
5566 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5567 BaseEnd = ClassDecl->bases_end();
5568 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005569 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005570 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005571
5572 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5573 DeclareImplicitCopyAssignment(BaseClassDecl);
5574
Douglas Gregorb87786f2010-07-01 17:48:08 +00005575 if (CXXMethodDecl *CopyAssign
5576 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5577 ExceptSpec.CalledDecl(CopyAssign);
5578 }
5579 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5580 FieldEnd = ClassDecl->field_end();
5581 Field != FieldEnd;
5582 ++Field) {
5583 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5584 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005585 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005586 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005587
5588 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5589 DeclareImplicitCopyAssignment(FieldClassDecl);
5590
Douglas Gregorb87786f2010-07-01 17:48:08 +00005591 if (CXXMethodDecl *CopyAssign
5592 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5593 ExceptSpec.CalledDecl(CopyAssign);
5594 }
5595 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005596
Douglas Gregord3c35902010-07-01 16:36:15 +00005597 // An implicitly-declared copy assignment operator is an inline public
5598 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005599 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005600 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005601 EPI.NumExceptions = ExceptSpec.size();
5602 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005603 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005604 SourceLocation ClassLoc = ClassDecl->getLocation();
5605 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00005606 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005607 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005608 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005609 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005610 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00005611 /*isInline=*/true,
5612 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005613 CopyAssignment->setAccess(AS_public);
5614 CopyAssignment->setImplicit();
5615 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005616
5617 // Add the parameter to the operator.
5618 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005619 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00005620 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005621 SC_None,
5622 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005623 CopyAssignment->setParams(&FromParam, 1);
5624
Douglas Gregora376d102010-07-02 21:50:04 +00005625 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005626 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5627
Douglas Gregor23c94db2010-07-02 17:43:08 +00005628 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005629 PushOnScopeChains(CopyAssignment, S, false);
5630 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005631
5632 AddOverriddenMethods(ClassDecl, CopyAssignment);
5633 return CopyAssignment;
5634}
5635
Douglas Gregor06a9f362010-05-01 20:49:11 +00005636void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5637 CXXMethodDecl *CopyAssignOperator) {
5638 assert((CopyAssignOperator->isImplicit() &&
5639 CopyAssignOperator->isOverloadedOperator() &&
5640 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005641 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005642 "DefineImplicitCopyAssignment called for wrong function");
5643
5644 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5645
5646 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5647 CopyAssignOperator->setInvalidDecl();
5648 return;
5649 }
5650
5651 CopyAssignOperator->setUsed();
5652
5653 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005654 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005655
5656 // C++0x [class.copy]p30:
5657 // The implicitly-defined or explicitly-defaulted copy assignment operator
5658 // for a non-union class X performs memberwise copy assignment of its
5659 // subobjects. The direct base classes of X are assigned first, in the
5660 // order of their declaration in the base-specifier-list, and then the
5661 // immediate non-static data members of X are assigned, in the order in
5662 // which they were declared in the class definition.
5663
5664 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005665 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005666
5667 // The parameter for the "other" object, which we are copying from.
5668 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5669 Qualifiers OtherQuals = Other->getType().getQualifiers();
5670 QualType OtherRefType = Other->getType();
5671 if (const LValueReferenceType *OtherRef
5672 = OtherRefType->getAs<LValueReferenceType>()) {
5673 OtherRefType = OtherRef->getPointeeType();
5674 OtherQuals = OtherRefType.getQualifiers();
5675 }
5676
5677 // Our location for everything implicitly-generated.
5678 SourceLocation Loc = CopyAssignOperator->getLocation();
5679
5680 // Construct a reference to the "other" object. We'll be using this
5681 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005682 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005683 assert(OtherRef && "Reference to parameter cannot fail!");
5684
5685 // Construct the "this" pointer. We'll be using this throughout the generated
5686 // ASTs.
5687 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5688 assert(This && "Reference to this cannot fail!");
5689
5690 // Assign base classes.
5691 bool Invalid = false;
5692 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5693 E = ClassDecl->bases_end(); Base != E; ++Base) {
5694 // Form the assignment:
5695 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5696 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005697 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005698 Invalid = true;
5699 continue;
5700 }
5701
John McCallf871d0c2010-08-07 06:22:56 +00005702 CXXCastPath BasePath;
5703 BasePath.push_back(Base);
5704
Douglas Gregor06a9f362010-05-01 20:49:11 +00005705 // Construct the "from" expression, which is an implicit cast to the
5706 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005707 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00005708 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5709 CK_UncheckedDerivedToBase,
5710 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005711
5712 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005713 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005714
5715 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00005716 To = ImpCastExprToType(To.take(),
5717 Context.getCVRQualifiedType(BaseType,
5718 CopyAssignOperator->getTypeQualifiers()),
5719 CK_UncheckedDerivedToBase,
5720 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005721
5722 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005723 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005724 To.get(), From,
5725 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005726 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005727 Diag(CurrentLocation, diag::note_member_synthesized_at)
5728 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5729 CopyAssignOperator->setInvalidDecl();
5730 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005731 }
5732
5733 // Success! Record the copy.
5734 Statements.push_back(Copy.takeAs<Expr>());
5735 }
5736
5737 // \brief Reference to the __builtin_memcpy function.
5738 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005739 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005740 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005741
5742 // Assign non-static members.
5743 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5744 FieldEnd = ClassDecl->field_end();
5745 Field != FieldEnd; ++Field) {
5746 // Check for members of reference type; we can't copy those.
5747 if (Field->getType()->isReferenceType()) {
5748 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5749 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5750 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005751 Diag(CurrentLocation, diag::note_member_synthesized_at)
5752 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005753 Invalid = true;
5754 continue;
5755 }
5756
5757 // Check for members of const-qualified, non-class type.
5758 QualType BaseType = Context.getBaseElementType(Field->getType());
5759 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5760 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5761 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5762 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005763 Diag(CurrentLocation, diag::note_member_synthesized_at)
5764 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005765 Invalid = true;
5766 continue;
5767 }
5768
5769 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005770 if (FieldType->isIncompleteArrayType()) {
5771 assert(ClassDecl->hasFlexibleArrayMember() &&
5772 "Incomplete array type is not valid");
5773 continue;
5774 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005775
5776 // Build references to the field in the object we're copying from and to.
5777 CXXScopeSpec SS; // Intentionally empty
5778 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5779 LookupMemberName);
5780 MemberLookup.addDecl(*Field);
5781 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005782 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005783 Loc, /*IsArrow=*/false,
5784 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005785 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005786 Loc, /*IsArrow=*/true,
5787 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005788 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5789 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5790
5791 // If the field should be copied with __builtin_memcpy rather than via
5792 // explicit assignments, do so. This optimization only applies for arrays
5793 // of scalars and arrays of class type with trivial copy-assignment
5794 // operators.
5795 if (FieldType->isArrayType() &&
5796 (!BaseType->isRecordType() ||
5797 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5798 ->hasTrivialCopyAssignment())) {
5799 // Compute the size of the memory buffer to be copied.
5800 QualType SizeType = Context.getSizeType();
5801 llvm::APInt Size(Context.getTypeSize(SizeType),
5802 Context.getTypeSizeInChars(BaseType).getQuantity());
5803 for (const ConstantArrayType *Array
5804 = Context.getAsConstantArrayType(FieldType);
5805 Array;
5806 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005807 llvm::APInt ArraySize
5808 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005809 Size *= ArraySize;
5810 }
5811
5812 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005813 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5814 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005815
5816 bool NeedsCollectableMemCpy =
5817 (BaseType->isRecordType() &&
5818 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5819
5820 if (NeedsCollectableMemCpy) {
5821 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005822 // Create a reference to the __builtin_objc_memmove_collectable function.
5823 LookupResult R(*this,
5824 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005825 Loc, LookupOrdinaryName);
5826 LookupName(R, TUScope, true);
5827
5828 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5829 if (!CollectableMemCpy) {
5830 // Something went horribly wrong earlier, and we will have
5831 // complained about it.
5832 Invalid = true;
5833 continue;
5834 }
5835
5836 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5837 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005838 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005839 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5840 }
5841 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005842 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005843 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005844 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5845 LookupOrdinaryName);
5846 LookupName(R, TUScope, true);
5847
5848 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5849 if (!BuiltinMemCpy) {
5850 // Something went horribly wrong earlier, and we will have complained
5851 // about it.
5852 Invalid = true;
5853 continue;
5854 }
5855
5856 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5857 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005858 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005859 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5860 }
5861
John McCallca0408f2010-08-23 06:44:23 +00005862 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005863 CallArgs.push_back(To.takeAs<Expr>());
5864 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005865 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005866 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005867 if (NeedsCollectableMemCpy)
5868 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005869 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005870 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005871 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005872 else
5873 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005874 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005875 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005876 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005877
Douglas Gregor06a9f362010-05-01 20:49:11 +00005878 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5879 Statements.push_back(Call.takeAs<Expr>());
5880 continue;
5881 }
5882
5883 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005884 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005885 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005886 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005887 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005888 Diag(CurrentLocation, diag::note_member_synthesized_at)
5889 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5890 CopyAssignOperator->setInvalidDecl();
5891 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005892 }
5893
5894 // Success! Record the copy.
5895 Statements.push_back(Copy.takeAs<Stmt>());
5896 }
5897
5898 if (!Invalid) {
5899 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005900 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005901
John McCall60d7b3a2010-08-24 06:29:42 +00005902 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005903 if (Return.isInvalid())
5904 Invalid = true;
5905 else {
5906 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005907
5908 if (Trap.hasErrorOccurred()) {
5909 Diag(CurrentLocation, diag::note_member_synthesized_at)
5910 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5911 Invalid = true;
5912 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005913 }
5914 }
5915
5916 if (Invalid) {
5917 CopyAssignOperator->setInvalidDecl();
5918 return;
5919 }
5920
John McCall60d7b3a2010-08-24 06:29:42 +00005921 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005922 /*isStmtExpr=*/false);
5923 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5924 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005925
5926 if (ASTMutationListener *L = getASTMutationListener()) {
5927 L->CompletedImplicitDefinition(CopyAssignOperator);
5928 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005929}
5930
Douglas Gregor23c94db2010-07-02 17:43:08 +00005931CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5932 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005933 // C++ [class.copy]p4:
5934 // If the class definition does not explicitly declare a copy
5935 // constructor, one is declared implicitly.
5936
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005937 // C++ [class.copy]p5:
5938 // The implicitly-declared copy constructor for a class X will
5939 // have the form
5940 //
5941 // X::X(const X&)
5942 //
5943 // if
5944 bool HasConstCopyConstructor = true;
5945
5946 // -- each direct or virtual base class B of X has a copy
5947 // constructor whose first parameter is of type const B& or
5948 // const volatile B&, and
5949 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5950 BaseEnd = ClassDecl->bases_end();
5951 HasConstCopyConstructor && Base != BaseEnd;
5952 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005953 // Virtual bases are handled below.
5954 if (Base->isVirtual())
5955 continue;
5956
Douglas Gregor22584312010-07-02 23:41:54 +00005957 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005958 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005959 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5960 DeclareImplicitCopyConstructor(BaseClassDecl);
5961
Douglas Gregor598a8542010-07-01 18:27:03 +00005962 HasConstCopyConstructor
5963 = BaseClassDecl->hasConstCopyConstructor(Context);
5964 }
5965
5966 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5967 BaseEnd = ClassDecl->vbases_end();
5968 HasConstCopyConstructor && Base != BaseEnd;
5969 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005970 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005971 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005972 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5973 DeclareImplicitCopyConstructor(BaseClassDecl);
5974
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005975 HasConstCopyConstructor
5976 = BaseClassDecl->hasConstCopyConstructor(Context);
5977 }
5978
5979 // -- for all the nonstatic data members of X that are of a
5980 // class type M (or array thereof), each such class type
5981 // has a copy constructor whose first parameter is of type
5982 // const M& or const volatile M&.
5983 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5984 FieldEnd = ClassDecl->field_end();
5985 HasConstCopyConstructor && Field != FieldEnd;
5986 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005987 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005988 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005989 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005990 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005991 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5992 DeclareImplicitCopyConstructor(FieldClassDecl);
5993
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005994 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005995 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005996 }
5997 }
5998
5999 // Otherwise, the implicitly declared copy constructor will have
6000 // the form
6001 //
6002 // X::X(X&)
6003 QualType ClassType = Context.getTypeDeclType(ClassDecl);
6004 QualType ArgType = ClassType;
6005 if (HasConstCopyConstructor)
6006 ArgType = ArgType.withConst();
6007 ArgType = Context.getLValueReferenceType(ArgType);
6008
Douglas Gregor0d405db2010-07-01 20:59:04 +00006009 // C++ [except.spec]p14:
6010 // An implicitly declared special member function (Clause 12) shall have an
6011 // exception-specification. [...]
6012 ImplicitExceptionSpecification ExceptSpec(Context);
6013 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6014 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6015 BaseEnd = ClassDecl->bases_end();
6016 Base != BaseEnd;
6017 ++Base) {
6018 // Virtual bases are handled below.
6019 if (Base->isVirtual())
6020 continue;
6021
Douglas Gregor22584312010-07-02 23:41:54 +00006022 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006023 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006024 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6025 DeclareImplicitCopyConstructor(BaseClassDecl);
6026
Douglas Gregor0d405db2010-07-01 20:59:04 +00006027 if (CXXConstructorDecl *CopyConstructor
6028 = BaseClassDecl->getCopyConstructor(Context, Quals))
6029 ExceptSpec.CalledDecl(CopyConstructor);
6030 }
6031 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6032 BaseEnd = ClassDecl->vbases_end();
6033 Base != BaseEnd;
6034 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006035 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006036 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006037 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6038 DeclareImplicitCopyConstructor(BaseClassDecl);
6039
Douglas Gregor0d405db2010-07-01 20:59:04 +00006040 if (CXXConstructorDecl *CopyConstructor
6041 = BaseClassDecl->getCopyConstructor(Context, Quals))
6042 ExceptSpec.CalledDecl(CopyConstructor);
6043 }
6044 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6045 FieldEnd = ClassDecl->field_end();
6046 Field != FieldEnd;
6047 ++Field) {
6048 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6049 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006050 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006051 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006052 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6053 DeclareImplicitCopyConstructor(FieldClassDecl);
6054
Douglas Gregor0d405db2010-07-01 20:59:04 +00006055 if (CXXConstructorDecl *CopyConstructor
6056 = FieldClassDecl->getCopyConstructor(Context, Quals))
6057 ExceptSpec.CalledDecl(CopyConstructor);
6058 }
6059 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006060
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006061 // An implicitly-declared copy constructor is an inline public
6062 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00006063 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00006064 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00006065 EPI.NumExceptions = ExceptSpec.size();
6066 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006067 DeclarationName Name
6068 = Context.DeclarationNames.getCXXConstructorName(
6069 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006070 SourceLocation ClassLoc = ClassDecl->getLocation();
6071 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006072 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006073 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006074 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006075 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006076 /*TInfo=*/0,
6077 /*isExplicit=*/false,
6078 /*isInline=*/true,
6079 /*isImplicitlyDeclared=*/true);
6080 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006081 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6082
Douglas Gregor22584312010-07-02 23:41:54 +00006083 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00006084 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6085
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006086 // Add the parameter to the constructor.
6087 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006088 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006089 /*IdentifierInfo=*/0,
6090 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006091 SC_None,
6092 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006093 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00006094 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00006095 PushOnScopeChains(CopyConstructor, S, false);
6096 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006097
6098 return CopyConstructor;
6099}
6100
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006101void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6102 CXXConstructorDecl *CopyConstructor,
6103 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00006104 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00006105 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006106 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006107 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006108
Anders Carlsson63010a72010-04-23 16:24:12 +00006109 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006110 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006111
Douglas Gregor39957dc2010-05-01 15:04:51 +00006112 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006113 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006114
Sean Huntcbb67482011-01-08 20:30:50 +00006115 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006116 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00006117 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006118 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00006119 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006120 } else {
6121 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6122 CopyConstructor->getLocation(),
6123 MultiStmtArg(*this, 0, 0),
6124 /*isStmtExpr=*/false)
6125 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00006126 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006127
6128 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006129
6130 if (ASTMutationListener *L = getASTMutationListener()) {
6131 L->CompletedImplicitDefinition(CopyConstructor);
6132 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006133}
6134
John McCall60d7b3a2010-08-24 06:29:42 +00006135ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006136Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00006137 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00006138 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006139 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006140 unsigned ConstructKind,
6141 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006142 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006143
Douglas Gregor2f599792010-04-02 18:24:57 +00006144 // C++0x [class.copy]p34:
6145 // When certain criteria are met, an implementation is allowed to
6146 // omit the copy/move construction of a class object, even if the
6147 // copy/move constructor and/or destructor for the object have
6148 // side effects. [...]
6149 // - when a temporary class object that has not been bound to a
6150 // reference (12.2) would be copied/moved to a class object
6151 // with the same cv-unqualified type, the copy/move operation
6152 // can be omitted by constructing the temporary object
6153 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00006154 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00006155 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00006156 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00006157 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006158 }
Mike Stump1eb44332009-09-09 15:08:12 +00006159
6160 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006161 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006162 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006163}
6164
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006165/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6166/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006167ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006168Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6169 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00006170 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006171 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006172 unsigned ConstructKind,
6173 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00006174 unsigned NumExprs = ExprArgs.size();
6175 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006176
Nick Lewycky909a70d2011-03-25 01:44:32 +00006177 for (specific_attr_iterator<NonNullAttr>
6178 i = Constructor->specific_attr_begin<NonNullAttr>(),
6179 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6180 const NonNullAttr *NonNull = *i;
6181 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6182 }
6183
Douglas Gregor7edfb692009-11-23 12:27:39 +00006184 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00006185 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00006186 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00006187 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006188 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6189 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006190}
6191
Mike Stump1eb44332009-09-09 15:08:12 +00006192bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006193 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00006194 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00006195 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00006196 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00006197 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006198 move(Exprs), false, CXXConstructExpr::CK_Complete,
6199 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00006200 if (TempResult.isInvalid())
6201 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006202
Anders Carlssonda3f4e22009-08-25 05:12:04 +00006203 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00006204 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006205 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00006206 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00006207 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00006208
Anders Carlssonfe2de492009-08-25 05:18:00 +00006209 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00006210}
6211
John McCall68c6c9a2010-02-02 09:10:11 +00006212void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006213 if (VD->isInvalidDecl()) return;
6214
John McCall68c6c9a2010-02-02 09:10:11 +00006215 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006216 if (ClassDecl->isInvalidDecl()) return;
6217 if (ClassDecl->hasTrivialDestructor()) return;
6218 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00006219
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006220 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6221 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6222 CheckDestructorAccess(VD->getLocation(), Destructor,
6223 PDiag(diag::err_access_dtor_var)
6224 << VD->getDeclName()
6225 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00006226
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006227 if (!VD->hasGlobalStorage()) return;
6228
6229 // Emit warning for non-trivial dtor in global scope (a real global,
6230 // class-static, function-static).
6231 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6232
6233 // TODO: this should be re-enabled for static locals by !CXAAtExit
6234 if (!VD->isStaticLocal())
6235 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006236}
6237
Mike Stump1eb44332009-09-09 15:08:12 +00006238/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006239/// ActOnDeclarator, when a C++ direct initializer is present.
6240/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00006241void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006242 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006243 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00006244 SourceLocation RParenLoc,
6245 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00006246 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006247
6248 // If there is no declaration, there was an error parsing it. Just ignore
6249 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006250 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006251 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006252
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006253 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6254 if (!VDecl) {
6255 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6256 RealDecl->setInvalidDecl();
6257 return;
6258 }
6259
Richard Smith34b41d92011-02-20 03:19:35 +00006260 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6261 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00006262 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6263 if (Exprs.size() > 1) {
6264 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6265 diag::err_auto_var_init_multiple_expressions)
6266 << VDecl->getDeclName() << VDecl->getType()
6267 << VDecl->getSourceRange();
6268 RealDecl->setInvalidDecl();
6269 return;
6270 }
6271
6272 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00006273 TypeSourceInfo *DeducedType = 0;
6274 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00006275 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6276 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6277 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00006278 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006279 RealDecl->setInvalidDecl();
6280 return;
6281 }
Richard Smitha085da82011-03-17 16:11:59 +00006282 VDecl->setTypeSourceInfo(DeducedType);
6283 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00006284
6285 // If this is a redeclaration, check that the type we just deduced matches
6286 // the previously declared type.
6287 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6288 MergeVarDeclTypes(VDecl, Old);
6289 }
6290
Douglas Gregor83ddad32009-08-26 21:14:46 +00006291 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006292 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006293 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6294 //
6295 // Clients that want to distinguish between the two forms, can check for
6296 // direct initializer using VarDecl::hasCXXDirectInitializer().
6297 // A major benefit is that clients that don't particularly care about which
6298 // exactly form was it (like the CodeGen) can handle both cases without
6299 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006300
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006301 // C++ 8.5p11:
6302 // The form of initialization (using parentheses or '=') is generally
6303 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006304 // class type.
6305
Douglas Gregor4dffad62010-02-11 22:55:30 +00006306 if (!VDecl->getType()->isDependentType() &&
6307 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00006308 diag::err_typecheck_decl_incomplete_type)) {
6309 VDecl->setInvalidDecl();
6310 return;
6311 }
6312
Douglas Gregor90f93822009-12-22 22:17:25 +00006313 // The variable can not have an abstract class type.
6314 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6315 diag::err_abstract_type_in_decl,
6316 AbstractVariableType))
6317 VDecl->setInvalidDecl();
6318
Sebastian Redl31310a22010-02-01 20:16:42 +00006319 const VarDecl *Def;
6320 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006321 Diag(VDecl->getLocation(), diag::err_redefinition)
6322 << VDecl->getDeclName();
6323 Diag(Def->getLocation(), diag::note_previous_definition);
6324 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006325 return;
6326 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006327
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006328 // C++ [class.static.data]p4
6329 // If a static data member is of const integral or const
6330 // enumeration type, its declaration in the class definition can
6331 // specify a constant-initializer which shall be an integral
6332 // constant expression (5.19). In that case, the member can appear
6333 // in integral constant expressions. The member shall still be
6334 // defined in a namespace scope if it is used in the program and the
6335 // namespace scope definition shall not contain an initializer.
6336 //
6337 // We already performed a redefinition check above, but for static
6338 // data members we also need to check whether there was an in-class
6339 // declaration with an initializer.
6340 const VarDecl* PrevInit = 0;
6341 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6342 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6343 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6344 return;
6345 }
6346
Douglas Gregora31040f2010-12-16 01:31:22 +00006347 bool IsDependent = false;
6348 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6349 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6350 VDecl->setInvalidDecl();
6351 return;
6352 }
6353
6354 if (Exprs.get()[I]->isTypeDependent())
6355 IsDependent = true;
6356 }
6357
Douglas Gregor4dffad62010-02-11 22:55:30 +00006358 // If either the declaration has a dependent type or if any of the
6359 // expressions is type-dependent, we represent the initialization
6360 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006361 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006362 // Let clients know that initialization was done with a direct initializer.
6363 VDecl->setCXXDirectInitializer(true);
6364
6365 // Store the initialization expressions as a ParenListExpr.
6366 unsigned NumExprs = Exprs.size();
6367 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6368 (Expr **)Exprs.release(),
6369 NumExprs, RParenLoc));
6370 return;
6371 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006372
6373 // Capture the variable that is being initialized and the style of
6374 // initialization.
6375 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6376
6377 // FIXME: Poor source location information.
6378 InitializationKind Kind
6379 = InitializationKind::CreateDirect(VDecl->getLocation(),
6380 LParenLoc, RParenLoc);
6381
6382 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006383 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006384 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006385 if (Result.isInvalid()) {
6386 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006387 return;
6388 }
John McCallb4eb64d2010-10-08 02:01:28 +00006389
6390 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006391
Douglas Gregor53c374f2010-12-07 00:41:46 +00006392 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006393 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006394 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006395
John McCall2998d6b2011-01-19 11:48:09 +00006396 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006397}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006398
Douglas Gregor39da0b82009-09-09 23:08:42 +00006399/// \brief Given a constructor and the set of arguments provided for the
6400/// constructor, convert the arguments and add any required default arguments
6401/// to form a proper call to this constructor.
6402///
6403/// \returns true if an error occurred, false otherwise.
6404bool
6405Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6406 MultiExprArg ArgsPtr,
6407 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006408 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006409 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6410 unsigned NumArgs = ArgsPtr.size();
6411 Expr **Args = (Expr **)ArgsPtr.get();
6412
6413 const FunctionProtoType *Proto
6414 = Constructor->getType()->getAs<FunctionProtoType>();
6415 assert(Proto && "Constructor without a prototype?");
6416 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006417
6418 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006419 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006420 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006421 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006422 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006423
6424 VariadicCallType CallType =
6425 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6426 llvm::SmallVector<Expr *, 8> AllArgs;
6427 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6428 Proto, 0, Args, NumArgs, AllArgs,
6429 CallType);
6430 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6431 ConvertedArgs.push_back(AllArgs[i]);
6432 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006433}
6434
Anders Carlsson20d45d22009-12-12 00:32:00 +00006435static inline bool
6436CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6437 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006438 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006439 if (isa<NamespaceDecl>(DC)) {
6440 return SemaRef.Diag(FnDecl->getLocation(),
6441 diag::err_operator_new_delete_declared_in_namespace)
6442 << FnDecl->getDeclName();
6443 }
6444
6445 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006446 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006447 return SemaRef.Diag(FnDecl->getLocation(),
6448 diag::err_operator_new_delete_declared_static)
6449 << FnDecl->getDeclName();
6450 }
6451
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006452 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006453}
6454
Anders Carlsson156c78e2009-12-13 17:53:43 +00006455static inline bool
6456CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6457 CanQualType ExpectedResultType,
6458 CanQualType ExpectedFirstParamType,
6459 unsigned DependentParamTypeDiag,
6460 unsigned InvalidParamTypeDiag) {
6461 QualType ResultType =
6462 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6463
6464 // Check that the result type is not dependent.
6465 if (ResultType->isDependentType())
6466 return SemaRef.Diag(FnDecl->getLocation(),
6467 diag::err_operator_new_delete_dependent_result_type)
6468 << FnDecl->getDeclName() << ExpectedResultType;
6469
6470 // Check that the result type is what we expect.
6471 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6472 return SemaRef.Diag(FnDecl->getLocation(),
6473 diag::err_operator_new_delete_invalid_result_type)
6474 << FnDecl->getDeclName() << ExpectedResultType;
6475
6476 // A function template must have at least 2 parameters.
6477 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6478 return SemaRef.Diag(FnDecl->getLocation(),
6479 diag::err_operator_new_delete_template_too_few_parameters)
6480 << FnDecl->getDeclName();
6481
6482 // The function decl must have at least 1 parameter.
6483 if (FnDecl->getNumParams() == 0)
6484 return SemaRef.Diag(FnDecl->getLocation(),
6485 diag::err_operator_new_delete_too_few_parameters)
6486 << FnDecl->getDeclName();
6487
6488 // Check the the first parameter type is not dependent.
6489 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6490 if (FirstParamType->isDependentType())
6491 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6492 << FnDecl->getDeclName() << ExpectedFirstParamType;
6493
6494 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006495 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006496 ExpectedFirstParamType)
6497 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6498 << FnDecl->getDeclName() << ExpectedFirstParamType;
6499
6500 return false;
6501}
6502
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006503static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006504CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006505 // C++ [basic.stc.dynamic.allocation]p1:
6506 // A program is ill-formed if an allocation function is declared in a
6507 // namespace scope other than global scope or declared static in global
6508 // scope.
6509 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6510 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006511
6512 CanQualType SizeTy =
6513 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6514
6515 // C++ [basic.stc.dynamic.allocation]p1:
6516 // The return type shall be void*. The first parameter shall have type
6517 // std::size_t.
6518 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6519 SizeTy,
6520 diag::err_operator_new_dependent_param_type,
6521 diag::err_operator_new_param_type))
6522 return true;
6523
6524 // C++ [basic.stc.dynamic.allocation]p1:
6525 // The first parameter shall not have an associated default argument.
6526 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006527 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006528 diag::err_operator_new_default_arg)
6529 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6530
6531 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006532}
6533
6534static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006535CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6536 // C++ [basic.stc.dynamic.deallocation]p1:
6537 // A program is ill-formed if deallocation functions are declared in a
6538 // namespace scope other than global scope or declared static in global
6539 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006540 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6541 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006542
6543 // C++ [basic.stc.dynamic.deallocation]p2:
6544 // Each deallocation function shall return void and its first parameter
6545 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006546 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6547 SemaRef.Context.VoidPtrTy,
6548 diag::err_operator_delete_dependent_param_type,
6549 diag::err_operator_delete_param_type))
6550 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006551
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006552 return false;
6553}
6554
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006555/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6556/// of this overloaded operator is well-formed. If so, returns false;
6557/// otherwise, emits appropriate diagnostics and returns true.
6558bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006559 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006560 "Expected an overloaded operator declaration");
6561
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006562 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6563
Mike Stump1eb44332009-09-09 15:08:12 +00006564 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006565 // The allocation and deallocation functions, operator new,
6566 // operator new[], operator delete and operator delete[], are
6567 // described completely in 3.7.3. The attributes and restrictions
6568 // found in the rest of this subclause do not apply to them unless
6569 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006570 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006571 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006572
Anders Carlssona3ccda52009-12-12 00:26:23 +00006573 if (Op == OO_New || Op == OO_Array_New)
6574 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006575
6576 // C++ [over.oper]p6:
6577 // An operator function shall either be a non-static member
6578 // function or be a non-member function and have at least one
6579 // parameter whose type is a class, a reference to a class, an
6580 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006581 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6582 if (MethodDecl->isStatic())
6583 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006584 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006585 } else {
6586 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006587 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6588 ParamEnd = FnDecl->param_end();
6589 Param != ParamEnd; ++Param) {
6590 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006591 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6592 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006593 ClassOrEnumParam = true;
6594 break;
6595 }
6596 }
6597
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006598 if (!ClassOrEnumParam)
6599 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006600 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006601 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006602 }
6603
6604 // C++ [over.oper]p8:
6605 // An operator function cannot have default arguments (8.3.6),
6606 // except where explicitly stated below.
6607 //
Mike Stump1eb44332009-09-09 15:08:12 +00006608 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006609 // (C++ [over.call]p1).
6610 if (Op != OO_Call) {
6611 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6612 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006613 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006614 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006615 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006616 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006617 }
6618 }
6619
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006620 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6621 { false, false, false }
6622#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6623 , { Unary, Binary, MemberOnly }
6624#include "clang/Basic/OperatorKinds.def"
6625 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006626
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006627 bool CanBeUnaryOperator = OperatorUses[Op][0];
6628 bool CanBeBinaryOperator = OperatorUses[Op][1];
6629 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006630
6631 // C++ [over.oper]p8:
6632 // [...] Operator functions cannot have more or fewer parameters
6633 // than the number required for the corresponding operator, as
6634 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006635 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006636 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006637 if (Op != OO_Call &&
6638 ((NumParams == 1 && !CanBeUnaryOperator) ||
6639 (NumParams == 2 && !CanBeBinaryOperator) ||
6640 (NumParams < 1) || (NumParams > 2))) {
6641 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006642 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006643 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006644 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006645 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006646 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006647 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006648 assert(CanBeBinaryOperator &&
6649 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006650 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006651 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006652
Chris Lattner416e46f2008-11-21 07:57:12 +00006653 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006654 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006655 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006656
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006657 // Overloaded operators other than operator() cannot be variadic.
6658 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006659 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006660 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006661 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006662 }
6663
6664 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006665 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6666 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006667 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006668 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006669 }
6670
6671 // C++ [over.inc]p1:
6672 // The user-defined function called operator++ implements the
6673 // prefix and postfix ++ operator. If this function is a member
6674 // function with no parameters, or a non-member function with one
6675 // parameter of class or enumeration type, it defines the prefix
6676 // increment operator ++ for objects of that type. If the function
6677 // is a member function with one parameter (which shall be of type
6678 // int) or a non-member function with two parameters (the second
6679 // of which shall be of type int), it defines the postfix
6680 // increment operator ++ for objects of that type.
6681 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6682 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6683 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006684 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006685 ParamIsInt = BT->getKind() == BuiltinType::Int;
6686
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006687 if (!ParamIsInt)
6688 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006689 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006690 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006691 }
6692
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006693 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006694}
Chris Lattner5a003a42008-12-17 07:09:26 +00006695
Sean Hunta6c058d2010-01-13 09:01:02 +00006696/// CheckLiteralOperatorDeclaration - Check whether the declaration
6697/// of this literal operator function is well-formed. If so, returns
6698/// false; otherwise, emits appropriate diagnostics and returns true.
6699bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6700 DeclContext *DC = FnDecl->getDeclContext();
6701 Decl::Kind Kind = DC->getDeclKind();
6702 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6703 Kind != Decl::LinkageSpec) {
6704 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6705 << FnDecl->getDeclName();
6706 return true;
6707 }
6708
6709 bool Valid = false;
6710
Sean Hunt216c2782010-04-07 23:11:06 +00006711 // template <char...> type operator "" name() is the only valid template
6712 // signature, and the only valid signature with no parameters.
6713 if (FnDecl->param_size() == 0) {
6714 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6715 // Must have only one template parameter
6716 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6717 if (Params->size() == 1) {
6718 NonTypeTemplateParmDecl *PmDecl =
6719 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006720
Sean Hunt216c2782010-04-07 23:11:06 +00006721 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006722 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6723 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6724 Valid = true;
6725 }
6726 }
6727 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006728 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006729 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6730
Sean Hunta6c058d2010-01-13 09:01:02 +00006731 QualType T = (*Param)->getType();
6732
Sean Hunt30019c02010-04-07 22:57:35 +00006733 // unsigned long long int, long double, and any character type are allowed
6734 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006735 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6736 Context.hasSameType(T, Context.LongDoubleTy) ||
6737 Context.hasSameType(T, Context.CharTy) ||
6738 Context.hasSameType(T, Context.WCharTy) ||
6739 Context.hasSameType(T, Context.Char16Ty) ||
6740 Context.hasSameType(T, Context.Char32Ty)) {
6741 if (++Param == FnDecl->param_end())
6742 Valid = true;
6743 goto FinishedParams;
6744 }
6745
Sean Hunt30019c02010-04-07 22:57:35 +00006746 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006747 const PointerType *PT = T->getAs<PointerType>();
6748 if (!PT)
6749 goto FinishedParams;
6750 T = PT->getPointeeType();
6751 if (!T.isConstQualified())
6752 goto FinishedParams;
6753 T = T.getUnqualifiedType();
6754
6755 // Move on to the second parameter;
6756 ++Param;
6757
6758 // If there is no second parameter, the first must be a const char *
6759 if (Param == FnDecl->param_end()) {
6760 if (Context.hasSameType(T, Context.CharTy))
6761 Valid = true;
6762 goto FinishedParams;
6763 }
6764
6765 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6766 // are allowed as the first parameter to a two-parameter function
6767 if (!(Context.hasSameType(T, Context.CharTy) ||
6768 Context.hasSameType(T, Context.WCharTy) ||
6769 Context.hasSameType(T, Context.Char16Ty) ||
6770 Context.hasSameType(T, Context.Char32Ty)))
6771 goto FinishedParams;
6772
6773 // The second and final parameter must be an std::size_t
6774 T = (*Param)->getType().getUnqualifiedType();
6775 if (Context.hasSameType(T, Context.getSizeType()) &&
6776 ++Param == FnDecl->param_end())
6777 Valid = true;
6778 }
6779
6780 // FIXME: This diagnostic is absolutely terrible.
6781FinishedParams:
6782 if (!Valid) {
6783 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6784 << FnDecl->getDeclName();
6785 return true;
6786 }
6787
6788 return false;
6789}
6790
Douglas Gregor074149e2009-01-05 19:45:36 +00006791/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6792/// linkage specification, including the language and (if present)
6793/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6794/// the location of the language string literal, which is provided
6795/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6796/// the '{' brace. Otherwise, this linkage specification does not
6797/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006798Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6799 SourceLocation LangLoc,
6800 llvm::StringRef Lang,
6801 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006802 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006803 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006804 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006805 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006806 Language = LinkageSpecDecl::lang_cxx;
6807 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006808 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006809 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006810 }
Mike Stump1eb44332009-09-09 15:08:12 +00006811
Chris Lattnercc98eac2008-12-17 07:13:27 +00006812 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006813
Douglas Gregor074149e2009-01-05 19:45:36 +00006814 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006815 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006816 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006817 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006818 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006819}
6820
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006821/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006822/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6823/// valid, it's the position of the closing '}' brace in a linkage
6824/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006825Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006826 Decl *LinkageSpec,
6827 SourceLocation RBraceLoc) {
6828 if (LinkageSpec) {
6829 if (RBraceLoc.isValid()) {
6830 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6831 LSDecl->setRBraceLoc(RBraceLoc);
6832 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006833 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006834 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006835 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006836}
6837
Douglas Gregord308e622009-05-18 20:51:54 +00006838/// \brief Perform semantic analysis for the variable declaration that
6839/// occurs within a C++ catch clause, returning the newly-created
6840/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006841VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006842 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006843 SourceLocation StartLoc,
6844 SourceLocation Loc,
6845 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00006846 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006847 QualType ExDeclType = TInfo->getType();
6848
Sebastian Redl4b07b292008-12-22 19:15:10 +00006849 // Arrays and functions decay.
6850 if (ExDeclType->isArrayType())
6851 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6852 else if (ExDeclType->isFunctionType())
6853 ExDeclType = Context.getPointerType(ExDeclType);
6854
6855 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6856 // The exception-declaration shall not denote a pointer or reference to an
6857 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006858 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006859 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006860 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006861 Invalid = true;
6862 }
Douglas Gregord308e622009-05-18 20:51:54 +00006863
Douglas Gregora2762912010-03-08 01:47:36 +00006864 // GCC allows catching pointers and references to incomplete types
6865 // as an extension; so do we, but we warn by default.
6866
Sebastian Redl4b07b292008-12-22 19:15:10 +00006867 QualType BaseType = ExDeclType;
6868 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006869 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006870 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006871 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006872 BaseType = Ptr->getPointeeType();
6873 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006874 DK = diag::ext_catch_incomplete_ptr;
6875 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006876 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006877 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006878 BaseType = Ref->getPointeeType();
6879 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006880 DK = diag::ext_catch_incomplete_ref;
6881 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006882 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006883 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006884 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6885 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006886 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006887
Mike Stump1eb44332009-09-09 15:08:12 +00006888 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006889 RequireNonAbstractType(Loc, ExDeclType,
6890 diag::err_abstract_type_in_decl,
6891 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006892 Invalid = true;
6893
John McCall5a180392010-07-24 00:37:23 +00006894 // Only the non-fragile NeXT runtime currently supports C++ catches
6895 // of ObjC types, and no runtime supports catching ObjC types by value.
6896 if (!Invalid && getLangOptions().ObjC1) {
6897 QualType T = ExDeclType;
6898 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6899 T = RT->getPointeeType();
6900
6901 if (T->isObjCObjectType()) {
6902 Diag(Loc, diag::err_objc_object_catch);
6903 Invalid = true;
6904 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00006905 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00006906 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6907 Invalid = true;
6908 }
6909 }
6910 }
6911
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006912 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6913 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006914 ExDecl->setExceptionVariable(true);
6915
Douglas Gregor6d182892010-03-05 23:38:39 +00006916 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00006917 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00006918 // C++ [except.handle]p16:
6919 // The object declared in an exception-declaration or, if the
6920 // exception-declaration does not specify a name, a temporary (12.2) is
6921 // copy-initialized (8.5) from the exception object. [...]
6922 // The object is destroyed when the handler exits, after the destruction
6923 // of any automatic objects initialized within the handler.
6924 //
6925 // We just pretend to initialize the object with itself, then make sure
6926 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00006927 QualType initType = ExDeclType;
6928
6929 InitializedEntity entity =
6930 InitializedEntity::InitializeVariable(ExDecl);
6931 InitializationKind initKind =
6932 InitializationKind::CreateCopy(Loc, SourceLocation());
6933
6934 Expr *opaqueValue =
6935 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6936 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6937 ExprResult result = sequence.Perform(*this, entity, initKind,
6938 MultiExprArg(&opaqueValue, 1));
6939 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00006940 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00006941 else {
6942 // If the constructor used was non-trivial, set this as the
6943 // "initializer".
6944 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6945 if (!construct->getConstructor()->isTrivial()) {
6946 Expr *init = MaybeCreateExprWithCleanups(construct);
6947 ExDecl->setInit(init);
6948 }
6949
6950 // And make sure it's destructable.
6951 FinalizeVarWithDestructor(ExDecl, recordType);
6952 }
Douglas Gregor6d182892010-03-05 23:38:39 +00006953 }
6954 }
6955
Douglas Gregord308e622009-05-18 20:51:54 +00006956 if (Invalid)
6957 ExDecl->setInvalidDecl();
6958
6959 return ExDecl;
6960}
6961
6962/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6963/// handler.
John McCalld226f652010-08-21 09:40:31 +00006964Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006965 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006966 bool Invalid = D.isInvalidType();
6967
6968 // Check for unexpanded parameter packs.
6969 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6970 UPPC_ExceptionType)) {
6971 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6972 D.getIdentifierLoc());
6973 Invalid = true;
6974 }
6975
Sebastian Redl4b07b292008-12-22 19:15:10 +00006976 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006977 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006978 LookupOrdinaryName,
6979 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006980 // The scope should be freshly made just for us. There is just no way
6981 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006982 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006983 if (PrevDecl->isTemplateParameter()) {
6984 // Maybe we will complain about the shadowed template parameter.
6985 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006986 }
6987 }
6988
Chris Lattnereaaebc72009-04-25 08:06:05 +00006989 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006990 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6991 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006992 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006993 }
6994
Douglas Gregor83cb9422010-09-09 17:09:21 +00006995 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006996 D.getSourceRange().getBegin(),
6997 D.getIdentifierLoc(),
6998 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00006999 if (Invalid)
7000 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00007001
Sebastian Redl4b07b292008-12-22 19:15:10 +00007002 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00007003 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00007004 PushOnScopeChains(ExDecl, S);
7005 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007006 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007007
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007008 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00007009 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007010}
Anders Carlssonfb311762009-03-14 00:25:26 +00007011
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007012Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007013 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007014 Expr *AssertMessageExpr_,
7015 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00007016 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00007017
Anders Carlssonc3082412009-03-14 00:33:21 +00007018 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7019 llvm::APSInt Value(32);
7020 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007021 Diag(StaticAssertLoc,
7022 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00007023 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007024 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00007025 }
Anders Carlssonfb311762009-03-14 00:25:26 +00007026
Anders Carlssonc3082412009-03-14 00:33:21 +00007027 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007028 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00007029 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00007030 }
7031 }
Mike Stump1eb44332009-09-09 15:08:12 +00007032
Douglas Gregor399ad972010-12-15 23:55:21 +00007033 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7034 return 0;
7035
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007036 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7037 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00007038
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007039 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00007040 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00007041}
Sebastian Redl50de12f2009-03-24 22:27:57 +00007042
Douglas Gregor1d869352010-04-07 16:53:43 +00007043/// \brief Perform semantic analysis of the given friend type declaration.
7044///
7045/// \returns A friend declaration that.
7046FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7047 TypeSourceInfo *TSInfo) {
7048 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7049
7050 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00007051 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00007052
Douglas Gregor06245bf2010-04-07 17:57:12 +00007053 if (!getLangOptions().CPlusPlus0x) {
7054 // C++03 [class.friend]p2:
7055 // An elaborated-type-specifier shall be used in a friend declaration
7056 // for a class.*
7057 //
7058 // * The class-key of the elaborated-type-specifier is required.
7059 if (!ActiveTemplateInstantiations.empty()) {
7060 // Do not complain about the form of friend template types during
7061 // template instantiation; we will already have complained when the
7062 // template was declared.
7063 } else if (!T->isElaboratedTypeSpecifier()) {
7064 // If we evaluated the type to a record type, suggest putting
7065 // a tag in front.
7066 if (const RecordType *RT = T->getAs<RecordType>()) {
7067 RecordDecl *RD = RT->getDecl();
7068
7069 std::string InsertionText = std::string(" ") + RD->getKindName();
7070
7071 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7072 << (unsigned) RD->getTagKind()
7073 << T
7074 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7075 InsertionText);
7076 } else {
7077 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7078 << T
7079 << SourceRange(FriendLoc, TypeRange.getEnd());
7080 }
7081 } else if (T->getAs<EnumType>()) {
7082 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00007083 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00007084 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00007085 }
7086 }
7087
Douglas Gregor06245bf2010-04-07 17:57:12 +00007088 // C++0x [class.friend]p3:
7089 // If the type specifier in a friend declaration designates a (possibly
7090 // cv-qualified) class type, that class is declared as a friend; otherwise,
7091 // the friend declaration is ignored.
7092
7093 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7094 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00007095
7096 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7097}
7098
John McCall9a34edb2010-10-19 01:40:49 +00007099/// Handle a friend tag declaration where the scope specifier was
7100/// templated.
7101Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7102 unsigned TagSpec, SourceLocation TagLoc,
7103 CXXScopeSpec &SS,
7104 IdentifierInfo *Name, SourceLocation NameLoc,
7105 AttributeList *Attr,
7106 MultiTemplateParamsArg TempParamLists) {
7107 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7108
7109 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00007110 bool Invalid = false;
7111
7112 if (TemplateParameterList *TemplateParams
7113 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7114 TempParamLists.get(),
7115 TempParamLists.size(),
7116 /*friend*/ true,
7117 isExplicitSpecialization,
7118 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00007119 if (TemplateParams->size() > 0) {
7120 // This is a declaration of a class template.
7121 if (Invalid)
7122 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007123
John McCall9a34edb2010-10-19 01:40:49 +00007124 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7125 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007126 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007127 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007128 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00007129 } else {
7130 // The "template<>" header is extraneous.
7131 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7132 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7133 isExplicitSpecialization = true;
7134 }
7135 }
7136
7137 if (Invalid) return 0;
7138
7139 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7140
7141 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007142 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00007143 if (TempParamLists.get()[I]->size()) {
7144 isAllExplicitSpecializations = false;
7145 break;
7146 }
7147 }
7148
7149 // FIXME: don't ignore attributes.
7150
7151 // If it's explicit specializations all the way down, just forget
7152 // about the template header and build an appropriate non-templated
7153 // friend. TODO: for source fidelity, remember the headers.
7154 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00007155 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00007156 ElaboratedTypeKeyword Keyword
7157 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007158 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00007159 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007160 if (T.isNull())
7161 return 0;
7162
7163 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7164 if (isa<DependentNameType>(T)) {
7165 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7166 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007167 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007168 TL.setNameLoc(NameLoc);
7169 } else {
7170 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7171 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007172 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007173 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7174 }
7175
7176 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7177 TSI, FriendLoc);
7178 Friend->setAccess(AS_public);
7179 CurContext->addDecl(Friend);
7180 return Friend;
7181 }
7182
7183 // Handle the case of a templated-scope friend class. e.g.
7184 // template <class T> class A<T>::B;
7185 // FIXME: we don't support these right now.
7186 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7187 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7188 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7189 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7190 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007191 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00007192 TL.setNameLoc(NameLoc);
7193
7194 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7195 TSI, FriendLoc);
7196 Friend->setAccess(AS_public);
7197 Friend->setUnsupportedFriend(true);
7198 CurContext->addDecl(Friend);
7199 return Friend;
7200}
7201
7202
John McCalldd4a3b02009-09-16 22:47:08 +00007203/// Handle a friend type declaration. This works in tandem with
7204/// ActOnTag.
7205///
7206/// Notes on friend class templates:
7207///
7208/// We generally treat friend class declarations as if they were
7209/// declaring a class. So, for example, the elaborated type specifier
7210/// in a friend declaration is required to obey the restrictions of a
7211/// class-head (i.e. no typedefs in the scope chain), template
7212/// parameters are required to match up with simple template-ids, &c.
7213/// However, unlike when declaring a template specialization, it's
7214/// okay to refer to a template specialization without an empty
7215/// template parameter declaration, e.g.
7216/// friend class A<T>::B<unsigned>;
7217/// We permit this as a special case; if there are any template
7218/// parameters present at all, require proper matching, i.e.
7219/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00007220Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00007221 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00007222 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00007223
7224 assert(DS.isFriendSpecified());
7225 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7226
John McCalldd4a3b02009-09-16 22:47:08 +00007227 // Try to convert the decl specifier to a type. This works for
7228 // friend templates because ActOnTag never produces a ClassTemplateDecl
7229 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00007230 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00007231 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7232 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00007233 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00007234 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007235
Douglas Gregor6ccab972010-12-16 01:14:37 +00007236 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7237 return 0;
7238
John McCalldd4a3b02009-09-16 22:47:08 +00007239 // This is definitely an error in C++98. It's probably meant to
7240 // be forbidden in C++0x, too, but the specification is just
7241 // poorly written.
7242 //
7243 // The problem is with declarations like the following:
7244 // template <T> friend A<T>::foo;
7245 // where deciding whether a class C is a friend or not now hinges
7246 // on whether there exists an instantiation of A that causes
7247 // 'foo' to equal C. There are restrictions on class-heads
7248 // (which we declare (by fiat) elaborated friend declarations to
7249 // be) that makes this tractable.
7250 //
7251 // FIXME: handle "template <> friend class A<T>;", which
7252 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00007253 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00007254 Diag(Loc, diag::err_tagless_friend_type_template)
7255 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007256 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00007257 }
Douglas Gregor1d869352010-04-07 16:53:43 +00007258
John McCall02cace72009-08-28 07:59:38 +00007259 // C++98 [class.friend]p1: A friend of a class is a function
7260 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00007261 // This is fixed in DR77, which just barely didn't make the C++03
7262 // deadline. It's also a very silly restriction that seriously
7263 // affects inner classes and which nobody else seems to implement;
7264 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00007265 //
7266 // But note that we could warn about it: it's always useless to
7267 // friend one of your own members (it's not, however, worthless to
7268 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00007269
John McCalldd4a3b02009-09-16 22:47:08 +00007270 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00007271 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00007272 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00007273 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00007274 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00007275 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00007276 DS.getFriendSpecLoc());
7277 else
Douglas Gregor1d869352010-04-07 16:53:43 +00007278 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7279
7280 if (!D)
John McCalld226f652010-08-21 09:40:31 +00007281 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00007282
John McCalldd4a3b02009-09-16 22:47:08 +00007283 D->setAccess(AS_public);
7284 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00007285
John McCalld226f652010-08-21 09:40:31 +00007286 return D;
John McCall02cace72009-08-28 07:59:38 +00007287}
7288
John McCall337ec3d2010-10-12 23:13:28 +00007289Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7290 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00007291 const DeclSpec &DS = D.getDeclSpec();
7292
7293 assert(DS.isFriendSpecified());
7294 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7295
7296 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00007297 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7298 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00007299
7300 // C++ [class.friend]p1
7301 // A friend of a class is a function or class....
7302 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00007303 // It *doesn't* see through dependent types, which is correct
7304 // according to [temp.arg.type]p3:
7305 // If a declaration acquires a function type through a
7306 // type dependent on a template-parameter and this causes
7307 // a declaration that does not use the syntactic form of a
7308 // function declarator to have a function type, the program
7309 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00007310 if (!T->isFunctionType()) {
7311 Diag(Loc, diag::err_unexpected_friend);
7312
7313 // It might be worthwhile to try to recover by creating an
7314 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00007315 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007316 }
7317
7318 // C++ [namespace.memdef]p3
7319 // - If a friend declaration in a non-local class first declares a
7320 // class or function, the friend class or function is a member
7321 // of the innermost enclosing namespace.
7322 // - The name of the friend is not found by simple name lookup
7323 // until a matching declaration is provided in that namespace
7324 // scope (either before or after the class declaration granting
7325 // friendship).
7326 // - If a friend function is called, its name may be found by the
7327 // name lookup that considers functions from namespaces and
7328 // classes associated with the types of the function arguments.
7329 // - When looking for a prior declaration of a class or a function
7330 // declared as a friend, scopes outside the innermost enclosing
7331 // namespace scope are not considered.
7332
John McCall337ec3d2010-10-12 23:13:28 +00007333 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007334 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7335 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007336 assert(Name);
7337
Douglas Gregor6ccab972010-12-16 01:14:37 +00007338 // Check for unexpanded parameter packs.
7339 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7340 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7341 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7342 return 0;
7343
John McCall67d1a672009-08-06 02:15:43 +00007344 // The context we found the declaration in, or in which we should
7345 // create the declaration.
7346 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007347 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007348 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007349 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007350
John McCall337ec3d2010-10-12 23:13:28 +00007351 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007352
John McCall337ec3d2010-10-12 23:13:28 +00007353 // There are four cases here.
7354 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007355 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007356 // there as appropriate.
7357 // Recover from invalid scope qualifiers as if they just weren't there.
7358 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007359 // C++0x [namespace.memdef]p3:
7360 // If the name in a friend declaration is neither qualified nor
7361 // a template-id and the declaration is a function or an
7362 // elaborated-type-specifier, the lookup to determine whether
7363 // the entity has been previously declared shall not consider
7364 // any scopes outside the innermost enclosing namespace.
7365 // C++0x [class.friend]p11:
7366 // If a friend declaration appears in a local class and the name
7367 // specified is an unqualified name, a prior declaration is
7368 // looked up without considering scopes that are outside the
7369 // innermost enclosing non-class scope. For a friend function
7370 // declaration, if there is no prior declaration, the program is
7371 // ill-formed.
7372 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007373 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007374
John McCall29ae6e52010-10-13 05:45:15 +00007375 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007376 DC = CurContext;
7377 while (true) {
7378 // Skip class contexts. If someone can cite chapter and verse
7379 // for this behavior, that would be nice --- it's what GCC and
7380 // EDG do, and it seems like a reasonable intent, but the spec
7381 // really only says that checks for unqualified existing
7382 // declarations should stop at the nearest enclosing namespace,
7383 // not that they should only consider the nearest enclosing
7384 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007385 while (DC->isRecord())
7386 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007387
John McCall68263142009-11-18 22:49:29 +00007388 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007389
7390 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007391 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007392 break;
John McCall29ae6e52010-10-13 05:45:15 +00007393
John McCall8a407372010-10-14 22:22:28 +00007394 if (isTemplateId) {
7395 if (isa<TranslationUnitDecl>(DC)) break;
7396 } else {
7397 if (DC->isFileContext()) break;
7398 }
John McCall67d1a672009-08-06 02:15:43 +00007399 DC = DC->getParent();
7400 }
7401
7402 // C++ [class.friend]p1: A friend of a class is a function or
7403 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007404 // C++0x changes this for both friend types and functions.
7405 // Most C++ 98 compilers do seem to give an error here, so
7406 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007407 if (!Previous.empty() && DC->Equals(CurContext)
7408 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007409 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007410
John McCall380aaa42010-10-13 06:22:15 +00007411 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007412
John McCall337ec3d2010-10-12 23:13:28 +00007413 // - There's a non-dependent scope specifier, in which case we
7414 // compute it and do a previous lookup there for a function
7415 // or function template.
7416 } else if (!SS.getScopeRep()->isDependent()) {
7417 DC = computeDeclContext(SS);
7418 if (!DC) return 0;
7419
7420 if (RequireCompleteDeclContext(SS, DC)) return 0;
7421
7422 LookupQualifiedName(Previous, DC);
7423
7424 // Ignore things found implicitly in the wrong scope.
7425 // TODO: better diagnostics for this case. Suggesting the right
7426 // qualified scope would be nice...
7427 LookupResult::Filter F = Previous.makeFilter();
7428 while (F.hasNext()) {
7429 NamedDecl *D = F.next();
7430 if (!DC->InEnclosingNamespaceSetOf(
7431 D->getDeclContext()->getRedeclContext()))
7432 F.erase();
7433 }
7434 F.done();
7435
7436 if (Previous.empty()) {
7437 D.setInvalidType();
7438 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7439 return 0;
7440 }
7441
7442 // C++ [class.friend]p1: A friend of a class is a function or
7443 // class that is not a member of the class . . .
7444 if (DC->Equals(CurContext))
7445 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7446
7447 // - There's a scope specifier that does not match any template
7448 // parameter lists, in which case we use some arbitrary context,
7449 // create a method or method template, and wait for instantiation.
7450 // - There's a scope specifier that does match some template
7451 // parameter lists, which we don't handle right now.
7452 } else {
7453 DC = CurContext;
7454 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007455 }
7456
John McCall29ae6e52010-10-13 05:45:15 +00007457 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007458 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007459 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7460 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7461 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007462 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007463 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7464 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007465 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007466 }
John McCall67d1a672009-08-06 02:15:43 +00007467 }
7468
Douglas Gregor182ddf02009-09-28 00:08:27 +00007469 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007470 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007471 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007472 IsDefinition,
7473 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007474 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007475
Douglas Gregor182ddf02009-09-28 00:08:27 +00007476 assert(ND->getDeclContext() == DC);
7477 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007478
John McCallab88d972009-08-31 22:39:49 +00007479 // Add the function declaration to the appropriate lookup tables,
7480 // adjusting the redeclarations list as necessary. We don't
7481 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007482 //
John McCallab88d972009-08-31 22:39:49 +00007483 // Also update the scope-based lookup if the target context's
7484 // lookup context is in lexical scope.
7485 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007486 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007487 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007488 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007489 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007490 }
John McCall02cace72009-08-28 07:59:38 +00007491
7492 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007493 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007494 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007495 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007496 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007497
John McCall337ec3d2010-10-12 23:13:28 +00007498 if (ND->isInvalidDecl())
7499 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007500 else {
7501 FunctionDecl *FD;
7502 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7503 FD = FTD->getTemplatedDecl();
7504 else
7505 FD = cast<FunctionDecl>(ND);
7506
7507 // Mark templated-scope function declarations as unsupported.
7508 if (FD->getNumTemplateParameterLists())
7509 FrD->setUnsupportedFriend(true);
7510 }
John McCall337ec3d2010-10-12 23:13:28 +00007511
John McCalld226f652010-08-21 09:40:31 +00007512 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007513}
7514
John McCalld226f652010-08-21 09:40:31 +00007515void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7516 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007517
Sebastian Redl50de12f2009-03-24 22:27:57 +00007518 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7519 if (!Fn) {
7520 Diag(DelLoc, diag::err_deleted_non_function);
7521 return;
7522 }
7523 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7524 Diag(DelLoc, diag::err_deleted_decl_not_first);
7525 Diag(Prev->getLocation(), diag::note_previous_declaration);
7526 // If the declaration wasn't the first, we delete the function anyway for
7527 // recovery.
7528 }
7529 Fn->setDeleted();
7530}
Sebastian Redl13e88542009-04-27 21:33:24 +00007531
7532static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007533 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007534 Stmt *SubStmt = *CI;
7535 if (!SubStmt)
7536 continue;
7537 if (isa<ReturnStmt>(SubStmt))
7538 Self.Diag(SubStmt->getSourceRange().getBegin(),
7539 diag::err_return_in_constructor_handler);
7540 if (!isa<Expr>(SubStmt))
7541 SearchForReturnInStmt(Self, SubStmt);
7542 }
7543}
7544
7545void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7546 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7547 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7548 SearchForReturnInStmt(*this, Handler);
7549 }
7550}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007551
Mike Stump1eb44332009-09-09 15:08:12 +00007552bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007553 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007554 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7555 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007556
Chandler Carruth73857792010-02-15 11:53:20 +00007557 if (Context.hasSameType(NewTy, OldTy) ||
7558 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007559 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007560
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007561 // Check if the return types are covariant
7562 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007563
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007564 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007565 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7566 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007567 NewClassTy = NewPT->getPointeeType();
7568 OldClassTy = OldPT->getPointeeType();
7569 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007570 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7571 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7572 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7573 NewClassTy = NewRT->getPointeeType();
7574 OldClassTy = OldRT->getPointeeType();
7575 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007576 }
7577 }
Mike Stump1eb44332009-09-09 15:08:12 +00007578
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007579 // The return types aren't either both pointers or references to a class type.
7580 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007581 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007582 diag::err_different_return_type_for_overriding_virtual_function)
7583 << New->getDeclName() << NewTy << OldTy;
7584 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007585
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007586 return true;
7587 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007588
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007589 // C++ [class.virtual]p6:
7590 // If the return type of D::f differs from the return type of B::f, the
7591 // class type in the return type of D::f shall be complete at the point of
7592 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007593 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7594 if (!RT->isBeingDefined() &&
7595 RequireCompleteType(New->getLocation(), NewClassTy,
7596 PDiag(diag::err_covariant_return_incomplete)
7597 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007598 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007599 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007600
Douglas Gregora4923eb2009-11-16 21:35:15 +00007601 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007602 // Check if the new class derives from the old class.
7603 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7604 Diag(New->getLocation(),
7605 diag::err_covariant_return_not_derived)
7606 << New->getDeclName() << NewTy << OldTy;
7607 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7608 return true;
7609 }
Mike Stump1eb44332009-09-09 15:08:12 +00007610
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007611 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007612 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007613 diag::err_covariant_return_inaccessible_base,
7614 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7615 // FIXME: Should this point to the return type?
7616 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007617 // FIXME: this note won't trigger for delayed access control
7618 // diagnostics, and it's impossible to get an undelayed error
7619 // here from access control during the original parse because
7620 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007621 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7622 return true;
7623 }
7624 }
Mike Stump1eb44332009-09-09 15:08:12 +00007625
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007626 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007627 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007628 Diag(New->getLocation(),
7629 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007630 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007631 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7632 return true;
7633 };
Mike Stump1eb44332009-09-09 15:08:12 +00007634
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007635
7636 // The new class type must have the same or less qualifiers as the old type.
7637 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7638 Diag(New->getLocation(),
7639 diag::err_covariant_return_type_class_type_more_qualified)
7640 << New->getDeclName() << NewTy << OldTy;
7641 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7642 return true;
7643 };
Mike Stump1eb44332009-09-09 15:08:12 +00007644
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007645 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007646}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007647
Douglas Gregor4ba31362009-12-01 17:24:26 +00007648/// \brief Mark the given method pure.
7649///
7650/// \param Method the method to be marked pure.
7651///
7652/// \param InitRange the source range that covers the "0" initializer.
7653bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00007654 SourceLocation EndLoc = InitRange.getEnd();
7655 if (EndLoc.isValid())
7656 Method->setRangeEnd(EndLoc);
7657
Douglas Gregor4ba31362009-12-01 17:24:26 +00007658 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7659 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007660 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00007661 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00007662
7663 if (!Method->isInvalidDecl())
7664 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7665 << Method->getDeclName() << InitRange;
7666 return true;
7667}
7668
John McCall731ad842009-12-19 09:28:58 +00007669/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7670/// an initializer for the out-of-line declaration 'Dcl'. The scope
7671/// is a fresh scope pushed for just this purpose.
7672///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007673/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7674/// static data member of class X, names should be looked up in the scope of
7675/// class X.
John McCalld226f652010-08-21 09:40:31 +00007676void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007677 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007678 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007679
John McCall731ad842009-12-19 09:28:58 +00007680 // We should only get called for declarations with scope specifiers, like:
7681 // int foo::bar;
7682 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007683 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007684}
7685
7686/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007687/// initializer for the out-of-line declaration 'D'.
7688void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007689 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007690 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007691
John McCall731ad842009-12-19 09:28:58 +00007692 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007693 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007694}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007695
7696/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7697/// C++ if/switch/while/for statement.
7698/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007699DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007700 // C++ 6.4p2:
7701 // The declarator shall not specify a function or an array.
7702 // The type-specifier-seq shall not contain typedef and shall not declare a
7703 // new class or enumeration.
7704 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7705 "Parser allowed 'typedef' as storage class of condition decl.");
7706
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007707 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007708 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7709 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007710
7711 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7712 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7713 // would be created and CXXConditionDeclExpr wants a VarDecl.
7714 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7715 << D.getSourceRange();
7716 return DeclResult();
7717 } else if (OwnedTag && OwnedTag->isDefinition()) {
7718 // The type-specifier-seq shall not declare a new class or enumeration.
7719 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7720 }
7721
John McCalld226f652010-08-21 09:40:31 +00007722 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007723 if (!Dcl)
7724 return DeclResult();
7725
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007726 return Dcl;
7727}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007728
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007729void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7730 bool DefinitionRequired) {
7731 // Ignore any vtable uses in unevaluated operands or for classes that do
7732 // not have a vtable.
7733 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7734 CurContext->isDependentContext() ||
7735 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007736 return;
7737
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007738 // Try to insert this class into the map.
7739 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7740 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7741 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7742 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007743 // If we already had an entry, check to see if we are promoting this vtable
7744 // to required a definition. If so, we need to reappend to the VTableUses
7745 // list, since we may have already processed the first entry.
7746 if (DefinitionRequired && !Pos.first->second) {
7747 Pos.first->second = true;
7748 } else {
7749 // Otherwise, we can early exit.
7750 return;
7751 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007752 }
7753
7754 // Local classes need to have their virtual members marked
7755 // immediately. For all other classes, we mark their virtual members
7756 // at the end of the translation unit.
7757 if (Class->isLocalClass())
7758 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007759 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007760 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007761}
7762
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007763bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007764 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007765 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007766
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007767 // Note: The VTableUses vector could grow as a result of marking
7768 // the members of a class as "used", so we check the size each
7769 // time through the loop and prefer indices (with are stable) to
7770 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00007771 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007772 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007773 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007774 if (!Class)
7775 continue;
7776
7777 SourceLocation Loc = VTableUses[I].second;
7778
7779 // If this class has a key function, but that key function is
7780 // defined in another translation unit, we don't need to emit the
7781 // vtable even though we're using it.
7782 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007783 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007784 switch (KeyFunction->getTemplateSpecializationKind()) {
7785 case TSK_Undeclared:
7786 case TSK_ExplicitSpecialization:
7787 case TSK_ExplicitInstantiationDeclaration:
7788 // The key function is in another translation unit.
7789 continue;
7790
7791 case TSK_ExplicitInstantiationDefinition:
7792 case TSK_ImplicitInstantiation:
7793 // We will be instantiating the key function.
7794 break;
7795 }
7796 } else if (!KeyFunction) {
7797 // If we have a class with no key function that is the subject
7798 // of an explicit instantiation declaration, suppress the
7799 // vtable; it will live with the explicit instantiation
7800 // definition.
7801 bool IsExplicitInstantiationDeclaration
7802 = Class->getTemplateSpecializationKind()
7803 == TSK_ExplicitInstantiationDeclaration;
7804 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7805 REnd = Class->redecls_end();
7806 R != REnd; ++R) {
7807 TemplateSpecializationKind TSK
7808 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7809 if (TSK == TSK_ExplicitInstantiationDeclaration)
7810 IsExplicitInstantiationDeclaration = true;
7811 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7812 IsExplicitInstantiationDeclaration = false;
7813 break;
7814 }
7815 }
7816
7817 if (IsExplicitInstantiationDeclaration)
7818 continue;
7819 }
7820
7821 // Mark all of the virtual members of this class as referenced, so
7822 // that we can build a vtable. Then, tell the AST consumer that a
7823 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00007824 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007825 MarkVirtualMembersReferenced(Loc, Class);
7826 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7827 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7828
7829 // Optionally warn if we're emitting a weak vtable.
7830 if (Class->getLinkage() == ExternalLinkage &&
7831 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007832 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007833 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7834 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007835 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007836 VTableUses.clear();
7837
Douglas Gregor78844032011-04-22 22:25:37 +00007838 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007839}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007840
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007841void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7842 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007843 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7844 e = RD->method_end(); i != e; ++i) {
7845 CXXMethodDecl *MD = *i;
7846
7847 // C++ [basic.def.odr]p2:
7848 // [...] A virtual member function is used if it is not pure. [...]
7849 if (MD->isVirtual() && !MD->isPure())
7850 MarkDeclarationReferenced(Loc, MD);
7851 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007852
7853 // Only classes that have virtual bases need a VTT.
7854 if (RD->getNumVBases() == 0)
7855 return;
7856
7857 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7858 e = RD->bases_end(); i != e; ++i) {
7859 const CXXRecordDecl *Base =
7860 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007861 if (Base->getNumVBases() == 0)
7862 continue;
7863 MarkVirtualMembersReferenced(Loc, Base);
7864 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007865}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007866
7867/// SetIvarInitializers - This routine builds initialization ASTs for the
7868/// Objective-C implementation whose ivars need be initialized.
7869void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7870 if (!getLangOptions().CPlusPlus)
7871 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007872 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007873 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7874 CollectIvarsToConstructOrDestruct(OID, ivars);
7875 if (ivars.empty())
7876 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007877 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007878 for (unsigned i = 0; i < ivars.size(); i++) {
7879 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007880 if (Field->isInvalidDecl())
7881 continue;
7882
Sean Huntcbb67482011-01-08 20:30:50 +00007883 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007884 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7885 InitializationKind InitKind =
7886 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7887
7888 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007889 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007890 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007891 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007892 // Note, MemberInit could actually come back empty if no initialization
7893 // is required (e.g., because it would call a trivial default constructor)
7894 if (!MemberInit.get() || MemberInit.isInvalid())
7895 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007896
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007897 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007898 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7899 SourceLocation(),
7900 MemberInit.takeAs<Expr>(),
7901 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007902 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007903
7904 // Be sure that the destructor is accessible and is marked as referenced.
7905 if (const RecordType *RecordTy
7906 = Context.getBaseElementType(Field->getType())
7907 ->getAs<RecordType>()) {
7908 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007909 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007910 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7911 CheckDestructorAccess(Field->getLocation(), Destructor,
7912 PDiag(diag::err_access_dtor_ivar)
7913 << Context.getBaseElementType(Field->getType()));
7914 }
7915 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007916 }
7917 ObjCImplementation->setIvarInitializers(Context,
7918 AllToInit.data(), AllToInit.size());
7919 }
7920}