blob: 27632a1a57c452f02a501068ade631f28b8ef7f1 [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}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002071
2072bool
2073Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2074 CXXCtorInitializer *Initializer) {
2075 Constructor->setNumCtorInitializers(1);
2076 CXXCtorInitializer **initializer =
2077 new (Context) CXXCtorInitializer*[1];
2078 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2079 Constructor->setCtorInitializers(initializer);
2080
2081 // FIXME: This doesn't catch indirect loops yet
2082 CXXConstructorDecl *Target = Initializer->getTargetConstructor();
2083 while (Target) {
2084 if (Target == Constructor) {
2085 Diag(Initializer->getSourceLocation(), diag::err_delegating_ctor_loop)
2086 << Constructor;
2087 return true;
2088 }
2089 Target = Target->getTargetConstructor();
2090 }
2091
2092 return false;
2093}
2094
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002095
Eli Friedman80c30da2009-11-09 19:20:36 +00002096bool
Sean Huntcbb67482011-01-08 20:30:50 +00002097Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2098 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002099 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002100 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002101 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002102 // Just store the initializers as written, they will be checked during
2103 // instantiation.
2104 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002105 Constructor->setNumCtorInitializers(NumInitializers);
2106 CXXCtorInitializer **baseOrMemberInitializers =
2107 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002108 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002109 NumInitializers * sizeof(CXXCtorInitializer*));
2110 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002111 }
2112
2113 return false;
2114 }
2115
John McCallf1860e52010-05-20 23:23:51 +00002116 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002117
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002118 // We need to build the initializer AST according to order of construction
2119 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002120 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002121 if (!ClassDecl)
2122 return true;
2123
Eli Friedman80c30da2009-11-09 19:20:36 +00002124 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002126 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002127 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002128
2129 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002130 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002131 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002132 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002133 }
2134
Anders Carlsson711f34a2010-04-21 19:52:01 +00002135 // Keep track of the direct virtual bases.
2136 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2137 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2138 E = ClassDecl->bases_end(); I != E; ++I) {
2139 if (I->isVirtual())
2140 DirectVBases.insert(I);
2141 }
2142
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002143 // Push virtual bases before others.
2144 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2145 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2146
Sean Huntcbb67482011-01-08 20:30:50 +00002147 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002148 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2149 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002150 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002151 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002152 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002153 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002154 VBase, IsInheritedVirtualBase,
2155 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002156 HadError = true;
2157 continue;
2158 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002159
John McCallf1860e52010-05-20 23:23:51 +00002160 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002161 }
2162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
John McCallf1860e52010-05-20 23:23:51 +00002164 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002165 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2166 E = ClassDecl->bases_end(); Base != E; ++Base) {
2167 // Virtuals are in the virtual base list and already constructed.
2168 if (Base->isVirtual())
2169 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Sean Huntcbb67482011-01-08 20:30:50 +00002171 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002172 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2173 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002174 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002175 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002176 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002177 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002178 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002179 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002180 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002181 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002182
John McCallf1860e52010-05-20 23:23:51 +00002183 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002184 }
2185 }
Mike Stump1eb44332009-09-09 15:08:12 +00002186
John McCallf1860e52010-05-20 23:23:51 +00002187 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002188 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002189 E = ClassDecl->field_end(); Field != E; ++Field) {
2190 if ((*Field)->getType()->isIncompleteArrayType()) {
2191 assert(ClassDecl->hasFlexibleArrayMember() &&
2192 "Incomplete array type is not valid");
2193 continue;
2194 }
John McCallf1860e52010-05-20 23:23:51 +00002195 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002196 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002197 }
Mike Stump1eb44332009-09-09 15:08:12 +00002198
John McCallf1860e52010-05-20 23:23:51 +00002199 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002200 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002201 Constructor->setNumCtorInitializers(NumInitializers);
2202 CXXCtorInitializer **baseOrMemberInitializers =
2203 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002204 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002205 NumInitializers * sizeof(CXXCtorInitializer*));
2206 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002207
John McCallef027fe2010-03-16 21:39:52 +00002208 // Constructors implicitly reference the base and member
2209 // destructors.
2210 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2211 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002212 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002213
2214 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002215}
2216
Eli Friedman6347f422009-07-21 19:28:10 +00002217static void *GetKeyForTopLevelField(FieldDecl *Field) {
2218 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002219 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002220 if (RT->getDecl()->isAnonymousStructOrUnion())
2221 return static_cast<void *>(RT->getDecl());
2222 }
2223 return static_cast<void *>(Field);
2224}
2225
Anders Carlssonea356fb2010-04-02 05:42:15 +00002226static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002227 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002228}
2229
Anders Carlssonea356fb2010-04-02 05:42:15 +00002230static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002231 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002232 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002233 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002234
Eli Friedman6347f422009-07-21 19:28:10 +00002235 // For fields injected into the class via declaration of an anonymous union,
2236 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002237 FieldDecl *Field = Member->getAnyMember();
2238
John McCall3c3ccdb2010-04-10 09:28:51 +00002239 // If the field is a member of an anonymous struct or union, our key
2240 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002241 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002242 if (RD->isAnonymousStructOrUnion()) {
2243 while (true) {
2244 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2245 if (Parent->isAnonymousStructOrUnion())
2246 RD = Parent;
2247 else
2248 break;
2249 }
2250
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002251 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002252 }
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002254 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002255}
2256
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002257static void
2258DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002259 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002260 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002261 unsigned NumInits) {
2262 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002263 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002265 // Don't check initializers order unless the warning is enabled at the
2266 // location of at least one initializer.
2267 bool ShouldCheckOrder = false;
2268 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002269 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002270 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2271 Init->getSourceLocation())
2272 != Diagnostic::Ignored) {
2273 ShouldCheckOrder = true;
2274 break;
2275 }
2276 }
2277 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002278 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002279
John McCalld6ca8da2010-04-10 07:37:23 +00002280 // Build the list of bases and members in the order that they'll
2281 // actually be initialized. The explicit initializers should be in
2282 // this same order but may be missing things.
2283 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Anders Carlsson071d6102010-04-02 03:38:04 +00002285 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2286
John McCalld6ca8da2010-04-10 07:37:23 +00002287 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002288 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002289 ClassDecl->vbases_begin(),
2290 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002291 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002292
John McCalld6ca8da2010-04-10 07:37:23 +00002293 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002294 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002295 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002296 if (Base->isVirtual())
2297 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002298 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002299 }
Mike Stump1eb44332009-09-09 15:08:12 +00002300
John McCalld6ca8da2010-04-10 07:37:23 +00002301 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002302 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2303 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002304 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002305
John McCalld6ca8da2010-04-10 07:37:23 +00002306 unsigned NumIdealInits = IdealInitKeys.size();
2307 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002308
Sean Huntcbb67482011-01-08 20:30:50 +00002309 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002310 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002311 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002312 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002313
2314 // Scan forward to try to find this initializer in the idealized
2315 // initializers list.
2316 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2317 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002318 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002319
2320 // If we didn't find this initializer, it must be because we
2321 // scanned past it on a previous iteration. That can only
2322 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002323 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002324 Sema::SemaDiagnosticBuilder D =
2325 SemaRef.Diag(PrevInit->getSourceLocation(),
2326 diag::warn_initializer_out_of_order);
2327
Francois Pichet00eb3f92010-12-04 09:14:42 +00002328 if (PrevInit->isAnyMemberInitializer())
2329 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002330 else
2331 D << 1 << PrevInit->getBaseClassInfo()->getType();
2332
Francois Pichet00eb3f92010-12-04 09:14:42 +00002333 if (Init->isAnyMemberInitializer())
2334 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002335 else
2336 D << 1 << Init->getBaseClassInfo()->getType();
2337
2338 // Move back to the initializer's location in the ideal list.
2339 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2340 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002341 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002342
2343 assert(IdealIndex != NumIdealInits &&
2344 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002345 }
John McCalld6ca8da2010-04-10 07:37:23 +00002346
2347 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002348 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002349}
2350
John McCall3c3ccdb2010-04-10 09:28:51 +00002351namespace {
2352bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002353 CXXCtorInitializer *Init,
2354 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002355 if (!PrevInit) {
2356 PrevInit = Init;
2357 return false;
2358 }
2359
2360 if (FieldDecl *Field = Init->getMember())
2361 S.Diag(Init->getSourceLocation(),
2362 diag::err_multiple_mem_initialization)
2363 << Field->getDeclName()
2364 << Init->getSourceRange();
2365 else {
John McCallf4c73712011-01-19 06:33:43 +00002366 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002367 assert(BaseClass && "neither field nor base");
2368 S.Diag(Init->getSourceLocation(),
2369 diag::err_multiple_base_initialization)
2370 << QualType(BaseClass, 0)
2371 << Init->getSourceRange();
2372 }
2373 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2374 << 0 << PrevInit->getSourceRange();
2375
2376 return true;
2377}
2378
Sean Huntcbb67482011-01-08 20:30:50 +00002379typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002380typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2381
2382bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002383 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002384 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002385 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002386 RecordDecl *Parent = Field->getParent();
2387 if (!Parent->isAnonymousStructOrUnion())
2388 return false;
2389
2390 NamedDecl *Child = Field;
2391 do {
2392 if (Parent->isUnion()) {
2393 UnionEntry &En = Unions[Parent];
2394 if (En.first && En.first != Child) {
2395 S.Diag(Init->getSourceLocation(),
2396 diag::err_multiple_mem_union_initialization)
2397 << Field->getDeclName()
2398 << Init->getSourceRange();
2399 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2400 << 0 << En.second->getSourceRange();
2401 return true;
2402 } else if (!En.first) {
2403 En.first = Child;
2404 En.second = Init;
2405 }
2406 }
2407
2408 Child = Parent;
2409 Parent = cast<RecordDecl>(Parent->getDeclContext());
2410 } while (Parent->isAnonymousStructOrUnion());
2411
2412 return false;
2413}
2414}
2415
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002416/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002417void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002418 SourceLocation ColonLoc,
2419 MemInitTy **meminits, unsigned NumMemInits,
2420 bool AnyErrors) {
2421 if (!ConstructorDecl)
2422 return;
2423
2424 AdjustDeclIfTemplate(ConstructorDecl);
2425
2426 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002427 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002428
2429 if (!Constructor) {
2430 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2431 return;
2432 }
2433
Sean Huntcbb67482011-01-08 20:30:50 +00002434 CXXCtorInitializer **MemInits =
2435 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002436
2437 // Mapping for the duplicate initializers check.
2438 // For member initializers, this is keyed with a FieldDecl*.
2439 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002440 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002441
2442 // Mapping for the inconsistent anonymous-union initializers check.
2443 RedundantUnionMap MemberUnions;
2444
Anders Carlssonea356fb2010-04-02 05:42:15 +00002445 bool HadError = false;
2446 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002447 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002448
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002449 // Set the source order index.
2450 Init->setSourceOrder(i);
2451
Francois Pichet00eb3f92010-12-04 09:14:42 +00002452 if (Init->isAnyMemberInitializer()) {
2453 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002454 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2455 CheckRedundantUnionInit(*this, Init, MemberUnions))
2456 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002457 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002458 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2459 if (CheckRedundantInit(*this, Init, Members[Key]))
2460 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002461 } else {
2462 assert(Init->isDelegatingInitializer());
2463 // This must be the only initializer
2464 if (i != 0 || NumMemInits > 1) {
2465 Diag(MemInits[0]->getSourceLocation(),
2466 diag::err_delegating_initializer_alone)
2467 << MemInits[0]->getSourceRange();
2468 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002469 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002470 }
Sean Hunt059ce0d2011-05-01 07:04:31 +00002471 SetDelegatingInitializer(Constructor, *MemInits);
2472 // Return immediately as the initializer is set.
2473 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002474 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002475 }
2476
Anders Carlssonea356fb2010-04-02 05:42:15 +00002477 if (HadError)
2478 return;
2479
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002480 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002481
Sean Huntcbb67482011-01-08 20:30:50 +00002482 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002483}
2484
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002485void
John McCallef027fe2010-03-16 21:39:52 +00002486Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2487 CXXRecordDecl *ClassDecl) {
2488 // Ignore dependent contexts.
2489 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002490 return;
John McCall58e6f342010-03-16 05:22:47 +00002491
2492 // FIXME: all the access-control diagnostics are positioned on the
2493 // field/base declaration. That's probably good; that said, the
2494 // user might reasonably want to know why the destructor is being
2495 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002496
Anders Carlsson9f853df2009-11-17 04:44:12 +00002497 // Non-static data members.
2498 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2499 E = ClassDecl->field_end(); I != E; ++I) {
2500 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002501 if (Field->isInvalidDecl())
2502 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002503 QualType FieldType = Context.getBaseElementType(Field->getType());
2504
2505 const RecordType* RT = FieldType->getAs<RecordType>();
2506 if (!RT)
2507 continue;
2508
2509 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002510 if (FieldClassDecl->isInvalidDecl())
2511 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002512 if (FieldClassDecl->hasTrivialDestructor())
2513 continue;
2514
Douglas Gregordb89f282010-07-01 22:47:18 +00002515 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002516 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002517 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002518 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002519 << Field->getDeclName()
2520 << FieldType);
2521
John McCallef027fe2010-03-16 21:39:52 +00002522 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002523 }
2524
John McCall58e6f342010-03-16 05:22:47 +00002525 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2526
Anders Carlsson9f853df2009-11-17 04:44:12 +00002527 // Bases.
2528 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2529 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002530 // Bases are always records in a well-formed non-dependent class.
2531 const RecordType *RT = Base->getType()->getAs<RecordType>();
2532
2533 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002534 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002535 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002536
John McCall58e6f342010-03-16 05:22:47 +00002537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002538 // If our base class is invalid, we probably can't get its dtor anyway.
2539 if (BaseClassDecl->isInvalidDecl())
2540 continue;
2541 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002542 if (BaseClassDecl->hasTrivialDestructor())
2543 continue;
John McCall58e6f342010-03-16 05:22:47 +00002544
Douglas Gregordb89f282010-07-01 22:47:18 +00002545 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002546 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002547
2548 // FIXME: caret should be on the start of the class name
2549 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002550 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002551 << Base->getType()
2552 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002553
John McCallef027fe2010-03-16 21:39:52 +00002554 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002555 }
2556
2557 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002558 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2559 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002560
2561 // Bases are always records in a well-formed non-dependent class.
2562 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2563
2564 // Ignore direct virtual bases.
2565 if (DirectVirtualBases.count(RT))
2566 continue;
2567
John McCall58e6f342010-03-16 05:22:47 +00002568 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002569 // If our base class is invalid, we probably can't get its dtor anyway.
2570 if (BaseClassDecl->isInvalidDecl())
2571 continue;
2572 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002573 if (BaseClassDecl->hasTrivialDestructor())
2574 continue;
John McCall58e6f342010-03-16 05:22:47 +00002575
Douglas Gregordb89f282010-07-01 22:47:18 +00002576 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002577 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002578 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002579 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002580 << VBase->getType());
2581
John McCallef027fe2010-03-16 21:39:52 +00002582 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002583 }
2584}
2585
John McCalld226f652010-08-21 09:40:31 +00002586void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002587 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002588 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Mike Stump1eb44332009-09-09 15:08:12 +00002590 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002591 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002592 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002593}
2594
Mike Stump1eb44332009-09-09 15:08:12 +00002595bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002596 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002597 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002598 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002599 else
John McCall94c3b562010-08-18 09:41:07 +00002600 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002601}
2602
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002603bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002604 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002605 if (!getLangOptions().CPlusPlus)
2606 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Anders Carlsson11f21a02009-03-23 19:10:31 +00002608 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002609 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Ted Kremenek6217b802009-07-29 21:53:49 +00002611 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002612 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002613 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002614 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002616 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002617 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002618 }
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Ted Kremenek6217b802009-07-29 21:53:49 +00002620 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002621 if (!RT)
2622 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002623
John McCall86ff3082010-02-04 22:26:26 +00002624 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002625
John McCall94c3b562010-08-18 09:41:07 +00002626 // We can't answer whether something is abstract until it has a
2627 // definition. If it's currently being defined, we'll walk back
2628 // over all the declarations when we have a full definition.
2629 const CXXRecordDecl *Def = RD->getDefinition();
2630 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002631 return false;
2632
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002633 if (!RD->isAbstract())
2634 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002636 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002637 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002638
John McCall94c3b562010-08-18 09:41:07 +00002639 return true;
2640}
2641
2642void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2643 // Check if we've already emitted the list of pure virtual functions
2644 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002645 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002646 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002648 CXXFinalOverriderMap FinalOverriders;
2649 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002651 // Keep a set of seen pure methods so we won't diagnose the same method
2652 // more than once.
2653 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2654
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002655 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2656 MEnd = FinalOverriders.end();
2657 M != MEnd;
2658 ++M) {
2659 for (OverridingMethods::iterator SO = M->second.begin(),
2660 SOEnd = M->second.end();
2661 SO != SOEnd; ++SO) {
2662 // C++ [class.abstract]p4:
2663 // A class is abstract if it contains or inherits at least one
2664 // pure virtual function for which the final overrider is pure
2665 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002667 //
2668 if (SO->second.size() != 1)
2669 continue;
2670
2671 if (!SO->second.front().Method->isPure())
2672 continue;
2673
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002674 if (!SeenPureMethods.insert(SO->second.front().Method))
2675 continue;
2676
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002677 Diag(SO->second.front().Method->getLocation(),
2678 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002679 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002680 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002681 }
2682
2683 if (!PureVirtualClassDiagSet)
2684 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2685 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002686}
2687
Anders Carlsson8211eff2009-03-24 01:19:16 +00002688namespace {
John McCall94c3b562010-08-18 09:41:07 +00002689struct AbstractUsageInfo {
2690 Sema &S;
2691 CXXRecordDecl *Record;
2692 CanQualType AbstractType;
2693 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002694
John McCall94c3b562010-08-18 09:41:07 +00002695 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2696 : S(S), Record(Record),
2697 AbstractType(S.Context.getCanonicalType(
2698 S.Context.getTypeDeclType(Record))),
2699 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002700
John McCall94c3b562010-08-18 09:41:07 +00002701 void DiagnoseAbstractType() {
2702 if (Invalid) return;
2703 S.DiagnoseAbstractType(Record);
2704 Invalid = true;
2705 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002706
John McCall94c3b562010-08-18 09:41:07 +00002707 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2708};
2709
2710struct CheckAbstractUsage {
2711 AbstractUsageInfo &Info;
2712 const NamedDecl *Ctx;
2713
2714 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2715 : Info(Info), Ctx(Ctx) {}
2716
2717 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2718 switch (TL.getTypeLocClass()) {
2719#define ABSTRACT_TYPELOC(CLASS, PARENT)
2720#define TYPELOC(CLASS, PARENT) \
2721 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2722#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002723 }
John McCall94c3b562010-08-18 09:41:07 +00002724 }
Mike Stump1eb44332009-09-09 15:08:12 +00002725
John McCall94c3b562010-08-18 09:41:07 +00002726 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2727 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2728 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002729 if (!TL.getArg(I))
2730 continue;
2731
John McCall94c3b562010-08-18 09:41:07 +00002732 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2733 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002734 }
John McCall94c3b562010-08-18 09:41:07 +00002735 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002736
John McCall94c3b562010-08-18 09:41:07 +00002737 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2738 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2739 }
Mike Stump1eb44332009-09-09 15:08:12 +00002740
John McCall94c3b562010-08-18 09:41:07 +00002741 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2742 // Visit the type parameters from a permissive context.
2743 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2744 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2745 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2746 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2747 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2748 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002749 }
John McCall94c3b562010-08-18 09:41:07 +00002750 }
Mike Stump1eb44332009-09-09 15:08:12 +00002751
John McCall94c3b562010-08-18 09:41:07 +00002752 // Visit pointee types from a permissive context.
2753#define CheckPolymorphic(Type) \
2754 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2755 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2756 }
2757 CheckPolymorphic(PointerTypeLoc)
2758 CheckPolymorphic(ReferenceTypeLoc)
2759 CheckPolymorphic(MemberPointerTypeLoc)
2760 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002761
John McCall94c3b562010-08-18 09:41:07 +00002762 /// Handle all the types we haven't given a more specific
2763 /// implementation for above.
2764 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2765 // Every other kind of type that we haven't called out already
2766 // that has an inner type is either (1) sugar or (2) contains that
2767 // inner type in some way as a subobject.
2768 if (TypeLoc Next = TL.getNextTypeLoc())
2769 return Visit(Next, Sel);
2770
2771 // If there's no inner type and we're in a permissive context,
2772 // don't diagnose.
2773 if (Sel == Sema::AbstractNone) return;
2774
2775 // Check whether the type matches the abstract type.
2776 QualType T = TL.getType();
2777 if (T->isArrayType()) {
2778 Sel = Sema::AbstractArrayType;
2779 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002780 }
John McCall94c3b562010-08-18 09:41:07 +00002781 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2782 if (CT != Info.AbstractType) return;
2783
2784 // It matched; do some magic.
2785 if (Sel == Sema::AbstractArrayType) {
2786 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2787 << T << TL.getSourceRange();
2788 } else {
2789 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2790 << Sel << T << TL.getSourceRange();
2791 }
2792 Info.DiagnoseAbstractType();
2793 }
2794};
2795
2796void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2797 Sema::AbstractDiagSelID Sel) {
2798 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2799}
2800
2801}
2802
2803/// Check for invalid uses of an abstract type in a method declaration.
2804static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2805 CXXMethodDecl *MD) {
2806 // No need to do the check on definitions, which require that
2807 // the return/param types be complete.
2808 if (MD->isThisDeclarationADefinition())
2809 return;
2810
2811 // For safety's sake, just ignore it if we don't have type source
2812 // information. This should never happen for non-implicit methods,
2813 // but...
2814 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2815 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2816}
2817
2818/// Check for invalid uses of an abstract type within a class definition.
2819static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2820 CXXRecordDecl *RD) {
2821 for (CXXRecordDecl::decl_iterator
2822 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2823 Decl *D = *I;
2824 if (D->isImplicit()) continue;
2825
2826 // Methods and method templates.
2827 if (isa<CXXMethodDecl>(D)) {
2828 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2829 } else if (isa<FunctionTemplateDecl>(D)) {
2830 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2831 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2832
2833 // Fields and static variables.
2834 } else if (isa<FieldDecl>(D)) {
2835 FieldDecl *FD = cast<FieldDecl>(D);
2836 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2837 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2838 } else if (isa<VarDecl>(D)) {
2839 VarDecl *VD = cast<VarDecl>(D);
2840 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2841 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2842
2843 // Nested classes and class templates.
2844 } else if (isa<CXXRecordDecl>(D)) {
2845 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2846 } else if (isa<ClassTemplateDecl>(D)) {
2847 CheckAbstractClassUsage(Info,
2848 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2849 }
2850 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002851}
2852
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002853/// \brief Perform semantic checks on a class definition that has been
2854/// completing, introducing implicitly-declared members, checking for
2855/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002856void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002857 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002858 return;
2859
John McCall94c3b562010-08-18 09:41:07 +00002860 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2861 AbstractUsageInfo Info(*this, Record);
2862 CheckAbstractClassUsage(Info, Record);
2863 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002864
2865 // If this is not an aggregate type and has no user-declared constructor,
2866 // complain about any non-static data members of reference or const scalar
2867 // type, since they will never get initializers.
2868 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2869 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2870 bool Complained = false;
2871 for (RecordDecl::field_iterator F = Record->field_begin(),
2872 FEnd = Record->field_end();
2873 F != FEnd; ++F) {
2874 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002875 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002876 if (!Complained) {
2877 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2878 << Record->getTagKind() << Record;
2879 Complained = true;
2880 }
2881
2882 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2883 << F->getType()->isReferenceType()
2884 << F->getDeclName();
2885 }
2886 }
2887 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002888
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002889 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002890 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002891
2892 if (Record->getIdentifier()) {
2893 // C++ [class.mem]p13:
2894 // If T is the name of a class, then each of the following shall have a
2895 // name different from T:
2896 // - every member of every anonymous union that is a member of class T.
2897 //
2898 // C++ [class.mem]p14:
2899 // In addition, if class T has a user-declared constructor (12.1), every
2900 // non-static data member of class T shall have a name different from T.
2901 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002902 R.first != R.second; ++R.first) {
2903 NamedDecl *D = *R.first;
2904 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2905 isa<IndirectFieldDecl>(D)) {
2906 Diag(D->getLocation(), diag::err_member_name_of_class)
2907 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002908 break;
2909 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002910 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002911 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002912
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002913 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002914 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002915 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002916 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002917 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2918 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2919 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002920
2921 // See if a method overloads virtual methods in a base
2922 /// class without overriding any.
2923 if (!Record->isDependentType()) {
2924 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2925 MEnd = Record->method_end();
2926 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002927 if (!(*M)->isStatic())
2928 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002929 }
2930 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002931
2932 // Declare inherited constructors. We do this eagerly here because:
2933 // - The standard requires an eager diagnostic for conflicting inherited
2934 // constructors from different classes.
2935 // - The lazy declaration of the other implicit constructors is so as to not
2936 // waste space and performance on classes that are not meant to be
2937 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2938 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002939 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002940}
2941
2942/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00002943namespace {
2944 struct FindHiddenVirtualMethodData {
2945 Sema *S;
2946 CXXMethodDecl *Method;
2947 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2948 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2949 };
2950}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002951
2952/// \brief Member lookup function that determines whether a given C++
2953/// method overloads virtual methods in a base class without overriding any,
2954/// to be used with CXXRecordDecl::lookupInBases().
2955static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2956 CXXBasePath &Path,
2957 void *UserData) {
2958 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2959
2960 FindHiddenVirtualMethodData &Data
2961 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2962
2963 DeclarationName Name = Data.Method->getDeclName();
2964 assert(Name.getNameKind() == DeclarationName::Identifier);
2965
2966 bool foundSameNameMethod = false;
2967 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2968 for (Path.Decls = BaseRecord->lookup(Name);
2969 Path.Decls.first != Path.Decls.second;
2970 ++Path.Decls.first) {
2971 NamedDecl *D = *Path.Decls.first;
2972 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002973 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002974 foundSameNameMethod = true;
2975 // Interested only in hidden virtual methods.
2976 if (!MD->isVirtual())
2977 continue;
2978 // If the method we are checking overrides a method from its base
2979 // don't warn about the other overloaded methods.
2980 if (!Data.S->IsOverload(Data.Method, MD, false))
2981 return true;
2982 // Collect the overload only if its hidden.
2983 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2984 overloadedMethods.push_back(MD);
2985 }
2986 }
2987
2988 if (foundSameNameMethod)
2989 Data.OverloadedMethods.append(overloadedMethods.begin(),
2990 overloadedMethods.end());
2991 return foundSameNameMethod;
2992}
2993
2994/// \brief See if a method overloads virtual methods in a base class without
2995/// overriding any.
2996void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2997 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2998 MD->getLocation()) == Diagnostic::Ignored)
2999 return;
3000 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
3001 return;
3002
3003 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
3004 /*bool RecordPaths=*/false,
3005 /*bool DetectVirtual=*/false);
3006 FindHiddenVirtualMethodData Data;
3007 Data.Method = MD;
3008 Data.S = this;
3009
3010 // Keep the base methods that were overriden or introduced in the subclass
3011 // by 'using' in a set. A base method not in this set is hidden.
3012 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
3013 res.first != res.second; ++res.first) {
3014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
3015 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
3016 E = MD->end_overridden_methods();
3017 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003018 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003019 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
3020 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003021 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003022 }
3023
3024 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
3025 !Data.OverloadedMethods.empty()) {
3026 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
3027 << MD << (Data.OverloadedMethods.size() > 1);
3028
3029 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3030 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3031 Diag(overloadedMD->getLocation(),
3032 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3033 }
3034 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003035}
3036
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003037void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00003038 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003039 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003040 SourceLocation RBrac,
3041 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003042 if (!TagDecl)
3043 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Douglas Gregor42af25f2009-05-11 19:58:34 +00003045 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003046
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003047 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00003048 // strict aliasing violation!
3049 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003050 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00003051
Douglas Gregor23c94db2010-07-02 17:43:08 +00003052 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00003053 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003054}
3055
Douglas Gregord92ec472010-07-01 05:10:53 +00003056namespace {
3057 /// \brief Helper class that collects exception specifications for
3058 /// implicitly-declared special member functions.
3059 class ImplicitExceptionSpecification {
3060 ASTContext &Context;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003061 // We order exception specifications thus:
3062 // noexcept is the most restrictive, but is only used in C++0x.
3063 // throw() comes next.
3064 // Then a throw(collected exceptions)
3065 // Finally no specification.
3066 // throw(...) is used instead if any called function uses it.
3067 ExceptionSpecificationType ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003068 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3069 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003070
3071 void ClearExceptions() {
3072 ExceptionsSeen.clear();
3073 Exceptions.clear();
3074 }
3075
Douglas Gregord92ec472010-07-01 05:10:53 +00003076 public:
3077 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redl60618fa2011-03-12 11:50:43 +00003078 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3079 if (!Context.getLangOptions().CPlusPlus0x)
3080 ComputedEST = EST_DynamicNone;
Douglas Gregord92ec472010-07-01 05:10:53 +00003081 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003082
3083 /// \brief Get the computed exception specification type.
3084 ExceptionSpecificationType getExceptionSpecType() const {
3085 assert(ComputedEST != EST_ComputedNoexcept &&
3086 "noexcept(expr) should not be a possible result");
3087 return ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003088 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003089
Douglas Gregord92ec472010-07-01 05:10:53 +00003090 /// \brief The number of exceptions in the exception specification.
3091 unsigned size() const { return Exceptions.size(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003092
Douglas Gregord92ec472010-07-01 05:10:53 +00003093 /// \brief The set of exceptions in the exception specification.
3094 const QualType *data() const { return Exceptions.data(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003095
3096 /// \brief Integrate another called method into the collected data.
Douglas Gregord92ec472010-07-01 05:10:53 +00003097 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00003098 // If we have an MSAny spec already, don't bother.
3099 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregord92ec472010-07-01 05:10:53 +00003100 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003101
Douglas Gregord92ec472010-07-01 05:10:53 +00003102 const FunctionProtoType *Proto
3103 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003104
3105 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3106
Douglas Gregord92ec472010-07-01 05:10:53 +00003107 // If this function can throw any exceptions, make a note of that.
Sebastian Redl60618fa2011-03-12 11:50:43 +00003108 if (EST == EST_MSAny || EST == EST_None) {
3109 ClearExceptions();
3110 ComputedEST = EST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003111 return;
3112 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003113
3114 // If this function has a basic noexcept, it doesn't affect the outcome.
3115 if (EST == EST_BasicNoexcept)
3116 return;
3117
3118 // If we have a throw-all spec at this point, ignore the function.
3119 if (ComputedEST == EST_None)
3120 return;
3121
3122 // If we're still at noexcept(true) and there's a nothrow() callee,
3123 // change to that specification.
3124 if (EST == EST_DynamicNone) {
3125 if (ComputedEST == EST_BasicNoexcept)
3126 ComputedEST = EST_DynamicNone;
3127 return;
3128 }
3129
3130 // Check out noexcept specs.
3131 if (EST == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003132 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +00003133 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3134 "Must have noexcept result for EST_ComputedNoexcept.");
3135 assert(NR != FunctionProtoType::NR_Dependent &&
3136 "Should not generate implicit declarations for dependent cases, "
3137 "and don't know how to handle them anyway.");
3138
3139 // noexcept(false) -> no spec on the new function
3140 if (NR == FunctionProtoType::NR_Throw) {
3141 ClearExceptions();
3142 ComputedEST = EST_None;
3143 }
3144 // noexcept(true) won't change anything either.
3145 return;
3146 }
3147
3148 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3149 assert(ComputedEST != EST_None &&
3150 "Shouldn't collect exceptions when throw-all is guaranteed.");
3151 ComputedEST = EST_Dynamic;
Douglas Gregord92ec472010-07-01 05:10:53 +00003152 // Record the exceptions in this function's exception specification.
3153 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3154 EEnd = Proto->exception_end();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003155 E != EEnd; ++E)
Douglas Gregord92ec472010-07-01 05:10:53 +00003156 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3157 Exceptions.push_back(*E);
3158 }
3159 };
3160}
3161
3162
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003163/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3164/// special functions, such as the default constructor, copy
3165/// constructor, or destructor, to the given C++ class (C++
3166/// [special]p1). This routine can only be executed just before the
3167/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003168void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00003169 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00003170 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003171
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00003172 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00003173 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003174
Douglas Gregora376d102010-07-02 21:50:04 +00003175 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3176 ++ASTContext::NumImplicitCopyAssignmentOperators;
3177
3178 // If we have a dynamic class, then the copy assignment operator may be
3179 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3180 // it shows up in the right place in the vtable and that we diagnose
3181 // problems with the implicit exception specification.
3182 if (ClassDecl->isDynamicClass())
3183 DeclareImplicitCopyAssignment(ClassDecl);
3184 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003185
Douglas Gregor4923aa22010-07-02 20:37:36 +00003186 if (!ClassDecl->hasUserDeclaredDestructor()) {
3187 ++ASTContext::NumImplicitDestructors;
3188
3189 // If we have a dynamic class, then the destructor may be virtual, so we
3190 // have to declare the destructor immediately. This ensures that, e.g., it
3191 // shows up in the right place in the vtable and that we diagnose problems
3192 // with the implicit exception specification.
3193 if (ClassDecl->isDynamicClass())
3194 DeclareImplicitDestructor(ClassDecl);
3195 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003196}
3197
Francois Pichet8387e2a2011-04-22 22:18:13 +00003198void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3199 if (!D)
3200 return;
3201
3202 int NumParamList = D->getNumTemplateParameterLists();
3203 for (int i = 0; i < NumParamList; i++) {
3204 TemplateParameterList* Params = D->getTemplateParameterList(i);
3205 for (TemplateParameterList::iterator Param = Params->begin(),
3206 ParamEnd = Params->end();
3207 Param != ParamEnd; ++Param) {
3208 NamedDecl *Named = cast<NamedDecl>(*Param);
3209 if (Named->getDeclName()) {
3210 S->AddDecl(Named);
3211 IdResolver.AddDecl(Named);
3212 }
3213 }
3214 }
3215}
3216
John McCalld226f652010-08-21 09:40:31 +00003217void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003218 if (!D)
3219 return;
3220
3221 TemplateParameterList *Params = 0;
3222 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3223 Params = Template->getTemplateParameters();
3224 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3225 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3226 Params = PartialSpec->getTemplateParameters();
3227 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003228 return;
3229
Douglas Gregor6569d682009-05-27 23:11:45 +00003230 for (TemplateParameterList::iterator Param = Params->begin(),
3231 ParamEnd = Params->end();
3232 Param != ParamEnd; ++Param) {
3233 NamedDecl *Named = cast<NamedDecl>(*Param);
3234 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003235 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003236 IdResolver.AddDecl(Named);
3237 }
3238 }
3239}
3240
John McCalld226f652010-08-21 09:40:31 +00003241void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003242 if (!RecordD) return;
3243 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003244 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003245 PushDeclContext(S, Record);
3246}
3247
John McCalld226f652010-08-21 09:40:31 +00003248void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003249 if (!RecordD) return;
3250 PopDeclContext();
3251}
3252
Douglas Gregor72b505b2008-12-16 21:30:33 +00003253/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3254/// parsing a top-level (non-nested) C++ class, and we are now
3255/// parsing those parts of the given Method declaration that could
3256/// not be parsed earlier (C++ [class.mem]p2), such as default
3257/// arguments. This action should enter the scope of the given
3258/// Method declaration as if we had just parsed the qualified method
3259/// name. However, it should not bring the parameters into scope;
3260/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003261void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003262}
3263
3264/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3265/// C++ method declaration. We're (re-)introducing the given
3266/// function parameter into scope for use in parsing later parts of
3267/// the method declaration. For example, we could see an
3268/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003269void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003270 if (!ParamD)
3271 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003272
John McCalld226f652010-08-21 09:40:31 +00003273 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003274
3275 // If this parameter has an unparsed default argument, clear it out
3276 // to make way for the parsed default argument.
3277 if (Param->hasUnparsedDefaultArg())
3278 Param->setDefaultArg(0);
3279
John McCalld226f652010-08-21 09:40:31 +00003280 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003281 if (Param->getDeclName())
3282 IdResolver.AddDecl(Param);
3283}
3284
3285/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3286/// processing the delayed method declaration for Method. The method
3287/// declaration is now considered finished. There may be a separate
3288/// ActOnStartOfFunctionDef action later (not necessarily
3289/// immediately!) for this method, if it was also defined inside the
3290/// class body.
John McCalld226f652010-08-21 09:40:31 +00003291void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003292 if (!MethodD)
3293 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003295 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003296
John McCalld226f652010-08-21 09:40:31 +00003297 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003298
3299 // Now that we have our default arguments, check the constructor
3300 // again. It could produce additional diagnostics or affect whether
3301 // the class has implicitly-declared destructors, among other
3302 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003303 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3304 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003305
3306 // Check the default arguments, which we may have added.
3307 if (!Method->isInvalidDecl())
3308 CheckCXXDefaultArguments(Method);
3309}
3310
Douglas Gregor42a552f2008-11-05 20:51:48 +00003311/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003312/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003313/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003314/// emit diagnostics and set the invalid bit to true. In any case, the type
3315/// will be updated to reflect a well-formed type for the constructor and
3316/// returned.
3317QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003318 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003319 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003320
3321 // C++ [class.ctor]p3:
3322 // A constructor shall not be virtual (10.3) or static (9.4). A
3323 // constructor can be invoked for a const, volatile or const
3324 // volatile object. A constructor shall not be declared const,
3325 // volatile, or const volatile (9.3.2).
3326 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003327 if (!D.isInvalidType())
3328 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3329 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3330 << SourceRange(D.getIdentifierLoc());
3331 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003332 }
John McCalld931b082010-08-26 03:08:43 +00003333 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003334 if (!D.isInvalidType())
3335 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3336 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3337 << SourceRange(D.getIdentifierLoc());
3338 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003339 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003340 }
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003342 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003343 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003344 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003345 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3346 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003347 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003348 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3349 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003350 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003351 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3352 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003353 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003354 }
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Douglas Gregorc938c162011-01-26 05:01:58 +00003356 // C++0x [class.ctor]p4:
3357 // A constructor shall not be declared with a ref-qualifier.
3358 if (FTI.hasRefQualifier()) {
3359 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3360 << FTI.RefQualifierIsLValueRef
3361 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3362 D.setInvalidType();
3363 }
3364
Douglas Gregor42a552f2008-11-05 20:51:48 +00003365 // Rebuild the function type "R" without any type qualifiers (in
3366 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003367 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003368 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003369 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3370 return R;
3371
3372 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3373 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003374 EPI.RefQualifier = RQ_None;
3375
Chris Lattner65401802009-04-25 08:28:21 +00003376 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003377 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003378}
3379
Douglas Gregor72b505b2008-12-16 21:30:33 +00003380/// CheckConstructor - Checks a fully-formed constructor for
3381/// well-formedness, issuing any diagnostics required. Returns true if
3382/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003383void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003384 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003385 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3386 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003387 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003388
3389 // C++ [class.copy]p3:
3390 // A declaration of a constructor for a class X is ill-formed if
3391 // its first parameter is of type (optionally cv-qualified) X and
3392 // either there are no other parameters or else all other
3393 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003394 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003395 ((Constructor->getNumParams() == 1) ||
3396 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003397 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3398 Constructor->getTemplateSpecializationKind()
3399 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003400 QualType ParamType = Constructor->getParamDecl(0)->getType();
3401 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3402 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003403 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003404 const char *ConstRef
3405 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3406 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003407 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003408 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003409
3410 // FIXME: Rather that making the constructor invalid, we should endeavor
3411 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003412 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003413 }
3414 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003415}
3416
John McCall15442822010-08-04 01:04:25 +00003417/// CheckDestructor - Checks a fully-formed destructor definition for
3418/// well-formedness, issuing any diagnostics required. Returns true
3419/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003420bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003421 CXXRecordDecl *RD = Destructor->getParent();
3422
3423 if (Destructor->isVirtual()) {
3424 SourceLocation Loc;
3425
3426 if (!Destructor->isImplicit())
3427 Loc = Destructor->getLocation();
3428 else
3429 Loc = RD->getLocation();
3430
3431 // If we have a virtual destructor, look up the deallocation function
3432 FunctionDecl *OperatorDelete = 0;
3433 DeclarationName Name =
3434 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003435 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003436 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003437
3438 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003439
3440 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003441 }
Anders Carlsson37909802009-11-30 21:24:50 +00003442
3443 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003444}
3445
Mike Stump1eb44332009-09-09 15:08:12 +00003446static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003447FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3448 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3449 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003450 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003451}
3452
Douglas Gregor42a552f2008-11-05 20:51:48 +00003453/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3454/// the well-formednes of the destructor declarator @p D with type @p
3455/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003456/// emit diagnostics and set the declarator to invalid. Even if this happens,
3457/// will be updated to reflect a well-formed type for the destructor and
3458/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003459QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003460 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003461 // C++ [class.dtor]p1:
3462 // [...] A typedef-name that names a class is a class-name
3463 // (7.1.3); however, a typedef-name that names a class shall not
3464 // be used as the identifier in the declarator for a destructor
3465 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003466 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00003467 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00003468 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00003469 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003470
3471 // C++ [class.dtor]p2:
3472 // A destructor is used to destroy objects of its class type. A
3473 // destructor takes no parameters, and no return type can be
3474 // specified for it (not even void). The address of a destructor
3475 // shall not be taken. A destructor shall not be static. A
3476 // destructor can be invoked for a const, volatile or const
3477 // volatile object. A destructor shall not be declared const,
3478 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003479 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003480 if (!D.isInvalidType())
3481 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3482 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003483 << SourceRange(D.getIdentifierLoc())
3484 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3485
John McCalld931b082010-08-26 03:08:43 +00003486 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003487 }
Chris Lattner65401802009-04-25 08:28:21 +00003488 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003489 // Destructors don't have return types, but the parser will
3490 // happily parse something like:
3491 //
3492 // class X {
3493 // float ~X();
3494 // };
3495 //
3496 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003497 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3498 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3499 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003500 }
Mike Stump1eb44332009-09-09 15:08:12 +00003501
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003502 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003503 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003504 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003505 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3506 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003507 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003508 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3509 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003510 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003511 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3512 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003513 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003514 }
3515
Douglas Gregorc938c162011-01-26 05:01:58 +00003516 // C++0x [class.dtor]p2:
3517 // A destructor shall not be declared with a ref-qualifier.
3518 if (FTI.hasRefQualifier()) {
3519 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3520 << FTI.RefQualifierIsLValueRef
3521 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3522 D.setInvalidType();
3523 }
3524
Douglas Gregor42a552f2008-11-05 20:51:48 +00003525 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003526 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003527 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3528
3529 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003530 FTI.freeArgs();
3531 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003532 }
3533
Mike Stump1eb44332009-09-09 15:08:12 +00003534 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003535 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003536 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003537 D.setInvalidType();
3538 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003539
3540 // Rebuild the function type "R" without any type qualifiers or
3541 // parameters (in case any of the errors above fired) and with
3542 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003543 // types.
John McCalle23cf432010-12-14 08:05:40 +00003544 if (!D.isInvalidType())
3545 return R;
3546
Douglas Gregord92ec472010-07-01 05:10:53 +00003547 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003548 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3549 EPI.Variadic = false;
3550 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003551 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003552 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003553}
3554
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003555/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3556/// well-formednes of the conversion function declarator @p D with
3557/// type @p R. If there are any errors in the declarator, this routine
3558/// will emit diagnostics and return true. Otherwise, it will return
3559/// false. Either way, the type @p R will be updated to reflect a
3560/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003561void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003562 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003563 // C++ [class.conv.fct]p1:
3564 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003565 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003566 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003567 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003568 if (!D.isInvalidType())
3569 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3570 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3571 << SourceRange(D.getIdentifierLoc());
3572 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003573 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003574 }
John McCalla3f81372010-04-13 00:04:31 +00003575
3576 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3577
Chris Lattner6e475012009-04-25 08:35:12 +00003578 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003579 // Conversion functions don't have return types, but the parser will
3580 // happily parse something like:
3581 //
3582 // class X {
3583 // float operator bool();
3584 // };
3585 //
3586 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003587 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3588 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3589 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003590 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003591 }
3592
John McCalla3f81372010-04-13 00:04:31 +00003593 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3594
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003595 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003596 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003597 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3598
3599 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003600 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003601 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003602 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003603 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003604 D.setInvalidType();
3605 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003606
John McCalla3f81372010-04-13 00:04:31 +00003607 // Diagnose "&operator bool()" and other such nonsense. This
3608 // is actually a gcc extension which we don't support.
3609 if (Proto->getResultType() != ConvType) {
3610 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3611 << Proto->getResultType();
3612 D.setInvalidType();
3613 ConvType = Proto->getResultType();
3614 }
3615
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003616 // C++ [class.conv.fct]p4:
3617 // The conversion-type-id shall not represent a function type nor
3618 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003619 if (ConvType->isArrayType()) {
3620 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3621 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003622 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003623 } else if (ConvType->isFunctionType()) {
3624 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3625 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003626 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003627 }
3628
3629 // Rebuild the function type "R" without any parameters (in case any
3630 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003631 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003632 if (D.isInvalidType())
3633 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003634
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003635 // C++0x explicit conversion operators.
3636 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003637 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003638 diag::warn_explicit_conversion_functions)
3639 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003640}
3641
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003642/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3643/// the declaration of the given C++ conversion function. This routine
3644/// is responsible for recording the conversion function in the C++
3645/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003646Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003647 assert(Conversion && "Expected to receive a conversion function declaration");
3648
Douglas Gregor9d350972008-12-12 08:25:50 +00003649 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003650
3651 // Make sure we aren't redeclaring the conversion function.
3652 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003653
3654 // C++ [class.conv.fct]p1:
3655 // [...] A conversion function is never used to convert a
3656 // (possibly cv-qualified) object to the (possibly cv-qualified)
3657 // same object type (or a reference to it), to a (possibly
3658 // cv-qualified) base class of that type (or a reference to it),
3659 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003660 // FIXME: Suppress this warning if the conversion function ends up being a
3661 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003662 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003663 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003664 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003665 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003666 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3667 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003668 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003669 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003670 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3671 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003672 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003673 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003674 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003675 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003676 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003677 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003678 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003679 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003680 }
3681
Douglas Gregore80622f2010-09-29 04:25:11 +00003682 if (FunctionTemplateDecl *ConversionTemplate
3683 = Conversion->getDescribedFunctionTemplate())
3684 return ConversionTemplate;
3685
John McCalld226f652010-08-21 09:40:31 +00003686 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003687}
3688
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003689//===----------------------------------------------------------------------===//
3690// Namespace Handling
3691//===----------------------------------------------------------------------===//
3692
John McCallea318642010-08-26 09:15:37 +00003693
3694
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003695/// ActOnStartNamespaceDef - This is called at the start of a namespace
3696/// definition.
John McCalld226f652010-08-21 09:40:31 +00003697Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003698 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003699 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00003700 SourceLocation IdentLoc,
3701 IdentifierInfo *II,
3702 SourceLocation LBrace,
3703 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003704 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3705 // For anonymous namespace, take the location of the left brace.
3706 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00003707 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003708 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003709 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003710
3711 Scope *DeclRegionScope = NamespcScope->getParent();
3712
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003713 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3714
John McCall90f14502010-12-10 02:59:44 +00003715 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3716 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003717
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003718 if (II) {
3719 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003720 // The identifier in an original-namespace-definition shall not
3721 // have been previously defined in the declarative region in
3722 // which the original-namespace-definition appears. The
3723 // identifier in an original-namespace-definition is the name of
3724 // the namespace. Subsequently in that declarative region, it is
3725 // treated as an original-namespace-name.
3726 //
3727 // Since namespace names are unique in their scope, and we don't
3728 // look through using directives, just
3729 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3730 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Douglas Gregor44b43212008-12-11 16:49:14 +00003732 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3733 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003734 if (Namespc->isInline() != OrigNS->isInline()) {
3735 // inline-ness must match
3736 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3737 << Namespc->isInline();
3738 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3739 Namespc->setInvalidDecl();
3740 // Recover by ignoring the new namespace's inline status.
3741 Namespc->setInline(OrigNS->isInline());
3742 }
3743
Douglas Gregor44b43212008-12-11 16:49:14 +00003744 // Attach this namespace decl to the chain of extended namespace
3745 // definitions.
3746 OrigNS->setNextNamespace(Namespc);
3747 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003748
Mike Stump1eb44332009-09-09 15:08:12 +00003749 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003750 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003751 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003752 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003753 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003754 } else if (PrevDecl) {
3755 // This is an invalid name redefinition.
3756 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3757 << Namespc->getDeclName();
3758 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3759 Namespc->setInvalidDecl();
3760 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003761 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003762 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003763 // This is the first "real" definition of the namespace "std", so update
3764 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003765 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003766 // We had already defined a dummy namespace "std". Link this new
3767 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003768 StdNS->setNextNamespace(Namespc);
3769 StdNS->setLocation(IdentLoc);
3770 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003771 }
3772
3773 // Make our StdNamespace cache point at the first real definition of the
3774 // "std" namespace.
3775 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003776 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003777
3778 PushOnScopeChains(Namespc, DeclRegionScope);
3779 } else {
John McCall9aeed322009-10-01 00:25:31 +00003780 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003781 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003782
3783 // Link the anonymous namespace into its parent.
3784 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003785 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003786 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3787 PrevDecl = TU->getAnonymousNamespace();
3788 TU->setAnonymousNamespace(Namespc);
3789 } else {
3790 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3791 PrevDecl = ND->getAnonymousNamespace();
3792 ND->setAnonymousNamespace(Namespc);
3793 }
3794
3795 // Link the anonymous namespace with its previous declaration.
3796 if (PrevDecl) {
3797 assert(PrevDecl->isAnonymousNamespace());
3798 assert(!PrevDecl->getNextNamespace());
3799 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3800 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003801
3802 if (Namespc->isInline() != PrevDecl->isInline()) {
3803 // inline-ness must match
3804 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3805 << Namespc->isInline();
3806 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3807 Namespc->setInvalidDecl();
3808 // Recover by ignoring the new namespace's inline status.
3809 Namespc->setInline(PrevDecl->isInline());
3810 }
John McCall5fdd7642009-12-16 02:06:49 +00003811 }
John McCall9aeed322009-10-01 00:25:31 +00003812
Douglas Gregora4181472010-03-24 00:46:35 +00003813 CurContext->addDecl(Namespc);
3814
John McCall9aeed322009-10-01 00:25:31 +00003815 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3816 // behaves as if it were replaced by
3817 // namespace unique { /* empty body */ }
3818 // using namespace unique;
3819 // namespace unique { namespace-body }
3820 // where all occurrences of 'unique' in a translation unit are
3821 // replaced by the same identifier and this identifier differs
3822 // from all other identifiers in the entire program.
3823
3824 // We just create the namespace with an empty name and then add an
3825 // implicit using declaration, just like the standard suggests.
3826 //
3827 // CodeGen enforces the "universally unique" aspect by giving all
3828 // declarations semantically contained within an anonymous
3829 // namespace internal linkage.
3830
John McCall5fdd7642009-12-16 02:06:49 +00003831 if (!PrevDecl) {
3832 UsingDirectiveDecl* UD
3833 = UsingDirectiveDecl::Create(Context, CurContext,
3834 /* 'using' */ LBrace,
3835 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00003836 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00003837 /* identifier */ SourceLocation(),
3838 Namespc,
3839 /* Ancestor */ CurContext);
3840 UD->setImplicit();
3841 CurContext->addDecl(UD);
3842 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003843 }
3844
3845 // Although we could have an invalid decl (i.e. the namespace name is a
3846 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003847 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3848 // for the namespace has the declarations that showed up in that particular
3849 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003850 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003851 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003852}
3853
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003854/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3855/// is a namespace alias, returns the namespace it points to.
3856static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3857 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3858 return AD->getNamespace();
3859 return dyn_cast_or_null<NamespaceDecl>(D);
3860}
3861
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003862/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3863/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003864void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003865 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3866 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003867 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003868 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003869 if (Namespc->hasAttr<VisibilityAttr>())
3870 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003871}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003872
John McCall384aff82010-08-25 07:42:41 +00003873CXXRecordDecl *Sema::getStdBadAlloc() const {
3874 return cast_or_null<CXXRecordDecl>(
3875 StdBadAlloc.get(Context.getExternalSource()));
3876}
3877
3878NamespaceDecl *Sema::getStdNamespace() const {
3879 return cast_or_null<NamespaceDecl>(
3880 StdNamespace.get(Context.getExternalSource()));
3881}
3882
Douglas Gregor66992202010-06-29 17:53:46 +00003883/// \brief Retrieve the special "std" namespace, which may require us to
3884/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003885NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003886 if (!StdNamespace) {
3887 // The "std" namespace has not yet been defined, so build one implicitly.
3888 StdNamespace = NamespaceDecl::Create(Context,
3889 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003890 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00003891 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003892 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003893 }
3894
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003895 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003896}
3897
Douglas Gregor9172aa62011-03-26 22:25:30 +00003898/// \brief Determine whether a using statement is in a context where it will be
3899/// apply in all contexts.
3900static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3901 switch (CurContext->getDeclKind()) {
3902 case Decl::TranslationUnit:
3903 return true;
3904 case Decl::LinkageSpec:
3905 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3906 default:
3907 return false;
3908 }
3909}
3910
John McCalld226f652010-08-21 09:40:31 +00003911Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003912 SourceLocation UsingLoc,
3913 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003914 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003915 SourceLocation IdentLoc,
3916 IdentifierInfo *NamespcName,
3917 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003918 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3919 assert(NamespcName && "Invalid NamespcName.");
3920 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003921
3922 // This can only happen along a recovery path.
3923 while (S->getFlags() & Scope::TemplateParamScope)
3924 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003925 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003926
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003927 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003928 NestedNameSpecifier *Qualifier = 0;
3929 if (SS.isSet())
3930 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3931
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003932 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003933 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3934 LookupParsedName(R, S, &SS);
3935 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003936 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003937
Douglas Gregor66992202010-06-29 17:53:46 +00003938 if (R.empty()) {
3939 // Allow "using namespace std;" or "using namespace ::std;" even if
3940 // "std" hasn't been defined yet, for GCC compatibility.
3941 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3942 NamespcName->isStr("std")) {
3943 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003944 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003945 R.resolveKind();
3946 }
3947 // Otherwise, attempt typo correction.
3948 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3949 CTC_NoKeywords, 0)) {
3950 if (R.getAsSingle<NamespaceDecl>() ||
3951 R.getAsSingle<NamespaceAliasDecl>()) {
3952 if (DeclContext *DC = computeDeclContext(SS, false))
3953 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3954 << NamespcName << DC << Corrected << SS.getRange()
3955 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3956 else
3957 Diag(IdentLoc, diag::err_using_directive_suggest)
3958 << NamespcName << Corrected
3959 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3960 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3961 << Corrected;
3962
3963 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003964 } else {
3965 R.clear();
3966 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003967 }
3968 }
3969 }
3970
John McCallf36e02d2009-10-09 21:13:30 +00003971 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003972 NamedDecl *Named = R.getFoundDecl();
3973 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3974 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003975 // C++ [namespace.udir]p1:
3976 // A using-directive specifies that the names in the nominated
3977 // namespace can be used in the scope in which the
3978 // using-directive appears after the using-directive. During
3979 // unqualified name lookup (3.4.1), the names appear as if they
3980 // were declared in the nearest enclosing namespace which
3981 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003982 // namespace. [Note: in this context, "contains" means "contains
3983 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003984
3985 // Find enclosing context containing both using-directive and
3986 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003987 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003988 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3989 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3990 CommonAncestor = CommonAncestor->getParent();
3991
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003992 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00003993 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003994 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003995
Douglas Gregor9172aa62011-03-26 22:25:30 +00003996 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00003997 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003998 Diag(IdentLoc, diag::warn_using_directive_in_header);
3999 }
4000
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004001 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004002 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00004003 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00004004 }
4005
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004006 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00004007 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004008}
4009
4010void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4011 // If scope has associated entity, then using directive is at namespace
4012 // or translation unit scope. We add UsingDirectiveDecls, into
4013 // it's lookup structure.
4014 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004015 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004016 else
4017 // Otherwise it is block-sope. using-directives will affect lookup
4018 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00004019 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004020}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004021
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004022
John McCalld226f652010-08-21 09:40:31 +00004023Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00004024 AccessSpecifier AS,
4025 bool HasUsingKeyword,
4026 SourceLocation UsingLoc,
4027 CXXScopeSpec &SS,
4028 UnqualifiedId &Name,
4029 AttributeList *AttrList,
4030 bool IsTypeName,
4031 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004032 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Douglas Gregor12c118a2009-11-04 16:30:06 +00004034 switch (Name.getKind()) {
4035 case UnqualifiedId::IK_Identifier:
4036 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00004037 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004038 case UnqualifiedId::IK_ConversionFunctionId:
4039 break;
4040
4041 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00004042 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00004043 // C++0x inherited constructors.
4044 if (getLangOptions().CPlusPlus0x) break;
4045
Douglas Gregor12c118a2009-11-04 16:30:06 +00004046 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4047 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004048 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004049
4050 case UnqualifiedId::IK_DestructorName:
4051 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4052 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004053 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004054
4055 case UnqualifiedId::IK_TemplateId:
4056 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4057 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00004058 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00004059 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004060
4061 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4062 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00004063 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00004064 return 0;
John McCall604e7f12009-12-08 07:46:18 +00004065
John McCall60fa3cf2009-12-11 02:10:03 +00004066 // Warn about using declarations.
4067 // TODO: store that the declaration was written without 'using' and
4068 // talk about access decls instead of using decls in the
4069 // diagnostics.
4070 if (!HasUsingKeyword) {
4071 UsingLoc = Name.getSourceRange().getBegin();
4072
4073 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00004074 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00004075 }
4076
Douglas Gregor56c04582010-12-16 00:46:58 +00004077 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4078 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4079 return 0;
4080
John McCall9488ea12009-11-17 05:59:44 +00004081 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004082 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004083 /* IsInstantiation */ false,
4084 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00004085 if (UD)
4086 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00004087
John McCalld226f652010-08-21 09:40:31 +00004088 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00004089}
4090
Douglas Gregor09acc982010-07-07 23:08:52 +00004091/// \brief Determine whether a using declaration considers the given
4092/// declarations as "equivalent", e.g., if they are redeclarations of
4093/// the same entity or are both typedefs of the same type.
4094static bool
4095IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4096 bool &SuppressRedeclaration) {
4097 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4098 SuppressRedeclaration = false;
4099 return true;
4100 }
4101
Richard Smith162e1c12011-04-15 14:24:37 +00004102 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4103 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00004104 SuppressRedeclaration = true;
4105 return Context.hasSameType(TD1->getUnderlyingType(),
4106 TD2->getUnderlyingType());
4107 }
4108
4109 return false;
4110}
4111
4112
John McCall9f54ad42009-12-10 09:41:52 +00004113/// Determines whether to create a using shadow decl for a particular
4114/// decl, given the set of decls existing prior to this using lookup.
4115bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4116 const LookupResult &Previous) {
4117 // Diagnose finding a decl which is not from a base class of the
4118 // current class. We do this now because there are cases where this
4119 // function will silently decide not to build a shadow decl, which
4120 // will pre-empt further diagnostics.
4121 //
4122 // We don't need to do this in C++0x because we do the check once on
4123 // the qualifier.
4124 //
4125 // FIXME: diagnose the following if we care enough:
4126 // struct A { int foo; };
4127 // struct B : A { using A::foo; };
4128 // template <class T> struct C : A {};
4129 // template <class T> struct D : C<T> { using B::foo; } // <---
4130 // This is invalid (during instantiation) in C++03 because B::foo
4131 // resolves to the using decl in B, which is not a base class of D<T>.
4132 // We can't diagnose it immediately because C<T> is an unknown
4133 // specialization. The UsingShadowDecl in D<T> then points directly
4134 // to A::foo, which will look well-formed when we instantiate.
4135 // The right solution is to not collapse the shadow-decl chain.
4136 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4137 DeclContext *OrigDC = Orig->getDeclContext();
4138
4139 // Handle enums and anonymous structs.
4140 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4141 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4142 while (OrigRec->isAnonymousStructOrUnion())
4143 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4144
4145 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4146 if (OrigDC == CurContext) {
4147 Diag(Using->getLocation(),
4148 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004149 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004150 Diag(Orig->getLocation(), diag::note_using_decl_target);
4151 return true;
4152 }
4153
Douglas Gregordc355712011-02-25 00:36:19 +00004154 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00004155 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004156 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00004157 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00004158 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004159 Diag(Orig->getLocation(), diag::note_using_decl_target);
4160 return true;
4161 }
4162 }
4163
4164 if (Previous.empty()) return false;
4165
4166 NamedDecl *Target = Orig;
4167 if (isa<UsingShadowDecl>(Target))
4168 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4169
John McCalld7533ec2009-12-11 02:33:26 +00004170 // If the target happens to be one of the previous declarations, we
4171 // don't have a conflict.
4172 //
4173 // FIXME: but we might be increasing its access, in which case we
4174 // should redeclare it.
4175 NamedDecl *NonTag = 0, *Tag = 0;
4176 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4177 I != E; ++I) {
4178 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00004179 bool Result;
4180 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4181 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00004182
4183 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4184 }
4185
John McCall9f54ad42009-12-10 09:41:52 +00004186 if (Target->isFunctionOrFunctionTemplate()) {
4187 FunctionDecl *FD;
4188 if (isa<FunctionTemplateDecl>(Target))
4189 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4190 else
4191 FD = cast<FunctionDecl>(Target);
4192
4193 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00004194 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00004195 case Ovl_Overload:
4196 return false;
4197
4198 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00004199 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004200 break;
4201
4202 // We found a decl with the exact signature.
4203 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004204 // If we're in a record, we want to hide the target, so we
4205 // return true (without a diagnostic) to tell the caller not to
4206 // build a shadow decl.
4207 if (CurContext->isRecord())
4208 return true;
4209
4210 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00004211 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004212 break;
4213 }
4214
4215 Diag(Target->getLocation(), diag::note_using_decl_target);
4216 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4217 return true;
4218 }
4219
4220 // Target is not a function.
4221
John McCall9f54ad42009-12-10 09:41:52 +00004222 if (isa<TagDecl>(Target)) {
4223 // No conflict between a tag and a non-tag.
4224 if (!Tag) return false;
4225
John McCall41ce66f2009-12-10 19:51:03 +00004226 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004227 Diag(Target->getLocation(), diag::note_using_decl_target);
4228 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4229 return true;
4230 }
4231
4232 // No conflict between a tag and a non-tag.
4233 if (!NonTag) return false;
4234
John McCall41ce66f2009-12-10 19:51:03 +00004235 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004236 Diag(Target->getLocation(), diag::note_using_decl_target);
4237 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4238 return true;
4239}
4240
John McCall9488ea12009-11-17 05:59:44 +00004241/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004242UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004243 UsingDecl *UD,
4244 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004245
4246 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004247 NamedDecl *Target = Orig;
4248 if (isa<UsingShadowDecl>(Target)) {
4249 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4250 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004251 }
4252
4253 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004254 = UsingShadowDecl::Create(Context, CurContext,
4255 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004256 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004257
4258 Shadow->setAccess(UD->getAccess());
4259 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4260 Shadow->setInvalidDecl();
4261
John McCall9488ea12009-11-17 05:59:44 +00004262 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004263 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004264 else
John McCall604e7f12009-12-08 07:46:18 +00004265 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004266
John McCall604e7f12009-12-08 07:46:18 +00004267
John McCall9f54ad42009-12-10 09:41:52 +00004268 return Shadow;
4269}
John McCall604e7f12009-12-08 07:46:18 +00004270
John McCall9f54ad42009-12-10 09:41:52 +00004271/// Hides a using shadow declaration. This is required by the current
4272/// using-decl implementation when a resolvable using declaration in a
4273/// class is followed by a declaration which would hide or override
4274/// one or more of the using decl's targets; for example:
4275///
4276/// struct Base { void foo(int); };
4277/// struct Derived : Base {
4278/// using Base::foo;
4279/// void foo(int);
4280/// };
4281///
4282/// The governing language is C++03 [namespace.udecl]p12:
4283///
4284/// When a using-declaration brings names from a base class into a
4285/// derived class scope, member functions in the derived class
4286/// override and/or hide member functions with the same name and
4287/// parameter types in a base class (rather than conflicting).
4288///
4289/// There are two ways to implement this:
4290/// (1) optimistically create shadow decls when they're not hidden
4291/// by existing declarations, or
4292/// (2) don't create any shadow decls (or at least don't make them
4293/// visible) until we've fully parsed/instantiated the class.
4294/// The problem with (1) is that we might have to retroactively remove
4295/// a shadow decl, which requires several O(n) operations because the
4296/// decl structures are (very reasonably) not designed for removal.
4297/// (2) avoids this but is very fiddly and phase-dependent.
4298void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004299 if (Shadow->getDeclName().getNameKind() ==
4300 DeclarationName::CXXConversionFunctionName)
4301 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4302
John McCall9f54ad42009-12-10 09:41:52 +00004303 // Remove it from the DeclContext...
4304 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004305
John McCall9f54ad42009-12-10 09:41:52 +00004306 // ...and the scope, if applicable...
4307 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004308 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004309 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004310 }
4311
John McCall9f54ad42009-12-10 09:41:52 +00004312 // ...and the using decl.
4313 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4314
4315 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004316 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004317}
4318
John McCall7ba107a2009-11-18 02:36:19 +00004319/// Builds a using declaration.
4320///
4321/// \param IsInstantiation - Whether this call arises from an
4322/// instantiation of an unresolved using declaration. We treat
4323/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004324NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4325 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004326 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004327 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004328 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004329 bool IsInstantiation,
4330 bool IsTypeName,
4331 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004332 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004333 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004334 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004335
Anders Carlsson550b14b2009-08-28 05:49:21 +00004336 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004337
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004338 if (SS.isEmpty()) {
4339 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004340 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004341 }
Mike Stump1eb44332009-09-09 15:08:12 +00004342
John McCall9f54ad42009-12-10 09:41:52 +00004343 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004344 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004345 ForRedeclaration);
4346 Previous.setHideTags(false);
4347 if (S) {
4348 LookupName(Previous, S);
4349
4350 // It is really dumb that we have to do this.
4351 LookupResult::Filter F = Previous.makeFilter();
4352 while (F.hasNext()) {
4353 NamedDecl *D = F.next();
4354 if (!isDeclInScope(D, CurContext, S))
4355 F.erase();
4356 }
4357 F.done();
4358 } else {
4359 assert(IsInstantiation && "no scope in non-instantiation");
4360 assert(CurContext->isRecord() && "scope not record in instantiation");
4361 LookupQualifiedName(Previous, CurContext);
4362 }
4363
John McCall9f54ad42009-12-10 09:41:52 +00004364 // Check for invalid redeclarations.
4365 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4366 return 0;
4367
4368 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004369 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4370 return 0;
4371
John McCallaf8e6ed2009-11-12 03:15:40 +00004372 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004373 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00004374 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00004375 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004376 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004377 // FIXME: not all declaration name kinds are legal here
4378 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4379 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00004380 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004381 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004382 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004383 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4384 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004385 }
John McCalled976492009-12-04 22:46:56 +00004386 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004387 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4388 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004389 }
John McCalled976492009-12-04 22:46:56 +00004390 D->setAccess(AS);
4391 CurContext->addDecl(D);
4392
4393 if (!LookupContext) return D;
4394 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004395
John McCall77bb1aa2010-05-01 00:40:08 +00004396 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004397 UD->setInvalidDecl();
4398 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004399 }
4400
Sebastian Redlf677ea32011-02-05 19:23:19 +00004401 // Constructor inheriting using decls get special treatment.
4402 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004403 if (CheckInheritedConstructorUsingDecl(UD))
4404 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004405 return UD;
4406 }
4407
4408 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004409
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004410 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004411
John McCall604e7f12009-12-08 07:46:18 +00004412 // Unlike most lookups, we don't always want to hide tag
4413 // declarations: tag names are visible through the using declaration
4414 // even if hidden by ordinary names, *except* in a dependent context
4415 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004416 if (!IsInstantiation)
4417 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004418
John McCalla24dc2e2009-11-17 02:14:36 +00004419 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004420
John McCallf36e02d2009-10-09 21:13:30 +00004421 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004422 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004423 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004424 UD->setInvalidDecl();
4425 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004426 }
4427
John McCalled976492009-12-04 22:46:56 +00004428 if (R.isAmbiguous()) {
4429 UD->setInvalidDecl();
4430 return UD;
4431 }
Mike Stump1eb44332009-09-09 15:08:12 +00004432
John McCall7ba107a2009-11-18 02:36:19 +00004433 if (IsTypeName) {
4434 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004435 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004436 Diag(IdentLoc, diag::err_using_typename_non_type);
4437 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4438 Diag((*I)->getUnderlyingDecl()->getLocation(),
4439 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004440 UD->setInvalidDecl();
4441 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004442 }
4443 } else {
4444 // If we asked for a non-typename and we got a type, error out,
4445 // but only if this is an instantiation of an unresolved using
4446 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004447 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004448 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4449 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004450 UD->setInvalidDecl();
4451 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004452 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004453 }
4454
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004455 // C++0x N2914 [namespace.udecl]p6:
4456 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004457 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004458 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4459 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004460 UD->setInvalidDecl();
4461 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004462 }
Mike Stump1eb44332009-09-09 15:08:12 +00004463
John McCall9f54ad42009-12-10 09:41:52 +00004464 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4465 if (!CheckUsingShadowDecl(UD, *I, Previous))
4466 BuildUsingShadowDecl(S, UD, *I);
4467 }
John McCall9488ea12009-11-17 05:59:44 +00004468
4469 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004470}
4471
Sebastian Redlf677ea32011-02-05 19:23:19 +00004472/// Additional checks for a using declaration referring to a constructor name.
4473bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4474 if (UD->isTypeName()) {
4475 // FIXME: Cannot specify typename when specifying constructor
4476 return true;
4477 }
4478
Douglas Gregordc355712011-02-25 00:36:19 +00004479 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004480 assert(SourceType &&
4481 "Using decl naming constructor doesn't have type in scope spec.");
4482 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4483
4484 // Check whether the named type is a direct base class.
4485 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4486 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4487 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4488 BaseIt != BaseE; ++BaseIt) {
4489 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4490 if (CanonicalSourceType == BaseType)
4491 break;
4492 }
4493
4494 if (BaseIt == BaseE) {
4495 // Did not find SourceType in the bases.
4496 Diag(UD->getUsingLocation(),
4497 diag::err_using_decl_constructor_not_in_direct_base)
4498 << UD->getNameInfo().getSourceRange()
4499 << QualType(SourceType, 0) << TargetClass;
4500 return true;
4501 }
4502
4503 BaseIt->setInheritConstructors();
4504
4505 return false;
4506}
4507
John McCall9f54ad42009-12-10 09:41:52 +00004508/// Checks that the given using declaration is not an invalid
4509/// redeclaration. Note that this is checking only for the using decl
4510/// itself, not for any ill-formedness among the UsingShadowDecls.
4511bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4512 bool isTypeName,
4513 const CXXScopeSpec &SS,
4514 SourceLocation NameLoc,
4515 const LookupResult &Prev) {
4516 // C++03 [namespace.udecl]p8:
4517 // C++0x [namespace.udecl]p10:
4518 // A using-declaration is a declaration and can therefore be used
4519 // repeatedly where (and only where) multiple declarations are
4520 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004521 //
John McCall8a726212010-11-29 18:01:58 +00004522 // That's in non-member contexts.
4523 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004524 return false;
4525
4526 NestedNameSpecifier *Qual
4527 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4528
4529 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4530 NamedDecl *D = *I;
4531
4532 bool DTypename;
4533 NestedNameSpecifier *DQual;
4534 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4535 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00004536 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004537 } else if (UnresolvedUsingValueDecl *UD
4538 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4539 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00004540 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004541 } else if (UnresolvedUsingTypenameDecl *UD
4542 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4543 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00004544 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004545 } else continue;
4546
4547 // using decls differ if one says 'typename' and the other doesn't.
4548 // FIXME: non-dependent using decls?
4549 if (isTypeName != DTypename) continue;
4550
4551 // using decls differ if they name different scopes (but note that
4552 // template instantiation can cause this check to trigger when it
4553 // didn't before instantiation).
4554 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4555 Context.getCanonicalNestedNameSpecifier(DQual))
4556 continue;
4557
4558 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004559 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004560 return true;
4561 }
4562
4563 return false;
4564}
4565
John McCall604e7f12009-12-08 07:46:18 +00004566
John McCalled976492009-12-04 22:46:56 +00004567/// Checks that the given nested-name qualifier used in a using decl
4568/// in the current context is appropriately related to the current
4569/// scope. If an error is found, diagnoses it and returns true.
4570bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4571 const CXXScopeSpec &SS,
4572 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004573 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004574
John McCall604e7f12009-12-08 07:46:18 +00004575 if (!CurContext->isRecord()) {
4576 // C++03 [namespace.udecl]p3:
4577 // C++0x [namespace.udecl]p8:
4578 // A using-declaration for a class member shall be a member-declaration.
4579
4580 // If we weren't able to compute a valid scope, it must be a
4581 // dependent class scope.
4582 if (!NamedContext || NamedContext->isRecord()) {
4583 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4584 << SS.getRange();
4585 return true;
4586 }
4587
4588 // Otherwise, everything is known to be fine.
4589 return false;
4590 }
4591
4592 // The current scope is a record.
4593
4594 // If the named context is dependent, we can't decide much.
4595 if (!NamedContext) {
4596 // FIXME: in C++0x, we can diagnose if we can prove that the
4597 // nested-name-specifier does not refer to a base class, which is
4598 // still possible in some cases.
4599
4600 // Otherwise we have to conservatively report that things might be
4601 // okay.
4602 return false;
4603 }
4604
4605 if (!NamedContext->isRecord()) {
4606 // Ideally this would point at the last name in the specifier,
4607 // but we don't have that level of source info.
4608 Diag(SS.getRange().getBegin(),
4609 diag::err_using_decl_nested_name_specifier_is_not_class)
4610 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4611 return true;
4612 }
4613
Douglas Gregor6fb07292010-12-21 07:41:49 +00004614 if (!NamedContext->isDependentContext() &&
4615 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4616 return true;
4617
John McCall604e7f12009-12-08 07:46:18 +00004618 if (getLangOptions().CPlusPlus0x) {
4619 // C++0x [namespace.udecl]p3:
4620 // In a using-declaration used as a member-declaration, the
4621 // nested-name-specifier shall name a base class of the class
4622 // being defined.
4623
4624 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4625 cast<CXXRecordDecl>(NamedContext))) {
4626 if (CurContext == NamedContext) {
4627 Diag(NameLoc,
4628 diag::err_using_decl_nested_name_specifier_is_current_class)
4629 << SS.getRange();
4630 return true;
4631 }
4632
4633 Diag(SS.getRange().getBegin(),
4634 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4635 << (NestedNameSpecifier*) SS.getScopeRep()
4636 << cast<CXXRecordDecl>(CurContext)
4637 << SS.getRange();
4638 return true;
4639 }
4640
4641 return false;
4642 }
4643
4644 // C++03 [namespace.udecl]p4:
4645 // A using-declaration used as a member-declaration shall refer
4646 // to a member of a base class of the class being defined [etc.].
4647
4648 // Salient point: SS doesn't have to name a base class as long as
4649 // lookup only finds members from base classes. Therefore we can
4650 // diagnose here only if we can prove that that can't happen,
4651 // i.e. if the class hierarchies provably don't intersect.
4652
4653 // TODO: it would be nice if "definitely valid" results were cached
4654 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4655 // need to be repeated.
4656
4657 struct UserData {
4658 llvm::DenseSet<const CXXRecordDecl*> Bases;
4659
4660 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4661 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4662 Data->Bases.insert(Base);
4663 return true;
4664 }
4665
4666 bool hasDependentBases(const CXXRecordDecl *Class) {
4667 return !Class->forallBases(collect, this);
4668 }
4669
4670 /// Returns true if the base is dependent or is one of the
4671 /// accumulated base classes.
4672 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4673 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4674 return !Data->Bases.count(Base);
4675 }
4676
4677 bool mightShareBases(const CXXRecordDecl *Class) {
4678 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4679 }
4680 };
4681
4682 UserData Data;
4683
4684 // Returns false if we find a dependent base.
4685 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4686 return false;
4687
4688 // Returns false if the class has a dependent base or if it or one
4689 // of its bases is present in the base set of the current context.
4690 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4691 return false;
4692
4693 Diag(SS.getRange().getBegin(),
4694 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4695 << (NestedNameSpecifier*) SS.getScopeRep()
4696 << cast<CXXRecordDecl>(CurContext)
4697 << SS.getRange();
4698
4699 return true;
John McCalled976492009-12-04 22:46:56 +00004700}
4701
Richard Smith162e1c12011-04-15 14:24:37 +00004702Decl *Sema::ActOnAliasDeclaration(Scope *S,
4703 AccessSpecifier AS,
4704 SourceLocation UsingLoc,
4705 UnqualifiedId &Name,
4706 TypeResult Type) {
4707 assert((S->getFlags() & Scope::DeclScope) &&
4708 "got alias-declaration outside of declaration scope");
4709
4710 if (Type.isInvalid())
4711 return 0;
4712
4713 bool Invalid = false;
4714 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4715 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00004716 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00004717
4718 if (DiagnoseClassNameShadow(CurContext, NameInfo))
4719 return 0;
4720
4721 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
4722 UPPC_DeclarationType))
4723 Invalid = true;
4724
4725 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4726 LookupName(Previous, S);
4727
4728 // Warn about shadowing the name of a template parameter.
4729 if (Previous.isSingleResult() &&
4730 Previous.getFoundDecl()->isTemplateParameter()) {
4731 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4732 Previous.getFoundDecl()))
4733 Invalid = true;
4734 Previous.clear();
4735 }
4736
4737 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4738 "name in alias declaration must be an identifier");
4739 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4740 Name.StartLocation,
4741 Name.Identifier, TInfo);
4742
4743 NewTD->setAccess(AS);
4744
4745 if (Invalid)
4746 NewTD->setInvalidDecl();
4747
4748 bool Redeclaration = false;
4749 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
4750
4751 if (!Redeclaration)
4752 PushOnScopeChains(NewTD, S);
4753
4754 return NewTD;
4755}
4756
John McCalld226f652010-08-21 09:40:31 +00004757Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004758 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004759 SourceLocation AliasLoc,
4760 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004761 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004762 SourceLocation IdentLoc,
4763 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Anders Carlsson81c85c42009-03-28 23:53:49 +00004765 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004766 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4767 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004768
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004769 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004770 NamedDecl *PrevDecl
4771 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4772 ForRedeclaration);
4773 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4774 PrevDecl = 0;
4775
4776 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004777 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004778 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004779 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004780 // FIXME: At some point, we'll want to create the (redundant)
4781 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004782 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004783 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004784 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004785 }
Mike Stump1eb44332009-09-09 15:08:12 +00004786
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004787 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4788 diag::err_redefinition_different_kind;
4789 Diag(AliasLoc, DiagID) << Alias;
4790 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004791 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004792 }
4793
John McCalla24dc2e2009-11-17 02:14:36 +00004794 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004795 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004796
John McCallf36e02d2009-10-09 21:13:30 +00004797 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004798 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4799 CTC_NoKeywords, 0)) {
4800 if (R.getAsSingle<NamespaceDecl>() ||
4801 R.getAsSingle<NamespaceAliasDecl>()) {
4802 if (DeclContext *DC = computeDeclContext(SS, false))
4803 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4804 << Ident << DC << Corrected << SS.getRange()
4805 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4806 else
4807 Diag(IdentLoc, diag::err_using_directive_suggest)
4808 << Ident << Corrected
4809 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4810
4811 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4812 << Corrected;
4813
4814 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004815 } else {
4816 R.clear();
4817 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004818 }
4819 }
4820
4821 if (R.empty()) {
4822 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004823 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004824 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004825 }
Mike Stump1eb44332009-09-09 15:08:12 +00004826
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004827 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004828 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00004829 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00004830 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004831
John McCall3dbd3d52010-02-16 06:53:13 +00004832 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004833 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004834}
4835
Douglas Gregor39957dc2010-05-01 15:04:51 +00004836namespace {
4837 /// \brief Scoped object used to handle the state changes required in Sema
4838 /// to implicitly define the body of a C++ member function;
4839 class ImplicitlyDefinedFunctionScope {
4840 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004841 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004842
4843 public:
4844 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004845 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004846 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004847 S.PushFunctionScope();
4848 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4849 }
4850
4851 ~ImplicitlyDefinedFunctionScope() {
4852 S.PopExpressionEvaluationContext();
4853 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004854 }
4855 };
4856}
4857
Sebastian Redl751025d2010-09-13 22:02:47 +00004858static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4859 CXXRecordDecl *D) {
4860 ASTContext &Context = Self.Context;
4861 QualType ClassType = Context.getTypeDeclType(D);
4862 DeclarationName ConstructorName
4863 = Context.DeclarationNames.getCXXConstructorName(
4864 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4865
4866 DeclContext::lookup_const_iterator Con, ConEnd;
4867 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4868 Con != ConEnd; ++Con) {
4869 // FIXME: In C++0x, a constructor template can be a default constructor.
4870 if (isa<FunctionTemplateDecl>(*Con))
4871 continue;
4872
4873 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4874 if (Constructor->isDefaultConstructor())
4875 return Constructor;
4876 }
4877 return 0;
4878}
4879
Douglas Gregor23c94db2010-07-02 17:43:08 +00004880CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4881 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004882 // C++ [class.ctor]p5:
4883 // A default constructor for a class X is a constructor of class X
4884 // that can be called without an argument. If there is no
4885 // user-declared constructor for class X, a default constructor is
4886 // implicitly declared. An implicitly-declared default constructor
4887 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004888 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4889 "Should not build implicit default constructor!");
4890
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004891 // C++ [except.spec]p14:
4892 // An implicitly declared special member function (Clause 12) shall have an
4893 // exception-specification. [...]
4894 ImplicitExceptionSpecification ExceptSpec(Context);
4895
Sebastian Redl60618fa2011-03-12 11:50:43 +00004896 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004897 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4898 BEnd = ClassDecl->bases_end();
4899 B != BEnd; ++B) {
4900 if (B->isVirtual()) // Handled below.
4901 continue;
4902
Douglas Gregor18274032010-07-03 00:47:00 +00004903 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4904 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4905 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4906 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004907 else if (CXXConstructorDecl *Constructor
4908 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004909 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004910 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004911 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004912
4913 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004914 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4915 BEnd = ClassDecl->vbases_end();
4916 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004917 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4918 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4919 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4920 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4921 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004922 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004923 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004924 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004925 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004926
4927 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004928 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4929 FEnd = ClassDecl->field_end();
4930 F != FEnd; ++F) {
4931 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004932 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4933 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4934 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4935 ExceptSpec.CalledDecl(
4936 DeclareImplicitDefaultConstructor(FieldClassDecl));
4937 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004938 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004939 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004940 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004941 }
John McCalle23cf432010-12-14 08:05:40 +00004942
4943 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00004944 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00004945 EPI.NumExceptions = ExceptSpec.size();
4946 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00004947
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004948 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004949 CanQualType ClassType
4950 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004951 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00004952 DeclarationName Name
4953 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004954 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00004955 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004956 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004957 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004958 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004959 /*TInfo=*/0,
4960 /*isExplicit=*/false,
4961 /*isInline=*/true,
4962 /*isImplicitlyDeclared=*/true);
4963 DefaultCon->setAccess(AS_public);
4964 DefaultCon->setImplicit();
4965 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004966
4967 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004968 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4969
Douglas Gregor23c94db2010-07-02 17:43:08 +00004970 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004971 PushOnScopeChains(DefaultCon, S, false);
4972 ClassDecl->addDecl(DefaultCon);
4973
Douglas Gregor32df23e2010-07-01 22:02:46 +00004974 return DefaultCon;
4975}
4976
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004977void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4978 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004979 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004980 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004981 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004982
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004983 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004984 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004985
Douglas Gregor39957dc2010-05-01 15:04:51 +00004986 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004987 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004988 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004989 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004990 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004991 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004992 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004993 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004994 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004995
4996 SourceLocation Loc = Constructor->getLocation();
4997 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4998
4999 Constructor->setUsed();
5000 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005001
5002 if (ASTMutationListener *L = getASTMutationListener()) {
5003 L->CompletedImplicitDefinition(Constructor);
5004 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005005}
5006
Sebastian Redlf677ea32011-02-05 19:23:19 +00005007void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
5008 // We start with an initial pass over the base classes to collect those that
5009 // inherit constructors from. If there are none, we can forgo all further
5010 // processing.
5011 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
5012 BasesVector BasesToInheritFrom;
5013 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
5014 BaseE = ClassDecl->bases_end();
5015 BaseIt != BaseE; ++BaseIt) {
5016 if (BaseIt->getInheritConstructors()) {
5017 QualType Base = BaseIt->getType();
5018 if (Base->isDependentType()) {
5019 // If we inherit constructors from anything that is dependent, just
5020 // abort processing altogether. We'll get another chance for the
5021 // instantiations.
5022 return;
5023 }
5024 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
5025 }
5026 }
5027 if (BasesToInheritFrom.empty())
5028 return;
5029
5030 // Now collect the constructors that we already have in the current class.
5031 // Those take precedence over inherited constructors.
5032 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5033 // unless there is a user-declared constructor with the same signature in
5034 // the class where the using-declaration appears.
5035 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5036 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5037 CtorE = ClassDecl->ctor_end();
5038 CtorIt != CtorE; ++CtorIt) {
5039 ExistingConstructors.insert(
5040 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5041 }
5042
5043 Scope *S = getScopeForContext(ClassDecl);
5044 DeclarationName CreatedCtorName =
5045 Context.DeclarationNames.getCXXConstructorName(
5046 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5047
5048 // Now comes the true work.
5049 // First, we keep a map from constructor types to the base that introduced
5050 // them. Needed for finding conflicting constructors. We also keep the
5051 // actually inserted declarations in there, for pretty diagnostics.
5052 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5053 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5054 ConstructorToSourceMap InheritedConstructors;
5055 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5056 BaseE = BasesToInheritFrom.end();
5057 BaseIt != BaseE; ++BaseIt) {
5058 const RecordType *Base = *BaseIt;
5059 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5060 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5061 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5062 CtorE = BaseDecl->ctor_end();
5063 CtorIt != CtorE; ++CtorIt) {
5064 // Find the using declaration for inheriting this base's constructors.
5065 DeclarationName Name =
5066 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5067 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5068 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5069 SourceLocation UsingLoc = UD ? UD->getLocation() :
5070 ClassDecl->getLocation();
5071
5072 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5073 // from the class X named in the using-declaration consists of actual
5074 // constructors and notional constructors that result from the
5075 // transformation of defaulted parameters as follows:
5076 // - all non-template default constructors of X, and
5077 // - for each non-template constructor of X that has at least one
5078 // parameter with a default argument, the set of constructors that
5079 // results from omitting any ellipsis parameter specification and
5080 // successively omitting parameters with a default argument from the
5081 // end of the parameter-type-list.
5082 CXXConstructorDecl *BaseCtor = *CtorIt;
5083 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5084 const FunctionProtoType *BaseCtorType =
5085 BaseCtor->getType()->getAs<FunctionProtoType>();
5086
5087 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5088 maxParams = BaseCtor->getNumParams();
5089 params <= maxParams; ++params) {
5090 // Skip default constructors. They're never inherited.
5091 if (params == 0)
5092 continue;
5093 // Skip copy and move constructors for the same reason.
5094 if (CanBeCopyOrMove && params == 1)
5095 continue;
5096
5097 // Build up a function type for this particular constructor.
5098 // FIXME: The working paper does not consider that the exception spec
5099 // for the inheriting constructor might be larger than that of the
5100 // source. This code doesn't yet, either.
5101 const Type *NewCtorType;
5102 if (params == maxParams)
5103 NewCtorType = BaseCtorType;
5104 else {
5105 llvm::SmallVector<QualType, 16> Args;
5106 for (unsigned i = 0; i < params; ++i) {
5107 Args.push_back(BaseCtorType->getArgType(i));
5108 }
5109 FunctionProtoType::ExtProtoInfo ExtInfo =
5110 BaseCtorType->getExtProtoInfo();
5111 ExtInfo.Variadic = false;
5112 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5113 Args.data(), params, ExtInfo)
5114 .getTypePtr();
5115 }
5116 const Type *CanonicalNewCtorType =
5117 Context.getCanonicalType(NewCtorType);
5118
5119 // Now that we have the type, first check if the class already has a
5120 // constructor with this signature.
5121 if (ExistingConstructors.count(CanonicalNewCtorType))
5122 continue;
5123
5124 // Then we check if we have already declared an inherited constructor
5125 // with this signature.
5126 std::pair<ConstructorToSourceMap::iterator, bool> result =
5127 InheritedConstructors.insert(std::make_pair(
5128 CanonicalNewCtorType,
5129 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5130 if (!result.second) {
5131 // Already in the map. If it came from a different class, that's an
5132 // error. Not if it's from the same.
5133 CanQualType PreviousBase = result.first->second.first;
5134 if (CanonicalBase != PreviousBase) {
5135 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5136 const CXXConstructorDecl *PrevBaseCtor =
5137 PrevCtor->getInheritedConstructor();
5138 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5139
5140 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5141 Diag(BaseCtor->getLocation(),
5142 diag::note_using_decl_constructor_conflict_current_ctor);
5143 Diag(PrevBaseCtor->getLocation(),
5144 diag::note_using_decl_constructor_conflict_previous_ctor);
5145 Diag(PrevCtor->getLocation(),
5146 diag::note_using_decl_constructor_conflict_previous_using);
5147 }
5148 continue;
5149 }
5150
5151 // OK, we're there, now add the constructor.
5152 // C++0x [class.inhctor]p8: [...] that would be performed by a
5153 // user-writtern inline constructor [...]
5154 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5155 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005156 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5157 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005158 /*ImplicitlyDeclared=*/true);
5159 NewCtor->setAccess(BaseCtor->getAccess());
5160
5161 // Build up the parameter decls and add them.
5162 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5163 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005164 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5165 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005166 /*IdentifierInfo=*/0,
5167 BaseCtorType->getArgType(i),
5168 /*TInfo=*/0, SC_None,
5169 SC_None, /*DefaultArg=*/0));
5170 }
5171 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5172 NewCtor->setInheritedConstructor(BaseCtor);
5173
5174 PushOnScopeChains(NewCtor, S, false);
5175 ClassDecl->addDecl(NewCtor);
5176 result.first->second.second = NewCtor;
5177 }
5178 }
5179 }
5180}
5181
Douglas Gregor23c94db2010-07-02 17:43:08 +00005182CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005183 // C++ [class.dtor]p2:
5184 // If a class has no user-declared destructor, a destructor is
5185 // declared implicitly. An implicitly-declared destructor is an
5186 // inline public member of its class.
5187
5188 // C++ [except.spec]p14:
5189 // An implicitly declared special member function (Clause 12) shall have
5190 // an exception-specification.
5191 ImplicitExceptionSpecification ExceptSpec(Context);
5192
5193 // Direct base-class destructors.
5194 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5195 BEnd = ClassDecl->bases_end();
5196 B != BEnd; ++B) {
5197 if (B->isVirtual()) // Handled below.
5198 continue;
5199
5200 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5201 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005202 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005203 }
5204
5205 // Virtual base-class destructors.
5206 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5207 BEnd = ClassDecl->vbases_end();
5208 B != BEnd; ++B) {
5209 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5210 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005211 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005212 }
5213
5214 // Field destructors.
5215 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5216 FEnd = ClassDecl->field_end();
5217 F != FEnd; ++F) {
5218 if (const RecordType *RecordTy
5219 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5220 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005221 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005222 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005223
Douglas Gregor4923aa22010-07-02 20:37:36 +00005224 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00005225 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005226 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005227 EPI.NumExceptions = ExceptSpec.size();
5228 EPI.Exceptions = ExceptSpec.data();
5229 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00005230
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005231 CanQualType ClassType
5232 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005233 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005234 DeclarationName Name
5235 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005236 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005237 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00005238 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5239 /*isInline=*/true,
5240 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005241 Destructor->setAccess(AS_public);
5242 Destructor->setImplicit();
5243 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00005244
5245 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00005246 ++ASTContext::NumImplicitDestructorsDeclared;
5247
5248 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005249 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00005250 PushOnScopeChains(Destructor, S, false);
5251 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005252
5253 // This could be uniqued if it ever proves significant.
5254 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5255
5256 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00005257
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005258 return Destructor;
5259}
5260
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005261void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00005262 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00005263 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005264 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00005265 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005266 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005267
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005268 if (Destructor->isInvalidDecl())
5269 return;
5270
Douglas Gregor39957dc2010-05-01 15:04:51 +00005271 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005272
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005273 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00005274 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5275 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00005276
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005277 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005278 Diag(CurrentLocation, diag::note_member_synthesized_at)
5279 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5280
5281 Destructor->setInvalidDecl();
5282 return;
5283 }
5284
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005285 SourceLocation Loc = Destructor->getLocation();
5286 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5287
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005288 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005289 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005290
5291 if (ASTMutationListener *L = getASTMutationListener()) {
5292 L->CompletedImplicitDefinition(Destructor);
5293 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005294}
5295
Douglas Gregor06a9f362010-05-01 20:49:11 +00005296/// \brief Builds a statement that copies the given entity from \p From to
5297/// \c To.
5298///
5299/// This routine is used to copy the members of a class with an
5300/// implicitly-declared copy assignment operator. When the entities being
5301/// copied are arrays, this routine builds for loops to copy them.
5302///
5303/// \param S The Sema object used for type-checking.
5304///
5305/// \param Loc The location where the implicit copy is being generated.
5306///
5307/// \param T The type of the expressions being copied. Both expressions must
5308/// have this type.
5309///
5310/// \param To The expression we are copying to.
5311///
5312/// \param From The expression we are copying from.
5313///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005314/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5315/// Otherwise, it's a non-static member subobject.
5316///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005317/// \param Depth Internal parameter recording the depth of the recursion.
5318///
5319/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005320static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005321BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005322 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005323 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005324 // C++0x [class.copy]p30:
5325 // Each subobject is assigned in the manner appropriate to its type:
5326 //
5327 // - if the subobject is of class type, the copy assignment operator
5328 // for the class is used (as if by explicit qualification; that is,
5329 // ignoring any possible virtual overriding functions in more derived
5330 // classes);
5331 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5332 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5333
5334 // Look for operator=.
5335 DeclarationName Name
5336 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5337 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5338 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5339
5340 // Filter out any result that isn't a copy-assignment operator.
5341 LookupResult::Filter F = OpLookup.makeFilter();
5342 while (F.hasNext()) {
5343 NamedDecl *D = F.next();
5344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5345 if (Method->isCopyAssignmentOperator())
5346 continue;
5347
5348 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005349 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005350 F.done();
5351
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005352 // Suppress the protected check (C++ [class.protected]) for each of the
5353 // assignment operators we found. This strange dance is required when
5354 // we're assigning via a base classes's copy-assignment operator. To
5355 // ensure that we're getting the right base class subobject (without
5356 // ambiguities), we need to cast "this" to that subobject type; to
5357 // ensure that we don't go through the virtual call mechanism, we need
5358 // to qualify the operator= name with the base class (see below). However,
5359 // this means that if the base class has a protected copy assignment
5360 // operator, the protected member access check will fail. So, we
5361 // rewrite "protected" access to "public" access in this case, since we
5362 // know by construction that we're calling from a derived class.
5363 if (CopyingBaseSubobject) {
5364 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5365 L != LEnd; ++L) {
5366 if (L.getAccess() == AS_protected)
5367 L.setAccess(AS_public);
5368 }
5369 }
5370
Douglas Gregor06a9f362010-05-01 20:49:11 +00005371 // Create the nested-name-specifier that will be used to qualify the
5372 // reference to operator=; this is required to suppress the virtual
5373 // call mechanism.
5374 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00005375 SS.MakeTrivial(S.Context,
5376 NestedNameSpecifier::Create(S.Context, 0, false,
5377 T.getTypePtr()),
5378 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005379
5380 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005381 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005382 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005383 /*FirstQualifierInScope=*/0, OpLookup,
5384 /*TemplateArgs=*/0,
5385 /*SuppressQualifierCheck=*/true);
5386 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005387 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005388
5389 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005390
John McCall60d7b3a2010-08-24 06:29:42 +00005391 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005392 OpEqualRef.takeAs<Expr>(),
5393 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005394 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005395 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005396
5397 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005398 }
John McCallb0207482010-03-16 06:11:48 +00005399
Douglas Gregor06a9f362010-05-01 20:49:11 +00005400 // - if the subobject is of scalar type, the built-in assignment
5401 // operator is used.
5402 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5403 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005404 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005405 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005406 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005407
5408 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005409 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005410
5411 // - if the subobject is an array, each element is assigned, in the
5412 // manner appropriate to the element type;
5413
5414 // Construct a loop over the array bounds, e.g.,
5415 //
5416 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5417 //
5418 // that will copy each of the array elements.
5419 QualType SizeType = S.Context.getSizeType();
5420
5421 // Create the iteration variable.
5422 IdentifierInfo *IterationVarName = 0;
5423 {
5424 llvm::SmallString<8> Str;
5425 llvm::raw_svector_ostream OS(Str);
5426 OS << "__i" << Depth;
5427 IterationVarName = &S.Context.Idents.get(OS.str());
5428 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005429 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005430 IterationVarName, SizeType,
5431 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005432 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005433
5434 // Initialize the iteration variable to zero.
5435 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005436 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005437
5438 // Create a reference to the iteration variable; we'll use this several
5439 // times throughout.
5440 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005441 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005442 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5443
5444 // Create the DeclStmt that holds the iteration variable.
5445 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5446
5447 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005448 llvm::APInt Upper
5449 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005450 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005451 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005452 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5453 BO_NE, S.Context.BoolTy,
5454 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005455
5456 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005457 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005458 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5459 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005460
5461 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005462 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5463 IterationVarRef, Loc));
5464 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5465 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005466
5467 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005468 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5469 To, From, CopyingBaseSubobject,
5470 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005471 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005472 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005473
5474 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005475 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005476 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005477 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005478 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005479}
5480
Douglas Gregora376d102010-07-02 21:50:04 +00005481/// \brief Determine whether the given class has a copy assignment operator
5482/// that accepts a const-qualified argument.
5483static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5484 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5485
5486 if (!Class->hasDeclaredCopyAssignment())
5487 S.DeclareImplicitCopyAssignment(Class);
5488
5489 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5490 DeclarationName OpName
5491 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5492
5493 DeclContext::lookup_const_iterator Op, OpEnd;
5494 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5495 // C++ [class.copy]p9:
5496 // A user-declared copy assignment operator is a non-static non-template
5497 // member function of class X with exactly one parameter of type X, X&,
5498 // const X&, volatile X& or const volatile X&.
5499 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5500 if (!Method)
5501 continue;
5502
5503 if (Method->isStatic())
5504 continue;
5505 if (Method->getPrimaryTemplate())
5506 continue;
5507 const FunctionProtoType *FnType =
5508 Method->getType()->getAs<FunctionProtoType>();
5509 assert(FnType && "Overloaded operator has no prototype.");
5510 // Don't assert on this; an invalid decl might have been left in the AST.
5511 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5512 continue;
5513 bool AcceptsConst = true;
5514 QualType ArgType = FnType->getArgType(0);
5515 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5516 ArgType = Ref->getPointeeType();
5517 // Is it a non-const lvalue reference?
5518 if (!ArgType.isConstQualified())
5519 AcceptsConst = false;
5520 }
5521 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5522 continue;
5523
5524 // We have a single argument of type cv X or cv X&, i.e. we've found the
5525 // copy assignment operator. Return whether it accepts const arguments.
5526 return AcceptsConst;
5527 }
5528 assert(Class->isInvalidDecl() &&
5529 "No copy assignment operator declared in valid code.");
5530 return false;
5531}
5532
Douglas Gregor23c94db2010-07-02 17:43:08 +00005533CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005534 // Note: The following rules are largely analoguous to the copy
5535 // constructor rules. Note that virtual bases are not taken into account
5536 // for determining the argument type of the operator. Note also that
5537 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005538
5539
Douglas Gregord3c35902010-07-01 16:36:15 +00005540 // C++ [class.copy]p10:
5541 // If the class definition does not explicitly declare a copy
5542 // assignment operator, one is declared implicitly.
5543 // The implicitly-defined copy assignment operator for a class X
5544 // will have the form
5545 //
5546 // X& X::operator=(const X&)
5547 //
5548 // if
5549 bool HasConstCopyAssignment = true;
5550
5551 // -- each direct base class B of X has a copy assignment operator
5552 // whose parameter is of type const B&, const volatile B& or B,
5553 // and
5554 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5555 BaseEnd = ClassDecl->bases_end();
5556 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5557 assert(!Base->getType()->isDependentType() &&
5558 "Cannot generate implicit members for class with dependent bases.");
5559 const CXXRecordDecl *BaseClassDecl
5560 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005561 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005562 }
5563
5564 // -- for all the nonstatic data members of X that are of a class
5565 // type M (or array thereof), each such class type has a copy
5566 // assignment operator whose parameter is of type const M&,
5567 // const volatile M& or M.
5568 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5569 FieldEnd = ClassDecl->field_end();
5570 HasConstCopyAssignment && Field != FieldEnd;
5571 ++Field) {
5572 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5573 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5574 const CXXRecordDecl *FieldClassDecl
5575 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005576 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005577 }
5578 }
5579
5580 // Otherwise, the implicitly declared copy assignment operator will
5581 // have the form
5582 //
5583 // X& X::operator=(X&)
5584 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5585 QualType RetType = Context.getLValueReferenceType(ArgType);
5586 if (HasConstCopyAssignment)
5587 ArgType = ArgType.withConst();
5588 ArgType = Context.getLValueReferenceType(ArgType);
5589
Douglas Gregorb87786f2010-07-01 17:48:08 +00005590 // C++ [except.spec]p14:
5591 // An implicitly declared special member function (Clause 12) shall have an
5592 // exception-specification. [...]
5593 ImplicitExceptionSpecification ExceptSpec(Context);
5594 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5595 BaseEnd = ClassDecl->bases_end();
5596 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005597 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005598 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005599
5600 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5601 DeclareImplicitCopyAssignment(BaseClassDecl);
5602
Douglas Gregorb87786f2010-07-01 17:48:08 +00005603 if (CXXMethodDecl *CopyAssign
5604 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5605 ExceptSpec.CalledDecl(CopyAssign);
5606 }
5607 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5608 FieldEnd = ClassDecl->field_end();
5609 Field != FieldEnd;
5610 ++Field) {
5611 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5612 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005613 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005614 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005615
5616 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5617 DeclareImplicitCopyAssignment(FieldClassDecl);
5618
Douglas Gregorb87786f2010-07-01 17:48:08 +00005619 if (CXXMethodDecl *CopyAssign
5620 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5621 ExceptSpec.CalledDecl(CopyAssign);
5622 }
5623 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005624
Douglas Gregord3c35902010-07-01 16:36:15 +00005625 // An implicitly-declared copy assignment operator is an inline public
5626 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005627 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005628 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005629 EPI.NumExceptions = ExceptSpec.size();
5630 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005631 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005632 SourceLocation ClassLoc = ClassDecl->getLocation();
5633 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00005634 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005635 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005636 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005637 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005638 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00005639 /*isInline=*/true,
5640 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005641 CopyAssignment->setAccess(AS_public);
5642 CopyAssignment->setImplicit();
5643 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005644
5645 // Add the parameter to the operator.
5646 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005647 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00005648 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005649 SC_None,
5650 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005651 CopyAssignment->setParams(&FromParam, 1);
5652
Douglas Gregora376d102010-07-02 21:50:04 +00005653 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005654 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5655
Douglas Gregor23c94db2010-07-02 17:43:08 +00005656 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005657 PushOnScopeChains(CopyAssignment, S, false);
5658 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005659
5660 AddOverriddenMethods(ClassDecl, CopyAssignment);
5661 return CopyAssignment;
5662}
5663
Douglas Gregor06a9f362010-05-01 20:49:11 +00005664void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5665 CXXMethodDecl *CopyAssignOperator) {
5666 assert((CopyAssignOperator->isImplicit() &&
5667 CopyAssignOperator->isOverloadedOperator() &&
5668 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005669 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005670 "DefineImplicitCopyAssignment called for wrong function");
5671
5672 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5673
5674 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5675 CopyAssignOperator->setInvalidDecl();
5676 return;
5677 }
5678
5679 CopyAssignOperator->setUsed();
5680
5681 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005682 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005683
5684 // C++0x [class.copy]p30:
5685 // The implicitly-defined or explicitly-defaulted copy assignment operator
5686 // for a non-union class X performs memberwise copy assignment of its
5687 // subobjects. The direct base classes of X are assigned first, in the
5688 // order of their declaration in the base-specifier-list, and then the
5689 // immediate non-static data members of X are assigned, in the order in
5690 // which they were declared in the class definition.
5691
5692 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005693 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005694
5695 // The parameter for the "other" object, which we are copying from.
5696 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5697 Qualifiers OtherQuals = Other->getType().getQualifiers();
5698 QualType OtherRefType = Other->getType();
5699 if (const LValueReferenceType *OtherRef
5700 = OtherRefType->getAs<LValueReferenceType>()) {
5701 OtherRefType = OtherRef->getPointeeType();
5702 OtherQuals = OtherRefType.getQualifiers();
5703 }
5704
5705 // Our location for everything implicitly-generated.
5706 SourceLocation Loc = CopyAssignOperator->getLocation();
5707
5708 // Construct a reference to the "other" object. We'll be using this
5709 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005710 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005711 assert(OtherRef && "Reference to parameter cannot fail!");
5712
5713 // Construct the "this" pointer. We'll be using this throughout the generated
5714 // ASTs.
5715 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5716 assert(This && "Reference to this cannot fail!");
5717
5718 // Assign base classes.
5719 bool Invalid = false;
5720 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5721 E = ClassDecl->bases_end(); Base != E; ++Base) {
5722 // Form the assignment:
5723 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5724 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005725 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005726 Invalid = true;
5727 continue;
5728 }
5729
John McCallf871d0c2010-08-07 06:22:56 +00005730 CXXCastPath BasePath;
5731 BasePath.push_back(Base);
5732
Douglas Gregor06a9f362010-05-01 20:49:11 +00005733 // Construct the "from" expression, which is an implicit cast to the
5734 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005735 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00005736 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5737 CK_UncheckedDerivedToBase,
5738 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005739
5740 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005741 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005742
5743 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00005744 To = ImpCastExprToType(To.take(),
5745 Context.getCVRQualifiedType(BaseType,
5746 CopyAssignOperator->getTypeQualifiers()),
5747 CK_UncheckedDerivedToBase,
5748 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005749
5750 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005751 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005752 To.get(), From,
5753 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005754 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005755 Diag(CurrentLocation, diag::note_member_synthesized_at)
5756 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5757 CopyAssignOperator->setInvalidDecl();
5758 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005759 }
5760
5761 // Success! Record the copy.
5762 Statements.push_back(Copy.takeAs<Expr>());
5763 }
5764
5765 // \brief Reference to the __builtin_memcpy function.
5766 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005767 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005768 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005769
5770 // Assign non-static members.
5771 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5772 FieldEnd = ClassDecl->field_end();
5773 Field != FieldEnd; ++Field) {
5774 // Check for members of reference type; we can't copy those.
5775 if (Field->getType()->isReferenceType()) {
5776 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5777 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5778 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005779 Diag(CurrentLocation, diag::note_member_synthesized_at)
5780 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005781 Invalid = true;
5782 continue;
5783 }
5784
5785 // Check for members of const-qualified, non-class type.
5786 QualType BaseType = Context.getBaseElementType(Field->getType());
5787 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5788 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5789 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5790 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005791 Diag(CurrentLocation, diag::note_member_synthesized_at)
5792 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005793 Invalid = true;
5794 continue;
5795 }
5796
5797 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005798 if (FieldType->isIncompleteArrayType()) {
5799 assert(ClassDecl->hasFlexibleArrayMember() &&
5800 "Incomplete array type is not valid");
5801 continue;
5802 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005803
5804 // Build references to the field in the object we're copying from and to.
5805 CXXScopeSpec SS; // Intentionally empty
5806 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5807 LookupMemberName);
5808 MemberLookup.addDecl(*Field);
5809 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005810 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005811 Loc, /*IsArrow=*/false,
5812 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005813 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005814 Loc, /*IsArrow=*/true,
5815 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005816 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5817 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5818
5819 // If the field should be copied with __builtin_memcpy rather than via
5820 // explicit assignments, do so. This optimization only applies for arrays
5821 // of scalars and arrays of class type with trivial copy-assignment
5822 // operators.
5823 if (FieldType->isArrayType() &&
5824 (!BaseType->isRecordType() ||
5825 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5826 ->hasTrivialCopyAssignment())) {
5827 // Compute the size of the memory buffer to be copied.
5828 QualType SizeType = Context.getSizeType();
5829 llvm::APInt Size(Context.getTypeSize(SizeType),
5830 Context.getTypeSizeInChars(BaseType).getQuantity());
5831 for (const ConstantArrayType *Array
5832 = Context.getAsConstantArrayType(FieldType);
5833 Array;
5834 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005835 llvm::APInt ArraySize
5836 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005837 Size *= ArraySize;
5838 }
5839
5840 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005841 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5842 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005843
5844 bool NeedsCollectableMemCpy =
5845 (BaseType->isRecordType() &&
5846 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5847
5848 if (NeedsCollectableMemCpy) {
5849 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005850 // Create a reference to the __builtin_objc_memmove_collectable function.
5851 LookupResult R(*this,
5852 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005853 Loc, LookupOrdinaryName);
5854 LookupName(R, TUScope, true);
5855
5856 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5857 if (!CollectableMemCpy) {
5858 // Something went horribly wrong earlier, and we will have
5859 // complained about it.
5860 Invalid = true;
5861 continue;
5862 }
5863
5864 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5865 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005866 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005867 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5868 }
5869 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005870 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005871 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005872 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5873 LookupOrdinaryName);
5874 LookupName(R, TUScope, true);
5875
5876 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5877 if (!BuiltinMemCpy) {
5878 // Something went horribly wrong earlier, and we will have complained
5879 // about it.
5880 Invalid = true;
5881 continue;
5882 }
5883
5884 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5885 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005886 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005887 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5888 }
5889
John McCallca0408f2010-08-23 06:44:23 +00005890 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005891 CallArgs.push_back(To.takeAs<Expr>());
5892 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005893 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005894 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005895 if (NeedsCollectableMemCpy)
5896 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005897 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005898 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005899 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005900 else
5901 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005902 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005903 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005904 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005905
Douglas Gregor06a9f362010-05-01 20:49:11 +00005906 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5907 Statements.push_back(Call.takeAs<Expr>());
5908 continue;
5909 }
5910
5911 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005912 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005913 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005914 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005915 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005916 Diag(CurrentLocation, diag::note_member_synthesized_at)
5917 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5918 CopyAssignOperator->setInvalidDecl();
5919 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005920 }
5921
5922 // Success! Record the copy.
5923 Statements.push_back(Copy.takeAs<Stmt>());
5924 }
5925
5926 if (!Invalid) {
5927 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005928 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005929
John McCall60d7b3a2010-08-24 06:29:42 +00005930 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005931 if (Return.isInvalid())
5932 Invalid = true;
5933 else {
5934 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005935
5936 if (Trap.hasErrorOccurred()) {
5937 Diag(CurrentLocation, diag::note_member_synthesized_at)
5938 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5939 Invalid = true;
5940 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005941 }
5942 }
5943
5944 if (Invalid) {
5945 CopyAssignOperator->setInvalidDecl();
5946 return;
5947 }
5948
John McCall60d7b3a2010-08-24 06:29:42 +00005949 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005950 /*isStmtExpr=*/false);
5951 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5952 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005953
5954 if (ASTMutationListener *L = getASTMutationListener()) {
5955 L->CompletedImplicitDefinition(CopyAssignOperator);
5956 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005957}
5958
Douglas Gregor23c94db2010-07-02 17:43:08 +00005959CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5960 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005961 // C++ [class.copy]p4:
5962 // If the class definition does not explicitly declare a copy
5963 // constructor, one is declared implicitly.
5964
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005965 // C++ [class.copy]p5:
5966 // The implicitly-declared copy constructor for a class X will
5967 // have the form
5968 //
5969 // X::X(const X&)
5970 //
5971 // if
5972 bool HasConstCopyConstructor = true;
5973
5974 // -- each direct or virtual base class B of X has a copy
5975 // constructor whose first parameter is of type const B& or
5976 // const volatile B&, and
5977 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5978 BaseEnd = ClassDecl->bases_end();
5979 HasConstCopyConstructor && Base != BaseEnd;
5980 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005981 // Virtual bases are handled below.
5982 if (Base->isVirtual())
5983 continue;
5984
Douglas Gregor22584312010-07-02 23:41:54 +00005985 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005986 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005987 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5988 DeclareImplicitCopyConstructor(BaseClassDecl);
5989
Douglas Gregor598a8542010-07-01 18:27:03 +00005990 HasConstCopyConstructor
5991 = BaseClassDecl->hasConstCopyConstructor(Context);
5992 }
5993
5994 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5995 BaseEnd = ClassDecl->vbases_end();
5996 HasConstCopyConstructor && Base != BaseEnd;
5997 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005998 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005999 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006000 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6001 DeclareImplicitCopyConstructor(BaseClassDecl);
6002
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006003 HasConstCopyConstructor
6004 = BaseClassDecl->hasConstCopyConstructor(Context);
6005 }
6006
6007 // -- for all the nonstatic data members of X that are of a
6008 // class type M (or array thereof), each such class type
6009 // has a copy constructor whose first parameter is of type
6010 // const M& or const volatile M&.
6011 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6012 FieldEnd = ClassDecl->field_end();
6013 HasConstCopyConstructor && Field != FieldEnd;
6014 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00006015 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006016 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006017 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00006018 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006019 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6020 DeclareImplicitCopyConstructor(FieldClassDecl);
6021
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006022 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00006023 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006024 }
6025 }
6026
6027 // Otherwise, the implicitly declared copy constructor will have
6028 // the form
6029 //
6030 // X::X(X&)
6031 QualType ClassType = Context.getTypeDeclType(ClassDecl);
6032 QualType ArgType = ClassType;
6033 if (HasConstCopyConstructor)
6034 ArgType = ArgType.withConst();
6035 ArgType = Context.getLValueReferenceType(ArgType);
6036
Douglas Gregor0d405db2010-07-01 20:59:04 +00006037 // C++ [except.spec]p14:
6038 // An implicitly declared special member function (Clause 12) shall have an
6039 // exception-specification. [...]
6040 ImplicitExceptionSpecification ExceptSpec(Context);
6041 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6042 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6043 BaseEnd = ClassDecl->bases_end();
6044 Base != BaseEnd;
6045 ++Base) {
6046 // Virtual bases are handled below.
6047 if (Base->isVirtual())
6048 continue;
6049
Douglas Gregor22584312010-07-02 23:41:54 +00006050 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006051 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006052 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6053 DeclareImplicitCopyConstructor(BaseClassDecl);
6054
Douglas Gregor0d405db2010-07-01 20:59:04 +00006055 if (CXXConstructorDecl *CopyConstructor
6056 = BaseClassDecl->getCopyConstructor(Context, Quals))
6057 ExceptSpec.CalledDecl(CopyConstructor);
6058 }
6059 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6060 BaseEnd = ClassDecl->vbases_end();
6061 Base != BaseEnd;
6062 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00006063 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006064 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006065 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6066 DeclareImplicitCopyConstructor(BaseClassDecl);
6067
Douglas Gregor0d405db2010-07-01 20:59:04 +00006068 if (CXXConstructorDecl *CopyConstructor
6069 = BaseClassDecl->getCopyConstructor(Context, Quals))
6070 ExceptSpec.CalledDecl(CopyConstructor);
6071 }
6072 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6073 FieldEnd = ClassDecl->field_end();
6074 Field != FieldEnd;
6075 ++Field) {
6076 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6077 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006078 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00006079 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00006080 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6081 DeclareImplicitCopyConstructor(FieldClassDecl);
6082
Douglas Gregor0d405db2010-07-01 20:59:04 +00006083 if (CXXConstructorDecl *CopyConstructor
6084 = FieldClassDecl->getCopyConstructor(Context, Quals))
6085 ExceptSpec.CalledDecl(CopyConstructor);
6086 }
6087 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006088
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006089 // An implicitly-declared copy constructor is an inline public
6090 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00006091 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00006092 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00006093 EPI.NumExceptions = ExceptSpec.size();
6094 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006095 DeclarationName Name
6096 = Context.DeclarationNames.getCXXConstructorName(
6097 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006098 SourceLocation ClassLoc = ClassDecl->getLocation();
6099 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006100 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006101 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006102 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006103 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006104 /*TInfo=*/0,
6105 /*isExplicit=*/false,
6106 /*isInline=*/true,
6107 /*isImplicitlyDeclared=*/true);
6108 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006109 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6110
Douglas Gregor22584312010-07-02 23:41:54 +00006111 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00006112 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6113
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006114 // Add the parameter to the constructor.
6115 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006116 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006117 /*IdentifierInfo=*/0,
6118 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006119 SC_None,
6120 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006121 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00006122 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00006123 PushOnScopeChains(CopyConstructor, S, false);
6124 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00006125
6126 return CopyConstructor;
6127}
6128
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006129void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6130 CXXConstructorDecl *CopyConstructor,
6131 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00006132 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00006133 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006134 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006135 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006136
Anders Carlsson63010a72010-04-23 16:24:12 +00006137 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006138 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006139
Douglas Gregor39957dc2010-05-01 15:04:51 +00006140 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006141 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006142
Sean Huntcbb67482011-01-08 20:30:50 +00006143 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006144 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00006145 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006146 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00006147 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006148 } else {
6149 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6150 CopyConstructor->getLocation(),
6151 MultiStmtArg(*this, 0, 0),
6152 /*isStmtExpr=*/false)
6153 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00006154 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006155
6156 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006157
6158 if (ASTMutationListener *L = getASTMutationListener()) {
6159 L->CompletedImplicitDefinition(CopyConstructor);
6160 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006161}
6162
John McCall60d7b3a2010-08-24 06:29:42 +00006163ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006164Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00006165 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00006166 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006167 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006168 unsigned ConstructKind,
6169 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006170 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006171
Douglas Gregor2f599792010-04-02 18:24:57 +00006172 // C++0x [class.copy]p34:
6173 // When certain criteria are met, an implementation is allowed to
6174 // omit the copy/move construction of a class object, even if the
6175 // copy/move constructor and/or destructor for the object have
6176 // side effects. [...]
6177 // - when a temporary class object that has not been bound to a
6178 // reference (12.2) would be copied/moved to a class object
6179 // with the same cv-unqualified type, the copy/move operation
6180 // can be omitted by constructing the temporary object
6181 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00006182 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00006183 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00006184 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00006185 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006186 }
Mike Stump1eb44332009-09-09 15:08:12 +00006187
6188 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006189 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006190 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006191}
6192
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006193/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6194/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006195ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006196Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6197 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00006198 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006199 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006200 unsigned ConstructKind,
6201 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00006202 unsigned NumExprs = ExprArgs.size();
6203 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006204
Nick Lewycky909a70d2011-03-25 01:44:32 +00006205 for (specific_attr_iterator<NonNullAttr>
6206 i = Constructor->specific_attr_begin<NonNullAttr>(),
6207 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6208 const NonNullAttr *NonNull = *i;
6209 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6210 }
6211
Douglas Gregor7edfb692009-11-23 12:27:39 +00006212 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00006213 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00006214 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00006215 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006216 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6217 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006218}
6219
Mike Stump1eb44332009-09-09 15:08:12 +00006220bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006221 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00006222 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00006223 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00006224 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00006225 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006226 move(Exprs), false, CXXConstructExpr::CK_Complete,
6227 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00006228 if (TempResult.isInvalid())
6229 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006230
Anders Carlssonda3f4e22009-08-25 05:12:04 +00006231 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00006232 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006233 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00006234 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00006235 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Anders Carlssonfe2de492009-08-25 05:18:00 +00006237 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00006238}
6239
John McCall68c6c9a2010-02-02 09:10:11 +00006240void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006241 if (VD->isInvalidDecl()) return;
6242
John McCall68c6c9a2010-02-02 09:10:11 +00006243 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006244 if (ClassDecl->isInvalidDecl()) return;
6245 if (ClassDecl->hasTrivialDestructor()) return;
6246 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00006247
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006248 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6249 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6250 CheckDestructorAccess(VD->getLocation(), Destructor,
6251 PDiag(diag::err_access_dtor_var)
6252 << VD->getDeclName()
6253 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00006254
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006255 if (!VD->hasGlobalStorage()) return;
6256
6257 // Emit warning for non-trivial dtor in global scope (a real global,
6258 // class-static, function-static).
6259 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6260
6261 // TODO: this should be re-enabled for static locals by !CXAAtExit
6262 if (!VD->isStaticLocal())
6263 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006264}
6265
Mike Stump1eb44332009-09-09 15:08:12 +00006266/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006267/// ActOnDeclarator, when a C++ direct initializer is present.
6268/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00006269void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006270 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006271 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00006272 SourceLocation RParenLoc,
6273 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00006274 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006275
6276 // If there is no declaration, there was an error parsing it. Just ignore
6277 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006278 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006279 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006280
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006281 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6282 if (!VDecl) {
6283 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6284 RealDecl->setInvalidDecl();
6285 return;
6286 }
6287
Richard Smith34b41d92011-02-20 03:19:35 +00006288 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6289 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00006290 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6291 if (Exprs.size() > 1) {
6292 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6293 diag::err_auto_var_init_multiple_expressions)
6294 << VDecl->getDeclName() << VDecl->getType()
6295 << VDecl->getSourceRange();
6296 RealDecl->setInvalidDecl();
6297 return;
6298 }
6299
6300 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00006301 TypeSourceInfo *DeducedType = 0;
6302 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00006303 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6304 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6305 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00006306 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006307 RealDecl->setInvalidDecl();
6308 return;
6309 }
Richard Smitha085da82011-03-17 16:11:59 +00006310 VDecl->setTypeSourceInfo(DeducedType);
6311 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00006312
6313 // If this is a redeclaration, check that the type we just deduced matches
6314 // the previously declared type.
6315 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6316 MergeVarDeclTypes(VDecl, Old);
6317 }
6318
Douglas Gregor83ddad32009-08-26 21:14:46 +00006319 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006320 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006321 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6322 //
6323 // Clients that want to distinguish between the two forms, can check for
6324 // direct initializer using VarDecl::hasCXXDirectInitializer().
6325 // A major benefit is that clients that don't particularly care about which
6326 // exactly form was it (like the CodeGen) can handle both cases without
6327 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006328
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006329 // C++ 8.5p11:
6330 // The form of initialization (using parentheses or '=') is generally
6331 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006332 // class type.
6333
Douglas Gregor4dffad62010-02-11 22:55:30 +00006334 if (!VDecl->getType()->isDependentType() &&
6335 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00006336 diag::err_typecheck_decl_incomplete_type)) {
6337 VDecl->setInvalidDecl();
6338 return;
6339 }
6340
Douglas Gregor90f93822009-12-22 22:17:25 +00006341 // The variable can not have an abstract class type.
6342 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6343 diag::err_abstract_type_in_decl,
6344 AbstractVariableType))
6345 VDecl->setInvalidDecl();
6346
Sebastian Redl31310a22010-02-01 20:16:42 +00006347 const VarDecl *Def;
6348 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006349 Diag(VDecl->getLocation(), diag::err_redefinition)
6350 << VDecl->getDeclName();
6351 Diag(Def->getLocation(), diag::note_previous_definition);
6352 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006353 return;
6354 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006355
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006356 // C++ [class.static.data]p4
6357 // If a static data member is of const integral or const
6358 // enumeration type, its declaration in the class definition can
6359 // specify a constant-initializer which shall be an integral
6360 // constant expression (5.19). In that case, the member can appear
6361 // in integral constant expressions. The member shall still be
6362 // defined in a namespace scope if it is used in the program and the
6363 // namespace scope definition shall not contain an initializer.
6364 //
6365 // We already performed a redefinition check above, but for static
6366 // data members we also need to check whether there was an in-class
6367 // declaration with an initializer.
6368 const VarDecl* PrevInit = 0;
6369 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6370 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6371 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6372 return;
6373 }
6374
Douglas Gregora31040f2010-12-16 01:31:22 +00006375 bool IsDependent = false;
6376 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6377 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6378 VDecl->setInvalidDecl();
6379 return;
6380 }
6381
6382 if (Exprs.get()[I]->isTypeDependent())
6383 IsDependent = true;
6384 }
6385
Douglas Gregor4dffad62010-02-11 22:55:30 +00006386 // If either the declaration has a dependent type or if any of the
6387 // expressions is type-dependent, we represent the initialization
6388 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006389 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006390 // Let clients know that initialization was done with a direct initializer.
6391 VDecl->setCXXDirectInitializer(true);
6392
6393 // Store the initialization expressions as a ParenListExpr.
6394 unsigned NumExprs = Exprs.size();
6395 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6396 (Expr **)Exprs.release(),
6397 NumExprs, RParenLoc));
6398 return;
6399 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006400
6401 // Capture the variable that is being initialized and the style of
6402 // initialization.
6403 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6404
6405 // FIXME: Poor source location information.
6406 InitializationKind Kind
6407 = InitializationKind::CreateDirect(VDecl->getLocation(),
6408 LParenLoc, RParenLoc);
6409
6410 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006411 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006412 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006413 if (Result.isInvalid()) {
6414 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006415 return;
6416 }
John McCallb4eb64d2010-10-08 02:01:28 +00006417
6418 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006419
Douglas Gregor53c374f2010-12-07 00:41:46 +00006420 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006421 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006422 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006423
John McCall2998d6b2011-01-19 11:48:09 +00006424 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006425}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006426
Douglas Gregor39da0b82009-09-09 23:08:42 +00006427/// \brief Given a constructor and the set of arguments provided for the
6428/// constructor, convert the arguments and add any required default arguments
6429/// to form a proper call to this constructor.
6430///
6431/// \returns true if an error occurred, false otherwise.
6432bool
6433Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6434 MultiExprArg ArgsPtr,
6435 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006436 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006437 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6438 unsigned NumArgs = ArgsPtr.size();
6439 Expr **Args = (Expr **)ArgsPtr.get();
6440
6441 const FunctionProtoType *Proto
6442 = Constructor->getType()->getAs<FunctionProtoType>();
6443 assert(Proto && "Constructor without a prototype?");
6444 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006445
6446 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006447 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006448 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006449 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006450 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006451
6452 VariadicCallType CallType =
6453 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6454 llvm::SmallVector<Expr *, 8> AllArgs;
6455 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6456 Proto, 0, Args, NumArgs, AllArgs,
6457 CallType);
6458 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6459 ConvertedArgs.push_back(AllArgs[i]);
6460 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006461}
6462
Anders Carlsson20d45d22009-12-12 00:32:00 +00006463static inline bool
6464CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6465 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006466 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006467 if (isa<NamespaceDecl>(DC)) {
6468 return SemaRef.Diag(FnDecl->getLocation(),
6469 diag::err_operator_new_delete_declared_in_namespace)
6470 << FnDecl->getDeclName();
6471 }
6472
6473 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006474 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006475 return SemaRef.Diag(FnDecl->getLocation(),
6476 diag::err_operator_new_delete_declared_static)
6477 << FnDecl->getDeclName();
6478 }
6479
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006480 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006481}
6482
Anders Carlsson156c78e2009-12-13 17:53:43 +00006483static inline bool
6484CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6485 CanQualType ExpectedResultType,
6486 CanQualType ExpectedFirstParamType,
6487 unsigned DependentParamTypeDiag,
6488 unsigned InvalidParamTypeDiag) {
6489 QualType ResultType =
6490 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6491
6492 // Check that the result type is not dependent.
6493 if (ResultType->isDependentType())
6494 return SemaRef.Diag(FnDecl->getLocation(),
6495 diag::err_operator_new_delete_dependent_result_type)
6496 << FnDecl->getDeclName() << ExpectedResultType;
6497
6498 // Check that the result type is what we expect.
6499 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6500 return SemaRef.Diag(FnDecl->getLocation(),
6501 diag::err_operator_new_delete_invalid_result_type)
6502 << FnDecl->getDeclName() << ExpectedResultType;
6503
6504 // A function template must have at least 2 parameters.
6505 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6506 return SemaRef.Diag(FnDecl->getLocation(),
6507 diag::err_operator_new_delete_template_too_few_parameters)
6508 << FnDecl->getDeclName();
6509
6510 // The function decl must have at least 1 parameter.
6511 if (FnDecl->getNumParams() == 0)
6512 return SemaRef.Diag(FnDecl->getLocation(),
6513 diag::err_operator_new_delete_too_few_parameters)
6514 << FnDecl->getDeclName();
6515
6516 // Check the the first parameter type is not dependent.
6517 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6518 if (FirstParamType->isDependentType())
6519 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6520 << FnDecl->getDeclName() << ExpectedFirstParamType;
6521
6522 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006523 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006524 ExpectedFirstParamType)
6525 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6526 << FnDecl->getDeclName() << ExpectedFirstParamType;
6527
6528 return false;
6529}
6530
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006531static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006532CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006533 // C++ [basic.stc.dynamic.allocation]p1:
6534 // A program is ill-formed if an allocation function is declared in a
6535 // namespace scope other than global scope or declared static in global
6536 // scope.
6537 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6538 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006539
6540 CanQualType SizeTy =
6541 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6542
6543 // C++ [basic.stc.dynamic.allocation]p1:
6544 // The return type shall be void*. The first parameter shall have type
6545 // std::size_t.
6546 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6547 SizeTy,
6548 diag::err_operator_new_dependent_param_type,
6549 diag::err_operator_new_param_type))
6550 return true;
6551
6552 // C++ [basic.stc.dynamic.allocation]p1:
6553 // The first parameter shall not have an associated default argument.
6554 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006555 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006556 diag::err_operator_new_default_arg)
6557 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6558
6559 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006560}
6561
6562static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006563CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6564 // C++ [basic.stc.dynamic.deallocation]p1:
6565 // A program is ill-formed if deallocation functions are declared in a
6566 // namespace scope other than global scope or declared static in global
6567 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006568 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6569 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006570
6571 // C++ [basic.stc.dynamic.deallocation]p2:
6572 // Each deallocation function shall return void and its first parameter
6573 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006574 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6575 SemaRef.Context.VoidPtrTy,
6576 diag::err_operator_delete_dependent_param_type,
6577 diag::err_operator_delete_param_type))
6578 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006579
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006580 return false;
6581}
6582
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006583/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6584/// of this overloaded operator is well-formed. If so, returns false;
6585/// otherwise, emits appropriate diagnostics and returns true.
6586bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006587 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006588 "Expected an overloaded operator declaration");
6589
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006590 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6591
Mike Stump1eb44332009-09-09 15:08:12 +00006592 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006593 // The allocation and deallocation functions, operator new,
6594 // operator new[], operator delete and operator delete[], are
6595 // described completely in 3.7.3. The attributes and restrictions
6596 // found in the rest of this subclause do not apply to them unless
6597 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006598 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006599 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006600
Anders Carlssona3ccda52009-12-12 00:26:23 +00006601 if (Op == OO_New || Op == OO_Array_New)
6602 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006603
6604 // C++ [over.oper]p6:
6605 // An operator function shall either be a non-static member
6606 // function or be a non-member function and have at least one
6607 // parameter whose type is a class, a reference to a class, an
6608 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006609 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6610 if (MethodDecl->isStatic())
6611 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006612 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006613 } else {
6614 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006615 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6616 ParamEnd = FnDecl->param_end();
6617 Param != ParamEnd; ++Param) {
6618 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006619 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6620 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006621 ClassOrEnumParam = true;
6622 break;
6623 }
6624 }
6625
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006626 if (!ClassOrEnumParam)
6627 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006628 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006629 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006630 }
6631
6632 // C++ [over.oper]p8:
6633 // An operator function cannot have default arguments (8.3.6),
6634 // except where explicitly stated below.
6635 //
Mike Stump1eb44332009-09-09 15:08:12 +00006636 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006637 // (C++ [over.call]p1).
6638 if (Op != OO_Call) {
6639 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6640 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006641 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006642 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006643 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006644 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006645 }
6646 }
6647
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006648 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6649 { false, false, false }
6650#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6651 , { Unary, Binary, MemberOnly }
6652#include "clang/Basic/OperatorKinds.def"
6653 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006654
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006655 bool CanBeUnaryOperator = OperatorUses[Op][0];
6656 bool CanBeBinaryOperator = OperatorUses[Op][1];
6657 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006658
6659 // C++ [over.oper]p8:
6660 // [...] Operator functions cannot have more or fewer parameters
6661 // than the number required for the corresponding operator, as
6662 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006663 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006664 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006665 if (Op != OO_Call &&
6666 ((NumParams == 1 && !CanBeUnaryOperator) ||
6667 (NumParams == 2 && !CanBeBinaryOperator) ||
6668 (NumParams < 1) || (NumParams > 2))) {
6669 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006670 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006671 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006672 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006673 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006674 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006675 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006676 assert(CanBeBinaryOperator &&
6677 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006678 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006679 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006680
Chris Lattner416e46f2008-11-21 07:57:12 +00006681 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006682 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006683 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006684
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006685 // Overloaded operators other than operator() cannot be variadic.
6686 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006687 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006688 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006689 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006690 }
6691
6692 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006693 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6694 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006695 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006696 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006697 }
6698
6699 // C++ [over.inc]p1:
6700 // The user-defined function called operator++ implements the
6701 // prefix and postfix ++ operator. If this function is a member
6702 // function with no parameters, or a non-member function with one
6703 // parameter of class or enumeration type, it defines the prefix
6704 // increment operator ++ for objects of that type. If the function
6705 // is a member function with one parameter (which shall be of type
6706 // int) or a non-member function with two parameters (the second
6707 // of which shall be of type int), it defines the postfix
6708 // increment operator ++ for objects of that type.
6709 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6710 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6711 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006712 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006713 ParamIsInt = BT->getKind() == BuiltinType::Int;
6714
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006715 if (!ParamIsInt)
6716 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006717 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006718 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006719 }
6720
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006721 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006722}
Chris Lattner5a003a42008-12-17 07:09:26 +00006723
Sean Hunta6c058d2010-01-13 09:01:02 +00006724/// CheckLiteralOperatorDeclaration - Check whether the declaration
6725/// of this literal operator function is well-formed. If so, returns
6726/// false; otherwise, emits appropriate diagnostics and returns true.
6727bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6728 DeclContext *DC = FnDecl->getDeclContext();
6729 Decl::Kind Kind = DC->getDeclKind();
6730 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6731 Kind != Decl::LinkageSpec) {
6732 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6733 << FnDecl->getDeclName();
6734 return true;
6735 }
6736
6737 bool Valid = false;
6738
Sean Hunt216c2782010-04-07 23:11:06 +00006739 // template <char...> type operator "" name() is the only valid template
6740 // signature, and the only valid signature with no parameters.
6741 if (FnDecl->param_size() == 0) {
6742 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6743 // Must have only one template parameter
6744 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6745 if (Params->size() == 1) {
6746 NonTypeTemplateParmDecl *PmDecl =
6747 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006748
Sean Hunt216c2782010-04-07 23:11:06 +00006749 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006750 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6751 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6752 Valid = true;
6753 }
6754 }
6755 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006756 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006757 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6758
Sean Hunta6c058d2010-01-13 09:01:02 +00006759 QualType T = (*Param)->getType();
6760
Sean Hunt30019c02010-04-07 22:57:35 +00006761 // unsigned long long int, long double, and any character type are allowed
6762 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006763 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6764 Context.hasSameType(T, Context.LongDoubleTy) ||
6765 Context.hasSameType(T, Context.CharTy) ||
6766 Context.hasSameType(T, Context.WCharTy) ||
6767 Context.hasSameType(T, Context.Char16Ty) ||
6768 Context.hasSameType(T, Context.Char32Ty)) {
6769 if (++Param == FnDecl->param_end())
6770 Valid = true;
6771 goto FinishedParams;
6772 }
6773
Sean Hunt30019c02010-04-07 22:57:35 +00006774 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006775 const PointerType *PT = T->getAs<PointerType>();
6776 if (!PT)
6777 goto FinishedParams;
6778 T = PT->getPointeeType();
6779 if (!T.isConstQualified())
6780 goto FinishedParams;
6781 T = T.getUnqualifiedType();
6782
6783 // Move on to the second parameter;
6784 ++Param;
6785
6786 // If there is no second parameter, the first must be a const char *
6787 if (Param == FnDecl->param_end()) {
6788 if (Context.hasSameType(T, Context.CharTy))
6789 Valid = true;
6790 goto FinishedParams;
6791 }
6792
6793 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6794 // are allowed as the first parameter to a two-parameter function
6795 if (!(Context.hasSameType(T, Context.CharTy) ||
6796 Context.hasSameType(T, Context.WCharTy) ||
6797 Context.hasSameType(T, Context.Char16Ty) ||
6798 Context.hasSameType(T, Context.Char32Ty)))
6799 goto FinishedParams;
6800
6801 // The second and final parameter must be an std::size_t
6802 T = (*Param)->getType().getUnqualifiedType();
6803 if (Context.hasSameType(T, Context.getSizeType()) &&
6804 ++Param == FnDecl->param_end())
6805 Valid = true;
6806 }
6807
6808 // FIXME: This diagnostic is absolutely terrible.
6809FinishedParams:
6810 if (!Valid) {
6811 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6812 << FnDecl->getDeclName();
6813 return true;
6814 }
6815
6816 return false;
6817}
6818
Douglas Gregor074149e2009-01-05 19:45:36 +00006819/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6820/// linkage specification, including the language and (if present)
6821/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6822/// the location of the language string literal, which is provided
6823/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6824/// the '{' brace. Otherwise, this linkage specification does not
6825/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006826Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6827 SourceLocation LangLoc,
6828 llvm::StringRef Lang,
6829 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006830 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006831 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006832 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006833 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006834 Language = LinkageSpecDecl::lang_cxx;
6835 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006836 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006837 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006838 }
Mike Stump1eb44332009-09-09 15:08:12 +00006839
Chris Lattnercc98eac2008-12-17 07:13:27 +00006840 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006841
Douglas Gregor074149e2009-01-05 19:45:36 +00006842 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006843 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006844 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006845 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006846 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006847}
6848
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006849/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006850/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6851/// valid, it's the position of the closing '}' brace in a linkage
6852/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006853Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006854 Decl *LinkageSpec,
6855 SourceLocation RBraceLoc) {
6856 if (LinkageSpec) {
6857 if (RBraceLoc.isValid()) {
6858 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6859 LSDecl->setRBraceLoc(RBraceLoc);
6860 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006861 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006862 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006863 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006864}
6865
Douglas Gregord308e622009-05-18 20:51:54 +00006866/// \brief Perform semantic analysis for the variable declaration that
6867/// occurs within a C++ catch clause, returning the newly-created
6868/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006869VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006870 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006871 SourceLocation StartLoc,
6872 SourceLocation Loc,
6873 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00006874 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006875 QualType ExDeclType = TInfo->getType();
6876
Sebastian Redl4b07b292008-12-22 19:15:10 +00006877 // Arrays and functions decay.
6878 if (ExDeclType->isArrayType())
6879 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6880 else if (ExDeclType->isFunctionType())
6881 ExDeclType = Context.getPointerType(ExDeclType);
6882
6883 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6884 // The exception-declaration shall not denote a pointer or reference to an
6885 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006886 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006887 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006888 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006889 Invalid = true;
6890 }
Douglas Gregord308e622009-05-18 20:51:54 +00006891
Douglas Gregora2762912010-03-08 01:47:36 +00006892 // GCC allows catching pointers and references to incomplete types
6893 // as an extension; so do we, but we warn by default.
6894
Sebastian Redl4b07b292008-12-22 19:15:10 +00006895 QualType BaseType = ExDeclType;
6896 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006897 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006898 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006899 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006900 BaseType = Ptr->getPointeeType();
6901 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006902 DK = diag::ext_catch_incomplete_ptr;
6903 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006904 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006905 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006906 BaseType = Ref->getPointeeType();
6907 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006908 DK = diag::ext_catch_incomplete_ref;
6909 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006910 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006911 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006912 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6913 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006914 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006915
Mike Stump1eb44332009-09-09 15:08:12 +00006916 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006917 RequireNonAbstractType(Loc, ExDeclType,
6918 diag::err_abstract_type_in_decl,
6919 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006920 Invalid = true;
6921
John McCall5a180392010-07-24 00:37:23 +00006922 // Only the non-fragile NeXT runtime currently supports C++ catches
6923 // of ObjC types, and no runtime supports catching ObjC types by value.
6924 if (!Invalid && getLangOptions().ObjC1) {
6925 QualType T = ExDeclType;
6926 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6927 T = RT->getPointeeType();
6928
6929 if (T->isObjCObjectType()) {
6930 Diag(Loc, diag::err_objc_object_catch);
6931 Invalid = true;
6932 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00006933 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00006934 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6935 Invalid = true;
6936 }
6937 }
6938 }
6939
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006940 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6941 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006942 ExDecl->setExceptionVariable(true);
6943
Douglas Gregor6d182892010-03-05 23:38:39 +00006944 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00006945 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00006946 // C++ [except.handle]p16:
6947 // The object declared in an exception-declaration or, if the
6948 // exception-declaration does not specify a name, a temporary (12.2) is
6949 // copy-initialized (8.5) from the exception object. [...]
6950 // The object is destroyed when the handler exits, after the destruction
6951 // of any automatic objects initialized within the handler.
6952 //
6953 // We just pretend to initialize the object with itself, then make sure
6954 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00006955 QualType initType = ExDeclType;
6956
6957 InitializedEntity entity =
6958 InitializedEntity::InitializeVariable(ExDecl);
6959 InitializationKind initKind =
6960 InitializationKind::CreateCopy(Loc, SourceLocation());
6961
6962 Expr *opaqueValue =
6963 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6964 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6965 ExprResult result = sequence.Perform(*this, entity, initKind,
6966 MultiExprArg(&opaqueValue, 1));
6967 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00006968 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00006969 else {
6970 // If the constructor used was non-trivial, set this as the
6971 // "initializer".
6972 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6973 if (!construct->getConstructor()->isTrivial()) {
6974 Expr *init = MaybeCreateExprWithCleanups(construct);
6975 ExDecl->setInit(init);
6976 }
6977
6978 // And make sure it's destructable.
6979 FinalizeVarWithDestructor(ExDecl, recordType);
6980 }
Douglas Gregor6d182892010-03-05 23:38:39 +00006981 }
6982 }
6983
Douglas Gregord308e622009-05-18 20:51:54 +00006984 if (Invalid)
6985 ExDecl->setInvalidDecl();
6986
6987 return ExDecl;
6988}
6989
6990/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6991/// handler.
John McCalld226f652010-08-21 09:40:31 +00006992Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006993 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006994 bool Invalid = D.isInvalidType();
6995
6996 // Check for unexpanded parameter packs.
6997 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6998 UPPC_ExceptionType)) {
6999 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7000 D.getIdentifierLoc());
7001 Invalid = true;
7002 }
7003
Sebastian Redl4b07b292008-12-22 19:15:10 +00007004 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00007005 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00007006 LookupOrdinaryName,
7007 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007008 // The scope should be freshly made just for us. There is just no way
7009 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00007010 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00007011 if (PrevDecl->isTemplateParameter()) {
7012 // Maybe we will complain about the shadowed template parameter.
7013 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007014 }
7015 }
7016
Chris Lattnereaaebc72009-04-25 08:06:05 +00007017 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00007018 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
7019 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00007020 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007021 }
7022
Douglas Gregor83cb9422010-09-09 17:09:21 +00007023 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007024 D.getSourceRange().getBegin(),
7025 D.getIdentifierLoc(),
7026 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00007027 if (Invalid)
7028 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00007029
Sebastian Redl4b07b292008-12-22 19:15:10 +00007030 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00007031 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00007032 PushOnScopeChains(ExDecl, S);
7033 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007034 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00007035
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007036 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00007037 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00007038}
Anders Carlssonfb311762009-03-14 00:25:26 +00007039
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007040Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007041 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007042 Expr *AssertMessageExpr_,
7043 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00007044 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00007045
Anders Carlssonc3082412009-03-14 00:33:21 +00007046 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7047 llvm::APSInt Value(32);
7048 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007049 Diag(StaticAssertLoc,
7050 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00007051 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007052 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00007053 }
Anders Carlssonfb311762009-03-14 00:25:26 +00007054
Anders Carlssonc3082412009-03-14 00:33:21 +00007055 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007056 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00007057 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00007058 }
7059 }
Mike Stump1eb44332009-09-09 15:08:12 +00007060
Douglas Gregor399ad972010-12-15 23:55:21 +00007061 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7062 return 0;
7063
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007064 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7065 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00007066
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007067 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00007068 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00007069}
Sebastian Redl50de12f2009-03-24 22:27:57 +00007070
Douglas Gregor1d869352010-04-07 16:53:43 +00007071/// \brief Perform semantic analysis of the given friend type declaration.
7072///
7073/// \returns A friend declaration that.
7074FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7075 TypeSourceInfo *TSInfo) {
7076 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7077
7078 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00007079 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00007080
Douglas Gregor06245bf2010-04-07 17:57:12 +00007081 if (!getLangOptions().CPlusPlus0x) {
7082 // C++03 [class.friend]p2:
7083 // An elaborated-type-specifier shall be used in a friend declaration
7084 // for a class.*
7085 //
7086 // * The class-key of the elaborated-type-specifier is required.
7087 if (!ActiveTemplateInstantiations.empty()) {
7088 // Do not complain about the form of friend template types during
7089 // template instantiation; we will already have complained when the
7090 // template was declared.
7091 } else if (!T->isElaboratedTypeSpecifier()) {
7092 // If we evaluated the type to a record type, suggest putting
7093 // a tag in front.
7094 if (const RecordType *RT = T->getAs<RecordType>()) {
7095 RecordDecl *RD = RT->getDecl();
7096
7097 std::string InsertionText = std::string(" ") + RD->getKindName();
7098
7099 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7100 << (unsigned) RD->getTagKind()
7101 << T
7102 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7103 InsertionText);
7104 } else {
7105 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7106 << T
7107 << SourceRange(FriendLoc, TypeRange.getEnd());
7108 }
7109 } else if (T->getAs<EnumType>()) {
7110 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00007111 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00007112 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00007113 }
7114 }
7115
Douglas Gregor06245bf2010-04-07 17:57:12 +00007116 // C++0x [class.friend]p3:
7117 // If the type specifier in a friend declaration designates a (possibly
7118 // cv-qualified) class type, that class is declared as a friend; otherwise,
7119 // the friend declaration is ignored.
7120
7121 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7122 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00007123
7124 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7125}
7126
John McCall9a34edb2010-10-19 01:40:49 +00007127/// Handle a friend tag declaration where the scope specifier was
7128/// templated.
7129Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7130 unsigned TagSpec, SourceLocation TagLoc,
7131 CXXScopeSpec &SS,
7132 IdentifierInfo *Name, SourceLocation NameLoc,
7133 AttributeList *Attr,
7134 MultiTemplateParamsArg TempParamLists) {
7135 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7136
7137 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00007138 bool Invalid = false;
7139
7140 if (TemplateParameterList *TemplateParams
7141 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7142 TempParamLists.get(),
7143 TempParamLists.size(),
7144 /*friend*/ true,
7145 isExplicitSpecialization,
7146 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00007147 if (TemplateParams->size() > 0) {
7148 // This is a declaration of a class template.
7149 if (Invalid)
7150 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007151
John McCall9a34edb2010-10-19 01:40:49 +00007152 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7153 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007154 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007155 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007156 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00007157 } else {
7158 // The "template<>" header is extraneous.
7159 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7160 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7161 isExplicitSpecialization = true;
7162 }
7163 }
7164
7165 if (Invalid) return 0;
7166
7167 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7168
7169 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007170 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00007171 if (TempParamLists.get()[I]->size()) {
7172 isAllExplicitSpecializations = false;
7173 break;
7174 }
7175 }
7176
7177 // FIXME: don't ignore attributes.
7178
7179 // If it's explicit specializations all the way down, just forget
7180 // about the template header and build an appropriate non-templated
7181 // friend. TODO: for source fidelity, remember the headers.
7182 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00007183 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00007184 ElaboratedTypeKeyword Keyword
7185 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007186 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00007187 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007188 if (T.isNull())
7189 return 0;
7190
7191 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7192 if (isa<DependentNameType>(T)) {
7193 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7194 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007195 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007196 TL.setNameLoc(NameLoc);
7197 } else {
7198 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7199 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007200 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007201 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7202 }
7203
7204 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7205 TSI, FriendLoc);
7206 Friend->setAccess(AS_public);
7207 CurContext->addDecl(Friend);
7208 return Friend;
7209 }
7210
7211 // Handle the case of a templated-scope friend class. e.g.
7212 // template <class T> class A<T>::B;
7213 // FIXME: we don't support these right now.
7214 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7215 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7216 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7217 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7218 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007219 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00007220 TL.setNameLoc(NameLoc);
7221
7222 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7223 TSI, FriendLoc);
7224 Friend->setAccess(AS_public);
7225 Friend->setUnsupportedFriend(true);
7226 CurContext->addDecl(Friend);
7227 return Friend;
7228}
7229
7230
John McCalldd4a3b02009-09-16 22:47:08 +00007231/// Handle a friend type declaration. This works in tandem with
7232/// ActOnTag.
7233///
7234/// Notes on friend class templates:
7235///
7236/// We generally treat friend class declarations as if they were
7237/// declaring a class. So, for example, the elaborated type specifier
7238/// in a friend declaration is required to obey the restrictions of a
7239/// class-head (i.e. no typedefs in the scope chain), template
7240/// parameters are required to match up with simple template-ids, &c.
7241/// However, unlike when declaring a template specialization, it's
7242/// okay to refer to a template specialization without an empty
7243/// template parameter declaration, e.g.
7244/// friend class A<T>::B<unsigned>;
7245/// We permit this as a special case; if there are any template
7246/// parameters present at all, require proper matching, i.e.
7247/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00007248Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00007249 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00007250 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00007251
7252 assert(DS.isFriendSpecified());
7253 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7254
John McCalldd4a3b02009-09-16 22:47:08 +00007255 // Try to convert the decl specifier to a type. This works for
7256 // friend templates because ActOnTag never produces a ClassTemplateDecl
7257 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00007258 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00007259 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7260 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00007261 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00007262 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007263
Douglas Gregor6ccab972010-12-16 01:14:37 +00007264 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7265 return 0;
7266
John McCalldd4a3b02009-09-16 22:47:08 +00007267 // This is definitely an error in C++98. It's probably meant to
7268 // be forbidden in C++0x, too, but the specification is just
7269 // poorly written.
7270 //
7271 // The problem is with declarations like the following:
7272 // template <T> friend A<T>::foo;
7273 // where deciding whether a class C is a friend or not now hinges
7274 // on whether there exists an instantiation of A that causes
7275 // 'foo' to equal C. There are restrictions on class-heads
7276 // (which we declare (by fiat) elaborated friend declarations to
7277 // be) that makes this tractable.
7278 //
7279 // FIXME: handle "template <> friend class A<T>;", which
7280 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00007281 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00007282 Diag(Loc, diag::err_tagless_friend_type_template)
7283 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007284 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00007285 }
Douglas Gregor1d869352010-04-07 16:53:43 +00007286
John McCall02cace72009-08-28 07:59:38 +00007287 // C++98 [class.friend]p1: A friend of a class is a function
7288 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00007289 // This is fixed in DR77, which just barely didn't make the C++03
7290 // deadline. It's also a very silly restriction that seriously
7291 // affects inner classes and which nobody else seems to implement;
7292 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00007293 //
7294 // But note that we could warn about it: it's always useless to
7295 // friend one of your own members (it's not, however, worthless to
7296 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00007297
John McCalldd4a3b02009-09-16 22:47:08 +00007298 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00007299 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00007300 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00007301 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00007302 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00007303 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00007304 DS.getFriendSpecLoc());
7305 else
Douglas Gregor1d869352010-04-07 16:53:43 +00007306 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7307
7308 if (!D)
John McCalld226f652010-08-21 09:40:31 +00007309 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00007310
John McCalldd4a3b02009-09-16 22:47:08 +00007311 D->setAccess(AS_public);
7312 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00007313
John McCalld226f652010-08-21 09:40:31 +00007314 return D;
John McCall02cace72009-08-28 07:59:38 +00007315}
7316
John McCall337ec3d2010-10-12 23:13:28 +00007317Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7318 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00007319 const DeclSpec &DS = D.getDeclSpec();
7320
7321 assert(DS.isFriendSpecified());
7322 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7323
7324 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00007325 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7326 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00007327
7328 // C++ [class.friend]p1
7329 // A friend of a class is a function or class....
7330 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00007331 // It *doesn't* see through dependent types, which is correct
7332 // according to [temp.arg.type]p3:
7333 // If a declaration acquires a function type through a
7334 // type dependent on a template-parameter and this causes
7335 // a declaration that does not use the syntactic form of a
7336 // function declarator to have a function type, the program
7337 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00007338 if (!T->isFunctionType()) {
7339 Diag(Loc, diag::err_unexpected_friend);
7340
7341 // It might be worthwhile to try to recover by creating an
7342 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00007343 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007344 }
7345
7346 // C++ [namespace.memdef]p3
7347 // - If a friend declaration in a non-local class first declares a
7348 // class or function, the friend class or function is a member
7349 // of the innermost enclosing namespace.
7350 // - The name of the friend is not found by simple name lookup
7351 // until a matching declaration is provided in that namespace
7352 // scope (either before or after the class declaration granting
7353 // friendship).
7354 // - If a friend function is called, its name may be found by the
7355 // name lookup that considers functions from namespaces and
7356 // classes associated with the types of the function arguments.
7357 // - When looking for a prior declaration of a class or a function
7358 // declared as a friend, scopes outside the innermost enclosing
7359 // namespace scope are not considered.
7360
John McCall337ec3d2010-10-12 23:13:28 +00007361 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007362 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7363 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007364 assert(Name);
7365
Douglas Gregor6ccab972010-12-16 01:14:37 +00007366 // Check for unexpanded parameter packs.
7367 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7368 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7369 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7370 return 0;
7371
John McCall67d1a672009-08-06 02:15:43 +00007372 // The context we found the declaration in, or in which we should
7373 // create the declaration.
7374 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007375 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007376 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007377 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007378
John McCall337ec3d2010-10-12 23:13:28 +00007379 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007380
John McCall337ec3d2010-10-12 23:13:28 +00007381 // There are four cases here.
7382 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007383 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007384 // there as appropriate.
7385 // Recover from invalid scope qualifiers as if they just weren't there.
7386 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007387 // C++0x [namespace.memdef]p3:
7388 // If the name in a friend declaration is neither qualified nor
7389 // a template-id and the declaration is a function or an
7390 // elaborated-type-specifier, the lookup to determine whether
7391 // the entity has been previously declared shall not consider
7392 // any scopes outside the innermost enclosing namespace.
7393 // C++0x [class.friend]p11:
7394 // If a friend declaration appears in a local class and the name
7395 // specified is an unqualified name, a prior declaration is
7396 // looked up without considering scopes that are outside the
7397 // innermost enclosing non-class scope. For a friend function
7398 // declaration, if there is no prior declaration, the program is
7399 // ill-formed.
7400 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007401 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007402
John McCall29ae6e52010-10-13 05:45:15 +00007403 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007404 DC = CurContext;
7405 while (true) {
7406 // Skip class contexts. If someone can cite chapter and verse
7407 // for this behavior, that would be nice --- it's what GCC and
7408 // EDG do, and it seems like a reasonable intent, but the spec
7409 // really only says that checks for unqualified existing
7410 // declarations should stop at the nearest enclosing namespace,
7411 // not that they should only consider the nearest enclosing
7412 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007413 while (DC->isRecord())
7414 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007415
John McCall68263142009-11-18 22:49:29 +00007416 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007417
7418 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007419 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007420 break;
John McCall29ae6e52010-10-13 05:45:15 +00007421
John McCall8a407372010-10-14 22:22:28 +00007422 if (isTemplateId) {
7423 if (isa<TranslationUnitDecl>(DC)) break;
7424 } else {
7425 if (DC->isFileContext()) break;
7426 }
John McCall67d1a672009-08-06 02:15:43 +00007427 DC = DC->getParent();
7428 }
7429
7430 // C++ [class.friend]p1: A friend of a class is a function or
7431 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007432 // C++0x changes this for both friend types and functions.
7433 // Most C++ 98 compilers do seem to give an error here, so
7434 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007435 if (!Previous.empty() && DC->Equals(CurContext)
7436 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007437 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007438
John McCall380aaa42010-10-13 06:22:15 +00007439 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007440
John McCall337ec3d2010-10-12 23:13:28 +00007441 // - There's a non-dependent scope specifier, in which case we
7442 // compute it and do a previous lookup there for a function
7443 // or function template.
7444 } else if (!SS.getScopeRep()->isDependent()) {
7445 DC = computeDeclContext(SS);
7446 if (!DC) return 0;
7447
7448 if (RequireCompleteDeclContext(SS, DC)) return 0;
7449
7450 LookupQualifiedName(Previous, DC);
7451
7452 // Ignore things found implicitly in the wrong scope.
7453 // TODO: better diagnostics for this case. Suggesting the right
7454 // qualified scope would be nice...
7455 LookupResult::Filter F = Previous.makeFilter();
7456 while (F.hasNext()) {
7457 NamedDecl *D = F.next();
7458 if (!DC->InEnclosingNamespaceSetOf(
7459 D->getDeclContext()->getRedeclContext()))
7460 F.erase();
7461 }
7462 F.done();
7463
7464 if (Previous.empty()) {
7465 D.setInvalidType();
7466 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7467 return 0;
7468 }
7469
7470 // C++ [class.friend]p1: A friend of a class is a function or
7471 // class that is not a member of the class . . .
7472 if (DC->Equals(CurContext))
7473 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7474
7475 // - There's a scope specifier that does not match any template
7476 // parameter lists, in which case we use some arbitrary context,
7477 // create a method or method template, and wait for instantiation.
7478 // - There's a scope specifier that does match some template
7479 // parameter lists, which we don't handle right now.
7480 } else {
7481 DC = CurContext;
7482 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007483 }
7484
John McCall29ae6e52010-10-13 05:45:15 +00007485 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007486 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007487 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7488 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7489 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007490 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007491 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7492 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007493 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007494 }
John McCall67d1a672009-08-06 02:15:43 +00007495 }
7496
Douglas Gregor182ddf02009-09-28 00:08:27 +00007497 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007498 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007499 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007500 IsDefinition,
7501 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007502 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007503
Douglas Gregor182ddf02009-09-28 00:08:27 +00007504 assert(ND->getDeclContext() == DC);
7505 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007506
John McCallab88d972009-08-31 22:39:49 +00007507 // Add the function declaration to the appropriate lookup tables,
7508 // adjusting the redeclarations list as necessary. We don't
7509 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007510 //
John McCallab88d972009-08-31 22:39:49 +00007511 // Also update the scope-based lookup if the target context's
7512 // lookup context is in lexical scope.
7513 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007514 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007515 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007516 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007517 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007518 }
John McCall02cace72009-08-28 07:59:38 +00007519
7520 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007521 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007522 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007523 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007524 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007525
John McCall337ec3d2010-10-12 23:13:28 +00007526 if (ND->isInvalidDecl())
7527 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007528 else {
7529 FunctionDecl *FD;
7530 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7531 FD = FTD->getTemplatedDecl();
7532 else
7533 FD = cast<FunctionDecl>(ND);
7534
7535 // Mark templated-scope function declarations as unsupported.
7536 if (FD->getNumTemplateParameterLists())
7537 FrD->setUnsupportedFriend(true);
7538 }
John McCall337ec3d2010-10-12 23:13:28 +00007539
John McCalld226f652010-08-21 09:40:31 +00007540 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007541}
7542
John McCalld226f652010-08-21 09:40:31 +00007543void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7544 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007545
Sebastian Redl50de12f2009-03-24 22:27:57 +00007546 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7547 if (!Fn) {
7548 Diag(DelLoc, diag::err_deleted_non_function);
7549 return;
7550 }
7551 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7552 Diag(DelLoc, diag::err_deleted_decl_not_first);
7553 Diag(Prev->getLocation(), diag::note_previous_declaration);
7554 // If the declaration wasn't the first, we delete the function anyway for
7555 // recovery.
7556 }
7557 Fn->setDeleted();
7558}
Sebastian Redl13e88542009-04-27 21:33:24 +00007559
7560static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007561 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007562 Stmt *SubStmt = *CI;
7563 if (!SubStmt)
7564 continue;
7565 if (isa<ReturnStmt>(SubStmt))
7566 Self.Diag(SubStmt->getSourceRange().getBegin(),
7567 diag::err_return_in_constructor_handler);
7568 if (!isa<Expr>(SubStmt))
7569 SearchForReturnInStmt(Self, SubStmt);
7570 }
7571}
7572
7573void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7574 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7575 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7576 SearchForReturnInStmt(*this, Handler);
7577 }
7578}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007579
Mike Stump1eb44332009-09-09 15:08:12 +00007580bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007581 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007582 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7583 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007584
Chandler Carruth73857792010-02-15 11:53:20 +00007585 if (Context.hasSameType(NewTy, OldTy) ||
7586 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007587 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007588
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007589 // Check if the return types are covariant
7590 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007591
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007592 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007593 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7594 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007595 NewClassTy = NewPT->getPointeeType();
7596 OldClassTy = OldPT->getPointeeType();
7597 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007598 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7599 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7600 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7601 NewClassTy = NewRT->getPointeeType();
7602 OldClassTy = OldRT->getPointeeType();
7603 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007604 }
7605 }
Mike Stump1eb44332009-09-09 15:08:12 +00007606
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007607 // The return types aren't either both pointers or references to a class type.
7608 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007609 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007610 diag::err_different_return_type_for_overriding_virtual_function)
7611 << New->getDeclName() << NewTy << OldTy;
7612 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007613
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007614 return true;
7615 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007616
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007617 // C++ [class.virtual]p6:
7618 // If the return type of D::f differs from the return type of B::f, the
7619 // class type in the return type of D::f shall be complete at the point of
7620 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007621 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7622 if (!RT->isBeingDefined() &&
7623 RequireCompleteType(New->getLocation(), NewClassTy,
7624 PDiag(diag::err_covariant_return_incomplete)
7625 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007626 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007627 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007628
Douglas Gregora4923eb2009-11-16 21:35:15 +00007629 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007630 // Check if the new class derives from the old class.
7631 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7632 Diag(New->getLocation(),
7633 diag::err_covariant_return_not_derived)
7634 << New->getDeclName() << NewTy << OldTy;
7635 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7636 return true;
7637 }
Mike Stump1eb44332009-09-09 15:08:12 +00007638
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007639 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007640 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007641 diag::err_covariant_return_inaccessible_base,
7642 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7643 // FIXME: Should this point to the return type?
7644 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007645 // FIXME: this note won't trigger for delayed access control
7646 // diagnostics, and it's impossible to get an undelayed error
7647 // here from access control during the original parse because
7648 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007649 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7650 return true;
7651 }
7652 }
Mike Stump1eb44332009-09-09 15:08:12 +00007653
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007654 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007655 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007656 Diag(New->getLocation(),
7657 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007658 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007659 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7660 return true;
7661 };
Mike Stump1eb44332009-09-09 15:08:12 +00007662
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007663
7664 // The new class type must have the same or less qualifiers as the old type.
7665 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7666 Diag(New->getLocation(),
7667 diag::err_covariant_return_type_class_type_more_qualified)
7668 << New->getDeclName() << NewTy << OldTy;
7669 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7670 return true;
7671 };
Mike Stump1eb44332009-09-09 15:08:12 +00007672
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007673 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007674}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007675
Douglas Gregor4ba31362009-12-01 17:24:26 +00007676/// \brief Mark the given method pure.
7677///
7678/// \param Method the method to be marked pure.
7679///
7680/// \param InitRange the source range that covers the "0" initializer.
7681bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00007682 SourceLocation EndLoc = InitRange.getEnd();
7683 if (EndLoc.isValid())
7684 Method->setRangeEnd(EndLoc);
7685
Douglas Gregor4ba31362009-12-01 17:24:26 +00007686 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7687 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007688 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00007689 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00007690
7691 if (!Method->isInvalidDecl())
7692 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7693 << Method->getDeclName() << InitRange;
7694 return true;
7695}
7696
John McCall731ad842009-12-19 09:28:58 +00007697/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7698/// an initializer for the out-of-line declaration 'Dcl'. The scope
7699/// is a fresh scope pushed for just this purpose.
7700///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007701/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7702/// static data member of class X, names should be looked up in the scope of
7703/// class X.
John McCalld226f652010-08-21 09:40:31 +00007704void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007705 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007706 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007707
John McCall731ad842009-12-19 09:28:58 +00007708 // We should only get called for declarations with scope specifiers, like:
7709 // int foo::bar;
7710 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007711 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007712}
7713
7714/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007715/// initializer for the out-of-line declaration 'D'.
7716void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007717 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00007718 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007719
John McCall731ad842009-12-19 09:28:58 +00007720 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007721 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007722}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007723
7724/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7725/// C++ if/switch/while/for statement.
7726/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007727DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007728 // C++ 6.4p2:
7729 // The declarator shall not specify a function or an array.
7730 // The type-specifier-seq shall not contain typedef and shall not declare a
7731 // new class or enumeration.
7732 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7733 "Parser allowed 'typedef' as storage class of condition decl.");
7734
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007735 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007736 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7737 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007738
7739 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7740 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7741 // would be created and CXXConditionDeclExpr wants a VarDecl.
7742 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7743 << D.getSourceRange();
7744 return DeclResult();
7745 } else if (OwnedTag && OwnedTag->isDefinition()) {
7746 // The type-specifier-seq shall not declare a new class or enumeration.
7747 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7748 }
7749
John McCalld226f652010-08-21 09:40:31 +00007750 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007751 if (!Dcl)
7752 return DeclResult();
7753
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007754 return Dcl;
7755}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007756
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007757void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7758 bool DefinitionRequired) {
7759 // Ignore any vtable uses in unevaluated operands or for classes that do
7760 // not have a vtable.
7761 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7762 CurContext->isDependentContext() ||
7763 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007764 return;
7765
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007766 // Try to insert this class into the map.
7767 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7768 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7769 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7770 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007771 // If we already had an entry, check to see if we are promoting this vtable
7772 // to required a definition. If so, we need to reappend to the VTableUses
7773 // list, since we may have already processed the first entry.
7774 if (DefinitionRequired && !Pos.first->second) {
7775 Pos.first->second = true;
7776 } else {
7777 // Otherwise, we can early exit.
7778 return;
7779 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007780 }
7781
7782 // Local classes need to have their virtual members marked
7783 // immediately. For all other classes, we mark their virtual members
7784 // at the end of the translation unit.
7785 if (Class->isLocalClass())
7786 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007787 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007788 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007789}
7790
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007791bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007792 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007793 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007794
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007795 // Note: The VTableUses vector could grow as a result of marking
7796 // the members of a class as "used", so we check the size each
7797 // time through the loop and prefer indices (with are stable) to
7798 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00007799 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007800 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007801 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007802 if (!Class)
7803 continue;
7804
7805 SourceLocation Loc = VTableUses[I].second;
7806
7807 // If this class has a key function, but that key function is
7808 // defined in another translation unit, we don't need to emit the
7809 // vtable even though we're using it.
7810 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007811 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007812 switch (KeyFunction->getTemplateSpecializationKind()) {
7813 case TSK_Undeclared:
7814 case TSK_ExplicitSpecialization:
7815 case TSK_ExplicitInstantiationDeclaration:
7816 // The key function is in another translation unit.
7817 continue;
7818
7819 case TSK_ExplicitInstantiationDefinition:
7820 case TSK_ImplicitInstantiation:
7821 // We will be instantiating the key function.
7822 break;
7823 }
7824 } else if (!KeyFunction) {
7825 // If we have a class with no key function that is the subject
7826 // of an explicit instantiation declaration, suppress the
7827 // vtable; it will live with the explicit instantiation
7828 // definition.
7829 bool IsExplicitInstantiationDeclaration
7830 = Class->getTemplateSpecializationKind()
7831 == TSK_ExplicitInstantiationDeclaration;
7832 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7833 REnd = Class->redecls_end();
7834 R != REnd; ++R) {
7835 TemplateSpecializationKind TSK
7836 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7837 if (TSK == TSK_ExplicitInstantiationDeclaration)
7838 IsExplicitInstantiationDeclaration = true;
7839 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7840 IsExplicitInstantiationDeclaration = false;
7841 break;
7842 }
7843 }
7844
7845 if (IsExplicitInstantiationDeclaration)
7846 continue;
7847 }
7848
7849 // Mark all of the virtual members of this class as referenced, so
7850 // that we can build a vtable. Then, tell the AST consumer that a
7851 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00007852 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007853 MarkVirtualMembersReferenced(Loc, Class);
7854 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7855 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7856
7857 // Optionally warn if we're emitting a weak vtable.
7858 if (Class->getLinkage() == ExternalLinkage &&
7859 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007860 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007861 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7862 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007863 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007864 VTableUses.clear();
7865
Douglas Gregor78844032011-04-22 22:25:37 +00007866 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007867}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007868
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007869void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7870 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007871 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7872 e = RD->method_end(); i != e; ++i) {
7873 CXXMethodDecl *MD = *i;
7874
7875 // C++ [basic.def.odr]p2:
7876 // [...] A virtual member function is used if it is not pure. [...]
7877 if (MD->isVirtual() && !MD->isPure())
7878 MarkDeclarationReferenced(Loc, MD);
7879 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007880
7881 // Only classes that have virtual bases need a VTT.
7882 if (RD->getNumVBases() == 0)
7883 return;
7884
7885 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7886 e = RD->bases_end(); i != e; ++i) {
7887 const CXXRecordDecl *Base =
7888 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007889 if (Base->getNumVBases() == 0)
7890 continue;
7891 MarkVirtualMembersReferenced(Loc, Base);
7892 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007893}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007894
7895/// SetIvarInitializers - This routine builds initialization ASTs for the
7896/// Objective-C implementation whose ivars need be initialized.
7897void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7898 if (!getLangOptions().CPlusPlus)
7899 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007900 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007901 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7902 CollectIvarsToConstructOrDestruct(OID, ivars);
7903 if (ivars.empty())
7904 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007905 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007906 for (unsigned i = 0; i < ivars.size(); i++) {
7907 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007908 if (Field->isInvalidDecl())
7909 continue;
7910
Sean Huntcbb67482011-01-08 20:30:50 +00007911 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007912 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7913 InitializationKind InitKind =
7914 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7915
7916 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007917 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007918 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007919 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007920 // Note, MemberInit could actually come back empty if no initialization
7921 // is required (e.g., because it would call a trivial default constructor)
7922 if (!MemberInit.get() || MemberInit.isInvalid())
7923 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007924
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007925 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007926 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7927 SourceLocation(),
7928 MemberInit.takeAs<Expr>(),
7929 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007930 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007931
7932 // Be sure that the destructor is accessible and is marked as referenced.
7933 if (const RecordType *RecordTy
7934 = Context.getBaseElementType(Field->getType())
7935 ->getAs<RecordType>()) {
7936 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007937 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007938 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7939 CheckDestructorAccess(Field->getLocation(), Destructor,
7940 PDiag(diag::err_access_dtor_ivar)
7941 << Context.getBaseElementType(Field->getType()));
7942 }
7943 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007944 }
7945 ObjCImplementation->setIvarInitializers(Context,
7946 AllToInit.data(), AllToInit.size());
7947 }
7948}