blob: b8977cfa142d9c793680c8dabaa70038ed69d925 [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
14#include "Sema.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000027#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000028#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000029
30using namespace clang;
31
Chris Lattner8123a952008-04-10 02:22:51 +000032//===----------------------------------------------------------------------===//
33// CheckDefaultArgumentVisitor
34//===----------------------------------------------------------------------===//
35
Chris Lattner9e979552008-04-12 23:52:44 +000036namespace {
37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
38 /// the default argument of a parameter to determine whether it
39 /// contains any ill-formed subexpressions. For example, this will
40 /// diagnose the use of local variables or parameters within the
41 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000042 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000043 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000044 Expr *DefaultArg;
45 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000046
Chris Lattner9e979552008-04-12 23:52:44 +000047 public:
Mike Stump1eb44332009-09-09 15:08:12 +000048 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000049 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-04-12 23:52:44 +000051 bool VisitExpr(Expr *Node);
52 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000053 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000054 };
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 /// VisitExpr - Visit all of the children of this expression.
57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
58 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000059 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000060 E = Node->child_end(); I != E; ++I)
61 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000062 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000063 }
64
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitDeclRefExpr - Visit a reference to a declaration, to
66 /// determine whether this declaration can be used in the default
67 /// argument expression.
68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000069 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000070 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
71 // C++ [dcl.fct.default]p9
72 // Default arguments are evaluated each time the function is
73 // called. The order of evaluation of function arguments is
74 // unspecified. Consequently, parameters of a function shall not
75 // be used in default argument expressions, even if they are not
76 // evaluated. Parameters of a function declared before a default
77 // argument expression are in scope and can hide namespace and
78 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000079 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000080 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000081 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000082 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000083 // C++ [dcl.fct.default]p7
84 // Local variables shall not be used in default argument
85 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000086 if (VDecl->isBlockVarDecl())
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_local)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000090 }
Chris Lattner8123a952008-04-10 02:22:51 +000091
Douglas Gregor3996f232008-11-04 13:41:56 +000092 return false;
93 }
Chris Lattner9e979552008-04-12 23:52:44 +000094
Douglas Gregor796da182008-11-04 14:32:21 +000095 /// VisitCXXThisExpr - Visit a C++ "this" expression.
96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
97 // C++ [dcl.fct.default]p8:
98 // The keyword this shall not be used in a default argument of a
99 // member function.
100 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_this)
102 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104}
105
Anders Carlssoned961f92009-08-25 02:29:20 +0000106bool
107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000108 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000109 QualType ParamType = Param->getType();
110
Anders Carlsson5653ca52009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlssoned961f92009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000127 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Anders Carlssoned961f92009-08-25 02:29:20 +0000131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Anders Carlssoned961f92009-08-25 02:29:20 +0000134 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000137}
138
Chris Lattner8123a952008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000142void
Mike Stump1eb44332009-09-09 15:08:12 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Chris Lattnerb28317a2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlsson66e30672009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Anders Carlssoned961f92009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000170}
171
Douglas Gregor61366e92008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000179 if (!param)
180 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Anders Carlsson5e300d12009-06-12 16:51:40 +0000186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000187}
188
Douglas Gregor72b505b2008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000192 if (!param)
193 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Anders Carlsson5e300d12009-06-12 16:51:40 +0000197 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Anders Carlsson5e300d12009-06-12 16:51:40 +0000199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000200}
201
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattner3d1cee32008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000256 //
257 // C++ [dcl.fct.default]p6:
258 // Except for member functions of class templates, the default arguments
259 // in a member function definition that appears outside of the class
260 // definition are added to the set of default arguments provided by the
261 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
263 ParmVarDecl *OldParam = Old->getParamDecl(p);
264 ParmVarDecl *NewParam = New->getParamDecl(p);
265
Douglas Gregor6cc15182009-09-11 18:44:32 +0000266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000267 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000268 diag::err_param_default_argument_redefinition)
Douglas Gregor6cc15182009-09-11 18:44:32 +0000269 << NewParam->getDefaultArgRange();
270
271 // Look for the function declaration where the default argument was
272 // actually written, which may be a declaration prior to Old.
273 for (FunctionDecl *Older = Old->getPreviousDeclaration();
274 Older; Older = Older->getPreviousDeclaration()) {
275 if (!Older->getParamDecl(p)->hasDefaultArg())
276 break;
277
278 OldParam = Older->getParamDecl(p);
279 }
280
281 Diag(OldParam->getLocation(), diag::note_previous_definition)
282 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000283 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000284 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000285 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000286 if (OldParam->hasUninstantiatedDefaultArg())
287 NewParam->setUninstantiatedDefaultArg(
288 OldParam->getUninstantiatedDefaultArg());
289 else
290 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000291 } else if (NewParam->hasDefaultArg()) {
292 if (New->getDescribedFunctionTemplate()) {
293 // Paragraph 4, quoted above, only applies to non-template functions.
294 Diag(NewParam->getLocation(),
295 diag::err_param_default_argument_template_redecl)
296 << NewParam->getDefaultArgRange();
297 Diag(Old->getLocation(), diag::note_template_prev_declaration)
298 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000299 } else if (New->getTemplateSpecializationKind()
300 != TSK_ImplicitInstantiation &&
301 New->getTemplateSpecializationKind() != TSK_Undeclared) {
302 // C++ [temp.expr.spec]p21:
303 // Default function arguments shall not be specified in a declaration
304 // or a definition for one of the following explicit specializations:
305 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000306 // - the explicit specialization of a member function template;
307 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000308 // template where the class template specialization to which the
309 // member function specialization belongs is implicitly
310 // instantiated.
311 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
312 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
313 << New->getDeclName()
314 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000315 } else if (New->getDeclContext()->isDependentContext()) {
316 // C++ [dcl.fct.default]p6 (DR217):
317 // Default arguments for a member function of a class template shall
318 // be specified on the initial declaration of the member function
319 // within the class template.
320 //
321 // Reading the tea leaves a bit in DR217 and its reference to DR205
322 // leads me to the conclusion that one cannot add default function
323 // arguments for an out-of-line definition of a member function of a
324 // dependent type.
325 int WhichKind = 2;
326 if (CXXRecordDecl *Record
327 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
328 if (Record->getDescribedClassTemplate())
329 WhichKind = 0;
330 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
331 WhichKind = 1;
332 else
333 WhichKind = 2;
334 }
335
336 Diag(NewParam->getLocation(),
337 diag::err_param_default_argument_member_template_redecl)
338 << WhichKind
339 << NewParam->getDefaultArgRange();
340 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000341 }
342 }
343
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000344 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000345 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
346 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000347 Invalid = true;
348 }
349
Douglas Gregorcda9c672009-02-16 17:45:42 +0000350 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000351}
352
353/// CheckCXXDefaultArguments - Verify that the default arguments for a
354/// function declaration are well-formed according to C++
355/// [dcl.fct.default].
356void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
357 unsigned NumParams = FD->getNumParams();
358 unsigned p;
359
360 // Find first parameter with a default argument
361 for (p = 0; p < NumParams; ++p) {
362 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000363 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364 break;
365 }
366
367 // C++ [dcl.fct.default]p4:
368 // In a given function declaration, all parameters
369 // subsequent to a parameter with a default argument shall
370 // have default arguments supplied in this or previous
371 // declarations. A default argument shall not be redefined
372 // by a later declaration (not even to the same value).
373 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000374 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000377 if (Param->isInvalidDecl())
378 /* We already complained about this parameter. */;
379 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000380 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000381 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000382 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 else
Mike Stump1eb44332009-09-09 15:08:12 +0000384 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chris Lattner3d1cee32008-04-08 05:04:30 +0000387 LastMissingDefaultArg = p;
388 }
389 }
390
391 if (LastMissingDefaultArg > 0) {
392 // Some default arguments were missing. Clear out all of the
393 // default arguments up to (and including) the last missing
394 // default argument, so that we leave the function parameters
395 // in a semantically valid state.
396 for (p = 0; p <= LastMissingDefaultArg; ++p) {
397 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000398 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000399 if (!Param->hasUnparsedDefaultArg())
400 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 Param->setDefaultArg(0);
402 }
403 }
404 }
405}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000406
Douglas Gregorb48fe382008-10-31 09:07:45 +0000407/// isCurrentClassName - Determine whether the identifier II is the
408/// name of the class type currently being defined. In the case of
409/// nested classes, this will only return true if II is the name of
410/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000411bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
412 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000413 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000414 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000415 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
417 } else
418 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
419
420 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421 return &II == CurDecl->getIdentifier();
422 else
423 return false;
424}
425
Mike Stump1eb44332009-09-09 15:08:12 +0000426/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000427///
428/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
429/// and returns NULL otherwise.
430CXXBaseSpecifier *
431Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
432 SourceRange SpecifierRange,
433 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000434 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000435 SourceLocation BaseLoc) {
436 // C++ [class.union]p1:
437 // A union shall not have base classes.
438 if (Class->isUnion()) {
439 Diag(Class->getLocation(), diag::err_base_clause_on_union)
440 << SpecifierRange;
441 return 0;
442 }
443
444 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000445 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000446 Class->getTagKind() == RecordDecl::TK_class,
447 Access, BaseType);
448
449 // Base specifiers must be record types.
450 if (!BaseType->isRecordType()) {
451 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
452 return 0;
453 }
454
455 // C++ [class.union]p1:
456 // A union shall not be used as a base class.
457 if (BaseType->isUnionType()) {
458 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
459 return 0;
460 }
461
462 // C++ [class.derived]p2:
463 // The class-name in a base-specifier shall not be an incompletely
464 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000465 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000466 PDiag(diag::err_incomplete_base_class)
467 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000468 return 0;
469
Eli Friedman1d954f62009-08-15 21:55:26 +0000470 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000471 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000472 assert(BaseDecl && "Record type has no declaration");
473 BaseDecl = BaseDecl->getDefinition(Context);
474 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000475 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
476 assert(CXXBaseDecl && "Base type is not a C++ type");
477 if (!CXXBaseDecl->isEmpty())
478 Class->setEmpty(false);
479 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000480 Class->setPolymorphic(true);
481
482 // C++ [dcl.init.aggr]p1:
483 // An aggregate is [...] a class with [...] no base classes [...].
484 Class->setAggregate(false);
485 Class->setPOD(false);
486
Anders Carlsson347ba892009-04-16 00:08:20 +0000487 if (Virtual) {
488 // C++ [class.ctor]p5:
489 // A constructor is trivial if its class has no virtual base classes.
490 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000491
492 // C++ [class.copy]p6:
493 // A copy constructor is trivial if its class has no virtual base classes.
494 Class->setHasTrivialCopyConstructor(false);
495
496 // C++ [class.copy]p11:
497 // A copy assignment operator is trivial if its class has no virtual
498 // base classes.
499 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000500
501 // C++0x [meta.unary.prop] is_empty:
502 // T is a class type, but not a union type, with ... no virtual base
503 // classes
504 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000505 } else {
506 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000507 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000508 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000509 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
510 Class->setHasTrivialConstructor(false);
511
512 // C++ [class.copy]p6:
513 // A copy constructor is trivial if all the direct base classes of its
514 // class have trivial copy constructors.
515 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
516 Class->setHasTrivialCopyConstructor(false);
517
518 // C++ [class.copy]p11:
519 // A copy assignment operator is trivial if all the direct base classes
520 // of its class have trivial copy assignment operators.
521 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
522 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000523 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000524
525 // C++ [class.ctor]p3:
526 // A destructor is trivial if all the direct base classes of its class
527 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000528 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
529 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531 // Create the base specifier.
532 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000533 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
534 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000535 Access, BaseType);
536}
537
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000538/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
539/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000540/// example:
541/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000542/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000543Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000544Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000545 bool Virtual, AccessSpecifier Access,
546 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000547 if (!classdecl)
548 return true;
549
Douglas Gregor40808ce2009-03-09 23:48:35 +0000550 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000551 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000552 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000553 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
554 Virtual, Access,
555 BaseType, BaseLoc))
556 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Douglas Gregor2943aed2009-03-03 04:44:36 +0000558 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000559}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000560
Douglas Gregor2943aed2009-03-03 04:44:36 +0000561/// \brief Performs the actual work of attaching the given base class
562/// specifiers to a C++ class.
563bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
564 unsigned NumBases) {
565 if (NumBases == 0)
566 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000567
568 // Used to keep track of which base types we have already seen, so
569 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000570 // that the key is always the unqualified canonical type of the base
571 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000572 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
573
574 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000575 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000577 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000578 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000579 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000580 NewBaseType = NewBaseType.getUnqualifiedType();
581
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000582 if (KnownBaseTypes[NewBaseType]) {
583 // C++ [class.mi]p3:
584 // A class shall not be specified as a direct base class of a
585 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000587 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000588 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000590
591 // Delete the duplicate base class specifier; we're going to
592 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000593 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594
595 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000596 } else {
597 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598 KnownBaseTypes[NewBaseType] = Bases[idx];
599 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000600 }
601 }
602
603 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000604 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000605
606 // Delete the remaining (good) base class specifiers, since their
607 // data has been copied into the CXXRecordDecl.
608 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000609 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000610
611 return Invalid;
612}
613
614/// ActOnBaseSpecifiers - Attach the given base specifiers to the
615/// class, after checking whether there are any duplicate base
616/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000617void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 unsigned NumBases) {
619 if (!ClassDecl || !Bases || !NumBases)
620 return;
621
622 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000623 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000625}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000626
Douglas Gregora8f32e02009-10-06 17:59:45 +0000627/// \brief Determine whether the type \p Derived is a C++ class that is
628/// derived from the type \p Base.
629bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
630 if (!getLangOptions().CPlusPlus)
631 return false;
632
633 const RecordType *DerivedRT = Derived->getAs<RecordType>();
634 if (!DerivedRT)
635 return false;
636
637 const RecordType *BaseRT = Base->getAs<RecordType>();
638 if (!BaseRT)
639 return false;
640
641 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
642 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
643 return DerivedRD->isDerivedFrom(BaseRD);
644}
645
646/// \brief Determine whether the type \p Derived is a C++ class that is
647/// derived from the type \p Base.
648bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
649 if (!getLangOptions().CPlusPlus)
650 return false;
651
652 const RecordType *DerivedRT = Derived->getAs<RecordType>();
653 if (!DerivedRT)
654 return false;
655
656 const RecordType *BaseRT = Base->getAs<RecordType>();
657 if (!BaseRT)
658 return false;
659
660 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
661 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
662 return DerivedRD->isDerivedFrom(BaseRD, Paths);
663}
664
665/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
666/// conversion (where Derived and Base are class types) is
667/// well-formed, meaning that the conversion is unambiguous (and
668/// that all of the base classes are accessible). Returns true
669/// and emits a diagnostic if the code is ill-formed, returns false
670/// otherwise. Loc is the location where this routine should point to
671/// if there is an error, and Range is the source range to highlight
672/// if there is an error.
673bool
674Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
675 unsigned InaccessibleBaseID,
676 unsigned AmbigiousBaseConvID,
677 SourceLocation Loc, SourceRange Range,
678 DeclarationName Name) {
679 // First, determine whether the path from Derived to Base is
680 // ambiguous. This is slightly more expensive than checking whether
681 // the Derived to Base conversion exists, because here we need to
682 // explore multiple paths to determine if there is an ambiguity.
683 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
684 /*DetectVirtual=*/false);
685 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
686 assert(DerivationOkay &&
687 "Can only be used with a derived-to-base conversion");
688 (void)DerivationOkay;
689
690 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
691 // Check that the base class can be accessed.
692 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
693 Name);
694 }
695
696 // We know that the derived-to-base conversion is ambiguous, and
697 // we're going to produce a diagnostic. Perform the derived-to-base
698 // search just one more time to compute all of the possible paths so
699 // that we can print them out. This is more expensive than any of
700 // the previous derived-to-base checks we've done, but at this point
701 // performance isn't as much of an issue.
702 Paths.clear();
703 Paths.setRecordingPaths(true);
704 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
705 assert(StillOkay && "Can only be used with a derived-to-base conversion");
706 (void)StillOkay;
707
708 // Build up a textual representation of the ambiguous paths, e.g.,
709 // D -> B -> A, that will be used to illustrate the ambiguous
710 // conversions in the diagnostic. We only print one of the paths
711 // to each base class subobject.
712 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
713
714 Diag(Loc, AmbigiousBaseConvID)
715 << Derived << Base << PathDisplayStr << Range << Name;
716 return true;
717}
718
719bool
720Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
721 SourceLocation Loc, SourceRange Range) {
722 return CheckDerivedToBaseConversion(Derived, Base,
723 diag::err_conv_to_inaccessible_base,
724 diag::err_ambiguous_derived_to_base_conv,
725 Loc, Range, DeclarationName());
726}
727
728
729/// @brief Builds a string representing ambiguous paths from a
730/// specific derived class to different subobjects of the same base
731/// class.
732///
733/// This function builds a string that can be used in error messages
734/// to show the different paths that one can take through the
735/// inheritance hierarchy to go from the derived class to different
736/// subobjects of a base class. The result looks something like this:
737/// @code
738/// struct D -> struct B -> struct A
739/// struct D -> struct C -> struct A
740/// @endcode
741std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
742 std::string PathDisplayStr;
743 std::set<unsigned> DisplayedPaths;
744 for (CXXBasePaths::paths_iterator Path = Paths.begin();
745 Path != Paths.end(); ++Path) {
746 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
747 // We haven't displayed a path to this particular base
748 // class subobject yet.
749 PathDisplayStr += "\n ";
750 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
751 for (CXXBasePath::const_iterator Element = Path->begin();
752 Element != Path->end(); ++Element)
753 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
754 }
755 }
756
757 return PathDisplayStr;
758}
759
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000760//===----------------------------------------------------------------------===//
761// C++ class member Handling
762//===----------------------------------------------------------------------===//
763
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000764/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
765/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
766/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000767/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000768Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000769Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000770 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000771 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000772 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000773 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000774 Expr *BitWidth = static_cast<Expr*>(BW);
775 Expr *Init = static_cast<Expr*>(InitExpr);
776 SourceLocation Loc = D.getIdentifierLoc();
777
Sebastian Redl669d5d72008-11-14 23:42:31 +0000778 bool isFunc = D.isFunctionDeclarator();
779
John McCall67d1a672009-08-06 02:15:43 +0000780 assert(!DS.isFriendSpecified());
781
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000782 // C++ 9.2p6: A member shall not be declared to have automatic storage
783 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000784 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
785 // data members and cannot be applied to names declared const or static,
786 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000787 switch (DS.getStorageClassSpec()) {
788 case DeclSpec::SCS_unspecified:
789 case DeclSpec::SCS_typedef:
790 case DeclSpec::SCS_static:
791 // FALL THROUGH.
792 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000793 case DeclSpec::SCS_mutable:
794 if (isFunc) {
795 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000796 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000797 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000798 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Sebastian Redla11f42f2008-11-17 23:24:37 +0000800 // FIXME: It would be nicer if the keyword was ignored only for this
801 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000802 D.getMutableDeclSpec().ClearStorageClassSpecs();
803 } else {
804 QualType T = GetTypeForDeclarator(D, S);
805 diag::kind err = static_cast<diag::kind>(0);
806 if (T->isReferenceType())
807 err = diag::err_mutable_reference;
808 else if (T.isConstQualified())
809 err = diag::err_mutable_const;
810 if (err != 0) {
811 if (DS.getStorageClassSpecLoc().isValid())
812 Diag(DS.getStorageClassSpecLoc(), err);
813 else
814 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000815 // FIXME: It would be nicer if the keyword was ignored only for this
816 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000817 D.getMutableDeclSpec().ClearStorageClassSpecs();
818 }
819 }
820 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000821 default:
822 if (DS.getStorageClassSpecLoc().isValid())
823 Diag(DS.getStorageClassSpecLoc(),
824 diag::err_storageclass_invalid_for_member);
825 else
826 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
827 D.getMutableDeclSpec().ClearStorageClassSpecs();
828 }
829
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000830 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000831 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000832 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000833 // Check also for this case:
834 //
835 // typedef int f();
836 // f a;
837 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000838 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000839 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000840 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000841
Sebastian Redl669d5d72008-11-14 23:42:31 +0000842 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
843 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000844 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000845
846 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000847 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000848 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000849 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
850 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000851 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000852 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000853 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
854 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000855 if (!Member) {
856 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000857 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000858 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000859
860 // Non-instance-fields can't have a bitfield.
861 if (BitWidth) {
862 if (Member->isInvalidDecl()) {
863 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000864 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000865 // C++ 9.6p3: A bit-field shall not be a static member.
866 // "static member 'A' cannot be a bit-field"
867 Diag(Loc, diag::err_static_not_bitfield)
868 << Name << BitWidth->getSourceRange();
869 } else if (isa<TypedefDecl>(Member)) {
870 // "typedef member 'x' cannot be a bit-field"
871 Diag(Loc, diag::err_typedef_not_bitfield)
872 << Name << BitWidth->getSourceRange();
873 } else {
874 // A function typedef ("typedef int f(); f a;").
875 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
876 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000877 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000878 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner8b963ef2009-03-05 23:01:03 +0000881 DeleteExpr(BitWidth);
882 BitWidth = 0;
883 Member->setInvalidDecl();
884 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000885
886 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Douglas Gregor37b372b2009-08-20 22:52:58 +0000888 // If we have declared a member function template, set the access of the
889 // templated declaration as well.
890 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
891 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000892 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893
Douglas Gregor10bd3682008-11-17 22:58:34 +0000894 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000895
Douglas Gregor021c3b32009-03-11 23:00:04 +0000896 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000897 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000898 if (Deleted) // FIXME: Source location is not very good.
899 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000900
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000901 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000902 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000903 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000904 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000905 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000906}
907
Douglas Gregor7ad83902008-11-05 04:29:56 +0000908/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000909Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000910Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000911 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000912 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000913 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000914 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000915 SourceLocation IdLoc,
916 SourceLocation LParenLoc,
917 ExprTy **Args, unsigned NumArgs,
918 SourceLocation *CommaLocs,
919 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000920 if (!ConstructorD)
921 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000923 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000924
925 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000926 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000927 if (!Constructor) {
928 // The user wrote a constructor initializer on a function that is
929 // not a C++ constructor. Ignore the error for now, because we may
930 // have more member initializers coming; we'll diagnose it just
931 // once in ActOnMemInitializers.
932 return true;
933 }
934
935 CXXRecordDecl *ClassDecl = Constructor->getParent();
936
937 // C++ [class.base.init]p2:
938 // Names in a mem-initializer-id are looked up in the scope of the
939 // constructor’s class and, if not found in that scope, are looked
940 // up in the scope containing the constructor’s
941 // definition. [Note: if the constructor’s class contains a member
942 // with the same name as a direct or virtual base class of the
943 // class, a mem-initializer-id naming the member or base class and
944 // composed of a single identifier refers to the class member. A
945 // mem-initializer-id for the hidden base class may be specified
946 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000947 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000948 // Look for a member, first.
949 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000950 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000951 = ClassDecl->lookup(MemberOrBase);
952 if (Result.first != Result.second)
953 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000954
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000955 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000956
Eli Friedman59c04372009-07-29 19:44:27 +0000957 if (Member)
958 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
959 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000960 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000961 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000962 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000963 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000964 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000965 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
966 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000968 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000969
Eli Friedman59c04372009-07-29 19:44:27 +0000970 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
971 RParenLoc, ClassDecl);
972}
973
John McCallb4190042009-11-04 23:02:40 +0000974/// Checks an initializer expression for use of uninitialized fields, such as
975/// containing the field that is being initialized. Returns true if there is an
976/// uninitialized field was used an updates the SourceLocation parameter; false
977/// otherwise.
978static bool InitExprContainsUninitializedFields(const Stmt* S,
979 const FieldDecl* LhsField,
980 SourceLocation* L) {
981 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
982 if (ME) {
983 const NamedDecl* RhsField = ME->getMemberDecl();
984 if (RhsField == LhsField) {
985 // Initializing a field with itself. Throw a warning.
986 // But wait; there are exceptions!
987 // Exception #1: The field may not belong to this record.
988 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
989 const Expr* base = ME->getBase();
990 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
991 // Even though the field matches, it does not belong to this record.
992 return false;
993 }
994 // None of the exceptions triggered; return true to indicate an
995 // uninitialized field was used.
996 *L = ME->getMemberLoc();
997 return true;
998 }
999 }
1000 bool found = false;
1001 for (Stmt::const_child_iterator it = S->child_begin();
1002 it != S->child_end() && found == false;
1003 ++it) {
1004 if (isa<CallExpr>(S)) {
1005 // Do not descend into function calls or constructors, as the use
1006 // of an uninitialized field may be valid. One would have to inspect
1007 // the contents of the function/ctor to determine if it is safe or not.
1008 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1009 // may be safe, depending on what the function/ctor does.
1010 continue;
1011 }
1012 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1013 }
1014 return found;
1015}
1016
Eli Friedman59c04372009-07-29 19:44:27 +00001017Sema::MemInitResult
1018Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1019 unsigned NumArgs, SourceLocation IdLoc,
1020 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001021 // Diagnose value-uses of fields to initialize themselves, e.g.
1022 // foo(foo)
1023 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001024 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001025 for (unsigned i = 0; i < NumArgs; ++i) {
1026 SourceLocation L;
1027 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1028 // FIXME: Return true in the case when other fields are used before being
1029 // uninitialized. For example, let this field be the i'th field. When
1030 // initializing the i'th field, throw a warning if any of the >= i'th
1031 // fields are used, as they are not yet initialized.
1032 // Right now we are only handling the case where the i'th field uses
1033 // itself in its initializer.
1034 Diag(L, diag::warn_field_is_uninit);
1035 }
1036 }
1037
Eli Friedman59c04372009-07-29 19:44:27 +00001038 bool HasDependentArg = false;
1039 for (unsigned i = 0; i < NumArgs; i++)
1040 HasDependentArg |= Args[i]->isTypeDependent();
1041
1042 CXXConstructorDecl *C = 0;
1043 QualType FieldType = Member->getType();
1044 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1045 FieldType = Array->getElementType();
1046 if (FieldType->isDependentType()) {
1047 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001048 } else if (FieldType->isRecordType()) {
1049 // Member is a record (struct/union/class), so pass the initializer
1050 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001051 if (!HasDependentArg) {
1052 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1053
1054 C = PerformInitializationByConstructor(FieldType,
1055 MultiExprArg(*this,
1056 (void**)Args,
1057 NumArgs),
1058 IdLoc,
1059 SourceRange(IdLoc, RParenLoc),
1060 Member->getDeclName(), IK_Direct,
1061 ConstructorArgs);
1062
1063 if (C) {
1064 // Take over the constructor arguments as our own.
1065 NumArgs = ConstructorArgs.size();
1066 Args = (Expr **)ConstructorArgs.take();
1067 }
1068 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001069 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001070 // The member type is not a record type (or an array of record
1071 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001072 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001073 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1074 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001075 Expr *NewExp;
1076 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001077 if (FieldType->isReferenceType()) {
1078 Diag(IdLoc, diag::err_null_intialized_reference_member)
1079 << Member->getDeclName();
1080 return Diag(Member->getLocation(), diag::note_declared_at);
1081 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001082 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1083 NumArgs = 1;
1084 }
1085 else
1086 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001087 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1088 return true;
1089 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001090 }
Eli Friedman59c04372009-07-29 19:44:27 +00001091 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001092 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001093 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001094}
1095
1096Sema::MemInitResult
1097Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1098 unsigned NumArgs, SourceLocation IdLoc,
1099 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1100 bool HasDependentArg = false;
1101 for (unsigned i = 0; i < NumArgs; i++)
1102 HasDependentArg |= Args[i]->isTypeDependent();
1103
1104 if (!BaseType->isDependentType()) {
1105 if (!BaseType->isRecordType())
1106 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1107 << BaseType << SourceRange(IdLoc, RParenLoc);
1108
1109 // C++ [class.base.init]p2:
1110 // [...] Unless the mem-initializer-id names a nonstatic data
1111 // member of the constructor’s class or a direct or virtual base
1112 // of that class, the mem-initializer is ill-formed. A
1113 // mem-initializer-list can initialize a base class using any
1114 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Eli Friedman59c04372009-07-29 19:44:27 +00001116 // First, check for a direct base class.
1117 const CXXBaseSpecifier *DirectBaseSpec = 0;
1118 for (CXXRecordDecl::base_class_const_iterator Base =
1119 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001120 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +00001121 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1122 // We found a direct base of this type. That's what we're
1123 // initializing.
1124 DirectBaseSpec = &*Base;
1125 break;
1126 }
1127 }
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Eli Friedman59c04372009-07-29 19:44:27 +00001129 // Check for a virtual base class.
1130 // FIXME: We might be able to short-circuit this if we know in advance that
1131 // there are no virtual bases.
1132 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1133 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1134 // We haven't found a base yet; search the class hierarchy for a
1135 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001136 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1137 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001138 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001139 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001140 Path != Paths.end(); ++Path) {
1141 if (Path->back().Base->isVirtual()) {
1142 VirtualBaseSpec = Path->back().Base;
1143 break;
1144 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001145 }
1146 }
1147 }
Eli Friedman59c04372009-07-29 19:44:27 +00001148
1149 // C++ [base.class.init]p2:
1150 // If a mem-initializer-id is ambiguous because it designates both
1151 // a direct non-virtual base class and an inherited virtual base
1152 // class, the mem-initializer is ill-formed.
1153 if (DirectBaseSpec && VirtualBaseSpec)
1154 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1155 << BaseType << SourceRange(IdLoc, RParenLoc);
1156 // C++ [base.class.init]p2:
1157 // Unless the mem-initializer-id names a nonstatic data membeer of the
1158 // constructor's class ot a direst or virtual base of that class, the
1159 // mem-initializer is ill-formed.
1160 if (!DirectBaseSpec && !VirtualBaseSpec)
1161 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1162 << BaseType << ClassDecl->getNameAsCString()
1163 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001164 }
1165
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001166 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001167 if (!BaseType->isDependentType() && !HasDependentArg) {
1168 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
1169 Context.getCanonicalType(BaseType));
Douglas Gregor39da0b82009-09-09 23:08:42 +00001170 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1171
1172 C = PerformInitializationByConstructor(BaseType,
1173 MultiExprArg(*this,
1174 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001175 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001176 Name, IK_Direct,
1177 ConstructorArgs);
1178 if (C) {
1179 // Take over the constructor arguments as our own.
1180 NumArgs = ConstructorArgs.size();
1181 Args = (Expr **)ConstructorArgs.take();
1182 }
Eli Friedman59c04372009-07-29 19:44:27 +00001183 }
1184
Mike Stump1eb44332009-09-09 15:08:12 +00001185 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001186 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001187}
1188
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001189void
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001190Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001191 CXXBaseOrMemberInitializer **Initializers,
1192 unsigned NumInitializers,
Mike Stump1eb44332009-09-09 15:08:12 +00001193 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001194 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
1195 // We need to build the initializer AST according to order of construction
1196 // and not what user specified in the Initializers list.
1197 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1198 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1199 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1200 bool HasDependentBaseInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001202 for (unsigned i = 0; i < NumInitializers; i++) {
1203 CXXBaseOrMemberInitializer *Member = Initializers[i];
1204 if (Member->isBaseInitializer()) {
1205 if (Member->getBaseClass()->isDependentType())
1206 HasDependentBaseInit = true;
1207 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1208 } else {
1209 AllBaseFields[Member->getMember()] = Member;
1210 }
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001213 if (HasDependentBaseInit) {
1214 // FIXME. This does not preserve the ordering of the initializers.
1215 // Try (with -Wreorder)
1216 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001217 // template<class X> struct B : A<X> {
1218 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001219 // int x1;
1220 // };
1221 // B<int> x;
1222 // On seeing one dependent type, we should essentially exit this routine
1223 // while preserving user-declared initializer list. When this routine is
1224 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001225 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001227 // If we have a dependent base initialization, we can't determine the
1228 // association between initializers and bases; just dump the known
1229 // initializers into the list, and don't try to deal with other bases.
1230 for (unsigned i = 0; i < NumInitializers; i++) {
1231 CXXBaseOrMemberInitializer *Member = Initializers[i];
1232 if (Member->isBaseInitializer())
1233 AllToInit.push_back(Member);
1234 }
1235 } else {
1236 // Push virtual bases before others.
1237 for (CXXRecordDecl::base_class_iterator VBase =
1238 ClassDecl->vbases_begin(),
1239 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1240 if (VBase->getType()->isDependentType())
1241 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001242 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001243 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001244 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001245 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001246 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001247 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1248 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001249 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001250 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001251 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001252 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001253 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001254 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001255 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001256 if (!Ctor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001257 Bases.push_back(VBase);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001258 continue;
1259 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001260
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001261 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1262 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1263 Constructor->getLocation(), CtorArgs))
1264 continue;
1265
1266 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1267
Mike Stump1eb44332009-09-09 15:08:12 +00001268 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001269 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1270 CtorArgs.takeAs<Expr>(),
1271 CtorArgs.size(), Ctor,
1272 SourceLocation(),
1273 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001274 AllToInit.push_back(Member);
1275 }
1276 }
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001278 for (CXXRecordDecl::base_class_iterator Base =
1279 ClassDecl->bases_begin(),
1280 E = ClassDecl->bases_end(); Base != E; ++Base) {
1281 // Virtuals are in the virtual base list and already constructed.
1282 if (Base->isVirtual())
1283 continue;
1284 // Skip dependent types.
1285 if (Base->getType()->isDependentType())
1286 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001287 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001288 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001289 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001290 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001291 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001292 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1293 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001294 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001295 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001296 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001297 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001298 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001299 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001300 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001301 if (!Ctor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001302 Bases.push_back(Base);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001303 continue;
1304 }
1305
1306 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1307 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1308 Constructor->getLocation(), CtorArgs))
1309 continue;
1310
1311 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001312
Mike Stump1eb44332009-09-09 15:08:12 +00001313 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001314 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1315 CtorArgs.takeAs<Expr>(),
1316 CtorArgs.size(), Ctor,
1317 SourceLocation(),
1318 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001319 AllToInit.push_back(Member);
1320 }
1321 }
1322 }
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001324 // non-static data members.
1325 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1326 E = ClassDecl->field_end(); Field != E; ++Field) {
1327 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001328 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001329 Field->getType()->getAs<RecordType>()) {
1330 CXXRecordDecl *FieldClassDecl
1331 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001332 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001333 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1334 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1335 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1336 // set to the anonymous union data member used in the initializer
1337 // list.
1338 Value->setMember(*Field);
1339 Value->setAnonUnionMember(*FA);
1340 AllToInit.push_back(Value);
1341 break;
1342 }
1343 }
1344 }
1345 continue;
1346 }
1347 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001348 QualType FT = (*Field)->getType();
1349 if (const RecordType* RT = FT->getAs<RecordType>()) {
1350 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001351 assert(FieldRecDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001352 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001353 FieldRecDecl->getDefaultConstructor(Context))
1354 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1355 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001356 AllToInit.push_back(Value);
1357 continue;
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001360 if ((*Field)->getType()->isDependentType()) {
1361 Fields.push_back(*Field);
1362 continue;
1363 }
1364
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001365 QualType FT = Context.getBaseElementType((*Field)->getType());
1366 if (const RecordType* RT = FT->getAs<RecordType>()) {
1367 CXXConstructorDecl *Ctor =
1368 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001369 if (!Ctor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001370 Fields.push_back(*Field);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001371 continue;
1372 }
1373
1374 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1375 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1376 Constructor->getLocation(), CtorArgs))
1377 continue;
1378
Mike Stump1eb44332009-09-09 15:08:12 +00001379 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001380 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1381 CtorArgs.size(), Ctor,
1382 SourceLocation(),
1383 SourceLocation());
1384
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001385 AllToInit.push_back(Member);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001386 if (Ctor)
1387 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001388 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1389 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1390 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1391 Diag((*Field)->getLocation(), diag::note_declared_at);
1392 }
1393 }
1394 else if (FT->isReferenceType()) {
1395 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1396 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1397 Diag((*Field)->getLocation(), diag::note_declared_at);
1398 }
1399 else if (FT.isConstQualified()) {
1400 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1401 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1402 Diag((*Field)->getLocation(), diag::note_declared_at);
1403 }
1404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001406 NumInitializers = AllToInit.size();
1407 if (NumInitializers > 0) {
1408 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1409 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1410 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001412 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1413 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1414 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1415 }
1416}
1417
1418void
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001419Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1420 CXXConstructorDecl *Constructor,
1421 CXXBaseOrMemberInitializer **Initializers,
1422 unsigned NumInitializers
1423 ) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001424 llvm::SmallVector<CXXBaseSpecifier *, 4> Bases;
1425 llvm::SmallVector<FieldDecl *, 4> Members;
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001427 SetBaseOrMemberInitializers(Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001428 Initializers, NumInitializers, Bases, Members);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001429 for (unsigned int i = 0; i < Bases.size(); i++) {
1430 if (!Bases[i]->getType()->isDependentType())
1431 Diag(Bases[i]->getSourceRange().getBegin(),
1432 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1433 }
1434 for (unsigned int i = 0; i < Members.size(); i++) {
1435 if (!Members[i]->getType()->isDependentType())
1436 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
1437 << 1 << Members[i]->getType();
1438 }
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001439}
1440
Eli Friedman6347f422009-07-21 19:28:10 +00001441static void *GetKeyForTopLevelField(FieldDecl *Field) {
1442 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001443 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001444 if (RT->getDecl()->isAnonymousStructOrUnion())
1445 return static_cast<void *>(RT->getDecl());
1446 }
1447 return static_cast<void *>(Field);
1448}
1449
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001450static void *GetKeyForBase(QualType BaseType) {
1451 if (const RecordType *RT = BaseType->getAs<RecordType>())
1452 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001454 assert(0 && "Unexpected base type!");
1455 return 0;
1456}
1457
Mike Stump1eb44332009-09-09 15:08:12 +00001458static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001459 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001460 // For fields injected into the class via declaration of an anonymous union,
1461 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001462 if (Member->isMemberInitializer()) {
1463 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001465 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001466 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001467 // in AnonUnionMember field.
1468 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1469 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001470 if (Field->getDeclContext()->isRecord()) {
1471 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1472 if (RD->isAnonymousStructOrUnion())
1473 return static_cast<void *>(RD);
1474 }
1475 return static_cast<void *>(Field);
1476 }
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001478 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001479}
1480
John McCall6aee6212009-11-04 23:13:52 +00001481/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001482void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001483 SourceLocation ColonLoc,
1484 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001485 if (!ConstructorDecl)
1486 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001487
1488 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001489
1490 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001491 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Anders Carlssona7b35212009-03-25 02:58:17 +00001493 if (!Constructor) {
1494 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1495 return;
1496 }
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001498 if (!Constructor->isDependentContext()) {
1499 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1500 bool err = false;
1501 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001502 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001503 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1504 void *KeyToMember = GetKeyForMember(Member);
1505 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1506 if (!PrevMember) {
1507 PrevMember = Member;
1508 continue;
1509 }
1510 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001511 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001512 diag::error_multiple_mem_initialization)
1513 << Field->getNameAsString();
1514 else {
1515 Type *BaseClass = Member->getBaseClass();
1516 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001517 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001518 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001519 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001520 }
1521 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1522 << 0;
1523 err = true;
1524 }
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001526 if (err)
1527 return;
1528 }
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001530 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001531 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001532 NumMemInits);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001534 if (Constructor->isDependentContext())
1535 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001536
1537 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001538 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001539 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001540 Diagnostic::Ignored)
1541 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001543 // Also issue warning if order of ctor-initializer list does not match order
1544 // of 1) base class declarations and 2) order of non-static data members.
1545 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001547 CXXRecordDecl *ClassDecl
1548 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1549 // Push virtual bases before others.
1550 for (CXXRecordDecl::base_class_iterator VBase =
1551 ClassDecl->vbases_begin(),
1552 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001553 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001555 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1556 E = ClassDecl->bases_end(); Base != E; ++Base) {
1557 // Virtuals are alread in the virtual base list and are constructed
1558 // first.
1559 if (Base->isVirtual())
1560 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001561 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001564 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1565 E = ClassDecl->field_end(); Field != E; ++Field)
1566 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001568 int Last = AllBaseOrMembers.size();
1569 int curIndex = 0;
1570 CXXBaseOrMemberInitializer *PrevMember = 0;
1571 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001572 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001573 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1574 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001575
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001576 for (; curIndex < Last; curIndex++)
1577 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1578 break;
1579 if (curIndex == Last) {
1580 assert(PrevMember && "Member not in member list?!");
1581 // Initializer as specified in ctor-initializer list is out of order.
1582 // Issue a warning diagnostic.
1583 if (PrevMember->isBaseInitializer()) {
1584 // Diagnostics is for an initialized base class.
1585 Type *BaseClass = PrevMember->getBaseClass();
1586 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001587 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001588 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001589 } else {
1590 FieldDecl *Field = PrevMember->getMember();
1591 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001592 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001593 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001594 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001595 // Also the note!
1596 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001597 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001598 diag::note_fieldorbase_initialized_here) << 0
1599 << Field->getNameAsString();
1600 else {
1601 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001602 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001603 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001604 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001605 }
1606 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001607 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001608 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001609 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001610 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001611 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001612}
1613
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001614void
1615Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1616 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1617 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001619 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1620 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1621 if (VBase->getType()->isDependentType())
1622 continue;
1623 // Skip over virtual bases which have trivial destructors.
1624 CXXRecordDecl *BaseClassDecl
1625 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1626 if (BaseClassDecl->hasTrivialDestructor())
1627 continue;
1628 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001629 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001630 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001631
1632 uintptr_t Member =
1633 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001634 | CXXDestructorDecl::VBASE;
1635 AllToDestruct.push_back(Member);
1636 }
1637 for (CXXRecordDecl::base_class_iterator Base =
1638 ClassDecl->bases_begin(),
1639 E = ClassDecl->bases_end(); Base != E; ++Base) {
1640 if (Base->isVirtual())
1641 continue;
1642 if (Base->getType()->isDependentType())
1643 continue;
1644 // Skip over virtual bases which have trivial destructors.
1645 CXXRecordDecl *BaseClassDecl
1646 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1647 if (BaseClassDecl->hasTrivialDestructor())
1648 continue;
1649 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001650 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001651 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001652 uintptr_t Member =
1653 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001654 | CXXDestructorDecl::DRCTNONVBASE;
1655 AllToDestruct.push_back(Member);
1656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001658 // non-static data members.
1659 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1660 E = ClassDecl->field_end(); Field != E; ++Field) {
1661 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001663 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1664 // Skip over virtual bases which have trivial destructors.
1665 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1666 if (FieldClassDecl->hasTrivialDestructor())
1667 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001668 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001669 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001670 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001671 const_cast<CXXDestructorDecl*>(Dtor));
1672 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1673 AllToDestruct.push_back(Member);
1674 }
1675 }
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001677 unsigned NumDestructions = AllToDestruct.size();
1678 if (NumDestructions > 0) {
1679 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001680 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001681 new (Context) uintptr_t [NumDestructions];
1682 // Insert in reverse order.
1683 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1684 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1685 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1686 }
1687}
1688
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001689void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001690 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001691 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001693 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001694
1695 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001696 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001697 BuildBaseOrMemberInitializers(Context,
1698 Constructor,
1699 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001700}
1701
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001702namespace {
1703 /// PureVirtualMethodCollector - traverses a class and its superclasses
1704 /// and determines if it has any pure virtual methods.
1705 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1706 ASTContext &Context;
1707
Sebastian Redldfe292d2009-03-22 21:28:55 +00001708 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001709 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001710
1711 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001712 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001714 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001716 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001717 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001718 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001720 MethodList List;
1721 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001723 // Copy the temporary list to methods, and make sure to ignore any
1724 // null entries.
1725 for (size_t i = 0, e = List.size(); i != e; ++i) {
1726 if (List[i])
1727 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001728 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001731 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001733 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1734 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001735 };
Mike Stump1eb44332009-09-09 15:08:12 +00001736
1737 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001738 MethodList& Methods) {
1739 // First, collect the pure virtual methods for the base classes.
1740 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1741 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001742 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001743 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001744 if (BaseDecl && BaseDecl->isAbstract())
1745 Collect(BaseDecl, Methods);
1746 }
1747 }
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001749 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001750 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001752 MethodSetTy OverriddenMethods;
1753 size_t MethodsSize = Methods.size();
1754
Mike Stump1eb44332009-09-09 15:08:12 +00001755 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001756 i != e; ++i) {
1757 // Traverse the record, looking for methods.
1758 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001759 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001760 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001761 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Anders Carlsson27823022009-10-18 19:34:08 +00001763 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001764 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1765 E = MD->end_overridden_methods(); I != E; ++I) {
1766 // Keep track of the overridden methods.
1767 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001768 }
1769 }
1770 }
Mike Stump1eb44332009-09-09 15:08:12 +00001771
1772 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001773 // overridden.
1774 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1775 if (OverriddenMethods.count(Methods[i]))
1776 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001777 }
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001779 }
1780}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001781
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001782
Mike Stump1eb44332009-09-09 15:08:12 +00001783bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001784 unsigned DiagID, AbstractDiagSelID SelID,
1785 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001786 if (SelID == -1)
1787 return RequireNonAbstractType(Loc, T,
1788 PDiag(DiagID), CurrentRD);
1789 else
1790 return RequireNonAbstractType(Loc, T,
1791 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001792}
1793
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001794bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1795 const PartialDiagnostic &PD,
1796 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001797 if (!getLangOptions().CPlusPlus)
1798 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Anders Carlsson11f21a02009-03-23 19:10:31 +00001800 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001801 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001802 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Ted Kremenek6217b802009-07-29 21:53:49 +00001804 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001805 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001806 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001807 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001809 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001810 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001811 }
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Ted Kremenek6217b802009-07-29 21:53:49 +00001813 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001814 if (!RT)
1815 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001817 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1818 if (!RD)
1819 return false;
1820
Anders Carlssone65a3c82009-03-24 17:23:42 +00001821 if (CurrentRD && CurrentRD != RD)
1822 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001824 if (!RD->isAbstract())
1825 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001827 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001829 // Check if we've already emitted the list of pure virtual functions for this
1830 // class.
1831 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1832 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001834 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
1836 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001837 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1838 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001839
1840 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001841 MD->getDeclName();
1842 }
1843
1844 if (!PureVirtualClassDiagSet)
1845 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1846 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001848 return true;
1849}
1850
Anders Carlsson8211eff2009-03-24 01:19:16 +00001851namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001852 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001853 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1854 Sema &SemaRef;
1855 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Anders Carlssone65a3c82009-03-24 17:23:42 +00001857 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001858 bool Invalid = false;
1859
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001860 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1861 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001862 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001863
Anders Carlsson8211eff2009-03-24 01:19:16 +00001864 return Invalid;
1865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Anders Carlssone65a3c82009-03-24 17:23:42 +00001867 public:
1868 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1869 : SemaRef(SemaRef), AbstractClass(ac) {
1870 Visit(SemaRef.Context.getTranslationUnitDecl());
1871 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001872
Anders Carlssone65a3c82009-03-24 17:23:42 +00001873 bool VisitFunctionDecl(const FunctionDecl *FD) {
1874 if (FD->isThisDeclarationADefinition()) {
1875 // No need to do the check if we're in a definition, because it requires
1876 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001877 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001878 return VisitDeclContext(FD);
1879 }
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Anders Carlssone65a3c82009-03-24 17:23:42 +00001881 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001882 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001883 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001884 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1885 diag::err_abstract_type_in_decl,
1886 Sema::AbstractReturnType,
1887 AbstractClass);
1888
Mike Stump1eb44332009-09-09 15:08:12 +00001889 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001890 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001891 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001892 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001893 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001894 VD->getOriginalType(),
1895 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001896 Sema::AbstractParamType,
1897 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001898 }
1899
1900 return Invalid;
1901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Anders Carlssone65a3c82009-03-24 17:23:42 +00001903 bool VisitDecl(const Decl* D) {
1904 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1905 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlssone65a3c82009-03-24 17:23:42 +00001907 return false;
1908 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001909 };
1910}
1911
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001912void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001913 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001914 SourceLocation LBrac,
1915 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001916 if (!TagDecl)
1917 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Douglas Gregor42af25f2009-05-11 19:58:34 +00001919 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001920 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001921 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001922 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001923
Chris Lattnerb28317a2009-03-28 19:18:32 +00001924 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001925 if (!RD->isAbstract()) {
1926 // Collect all the pure virtual methods and see if this is an abstract
1927 // class after all.
1928 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001929 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001930 RD->setAbstract(true);
1931 }
Mike Stump1eb44332009-09-09 15:08:12 +00001932
1933 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001934 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Douglas Gregor663b5a02009-10-14 20:14:33 +00001936 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001937 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001938}
1939
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001940/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1941/// special functions, such as the default constructor, copy
1942/// constructor, or destructor, to the given C++ class (C++
1943/// [special]p1). This routine can only be executed just before the
1944/// definition of the class is complete.
1945void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001946 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001947 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001948
Sebastian Redl465226e2009-05-27 22:11:52 +00001949 // FIXME: Implicit declarations have exception specifications, which are
1950 // the union of the specifications of the implicitly called functions.
1951
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001952 if (!ClassDecl->hasUserDeclaredConstructor()) {
1953 // C++ [class.ctor]p5:
1954 // A default constructor for a class X is a constructor of class X
1955 // that can be called without an argument. If there is no
1956 // user-declared constructor for class X, a default constructor is
1957 // implicitly declared. An implicitly-declared default constructor
1958 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001959 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001960 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001961 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001962 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001963 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001964 Context.getFunctionType(Context.VoidTy,
1965 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001966 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001967 /*isExplicit=*/false,
1968 /*isInline=*/true,
1969 /*isImplicitlyDeclared=*/true);
1970 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001971 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001972 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001973 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001974 }
1975
1976 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1977 // C++ [class.copy]p4:
1978 // If the class definition does not explicitly declare a copy
1979 // constructor, one is declared implicitly.
1980
1981 // C++ [class.copy]p5:
1982 // The implicitly-declared copy constructor for a class X will
1983 // have the form
1984 //
1985 // X::X(const X&)
1986 //
1987 // if
1988 bool HasConstCopyConstructor = true;
1989
1990 // -- each direct or virtual base class B of X has a copy
1991 // constructor whose first parameter is of type const B& or
1992 // const volatile B&, and
1993 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1994 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1995 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001996 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001997 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001998 = BaseClassDecl->hasConstCopyConstructor(Context);
1999 }
2000
2001 // -- for all the nonstatic data members of X that are of a
2002 // class type M (or array thereof), each such class type
2003 // has a copy constructor whose first parameter is of type
2004 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002005 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2006 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002007 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002008 QualType FieldType = (*Field)->getType();
2009 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2010 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002011 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002012 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002013 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002014 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002015 = FieldClassDecl->hasConstCopyConstructor(Context);
2016 }
2017 }
2018
Sebastian Redl64b45f72009-01-05 20:52:13 +00002019 // Otherwise, the implicitly declared copy constructor will have
2020 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002021 //
2022 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002023 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002024 if (HasConstCopyConstructor)
2025 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002026 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002027
Sebastian Redl64b45f72009-01-05 20:52:13 +00002028 // An implicitly-declared copy constructor is an inline public
2029 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002030 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002031 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002032 CXXConstructorDecl *CopyConstructor
2033 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002034 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002035 Context.getFunctionType(Context.VoidTy,
2036 &ArgType, 1,
2037 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002038 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002039 /*isExplicit=*/false,
2040 /*isInline=*/true,
2041 /*isImplicitlyDeclared=*/true);
2042 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002043 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002044 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002045
2046 // Add the parameter to the constructor.
2047 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2048 ClassDecl->getLocation(),
2049 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002050 ArgType, /*DInfo=*/0,
2051 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002052 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002053 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002054 }
2055
Sebastian Redl64b45f72009-01-05 20:52:13 +00002056 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2057 // Note: The following rules are largely analoguous to the copy
2058 // constructor rules. Note that virtual bases are not taken into account
2059 // for determining the argument type of the operator. Note also that
2060 // operators taking an object instead of a reference are allowed.
2061 //
2062 // C++ [class.copy]p10:
2063 // If the class definition does not explicitly declare a copy
2064 // assignment operator, one is declared implicitly.
2065 // The implicitly-defined copy assignment operator for a class X
2066 // will have the form
2067 //
2068 // X& X::operator=(const X&)
2069 //
2070 // if
2071 bool HasConstCopyAssignment = true;
2072
2073 // -- each direct base class B of X has a copy assignment operator
2074 // whose parameter is of type const B&, const volatile B& or B,
2075 // and
2076 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2077 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002078 assert(!Base->getType()->isDependentType() &&
2079 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002080 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002081 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002082 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002083 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002084 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002085 }
2086
2087 // -- for all the nonstatic data members of X that are of a class
2088 // type M (or array thereof), each such class type has a copy
2089 // assignment operator whose parameter is of type const M&,
2090 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002091 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2092 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002093 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002094 QualType FieldType = (*Field)->getType();
2095 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2096 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002097 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002098 const CXXRecordDecl *FieldClassDecl
2099 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002100 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002101 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002102 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002103 }
2104 }
2105
2106 // Otherwise, the implicitly declared copy assignment operator will
2107 // have the form
2108 //
2109 // X& X::operator=(X&)
2110 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002111 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002112 if (HasConstCopyAssignment)
2113 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002114 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002115
2116 // An implicitly-declared copy assignment operator is an inline public
2117 // member of its class.
2118 DeclarationName Name =
2119 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2120 CXXMethodDecl *CopyAssignment =
2121 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2122 Context.getFunctionType(RetType, &ArgType, 1,
2123 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002124 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002125 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002126 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002127 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002128 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002129
2130 // Add the parameter to the operator.
2131 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2132 ClassDecl->getLocation(),
2133 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002134 ArgType, /*DInfo=*/0,
2135 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002136 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002137
2138 // Don't call addedAssignmentOperator. There is no way to distinguish an
2139 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002140 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002141 }
2142
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002143 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002144 // C++ [class.dtor]p2:
2145 // If a class has no user-declared destructor, a destructor is
2146 // declared implicitly. An implicitly-declared destructor is an
2147 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002148 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002149 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002150 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002151 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002152 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002153 Context.getFunctionType(Context.VoidTy,
2154 0, 0, false, 0),
2155 /*isInline=*/true,
2156 /*isImplicitlyDeclared=*/true);
2157 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002158 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002159 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002160 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002161 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002162}
2163
Douglas Gregor6569d682009-05-27 23:11:45 +00002164void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002165 Decl *D = TemplateD.getAs<Decl>();
2166 if (!D)
2167 return;
2168
2169 TemplateParameterList *Params = 0;
2170 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2171 Params = Template->getTemplateParameters();
2172 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2173 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2174 Params = PartialSpec->getTemplateParameters();
2175 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002176 return;
2177
Douglas Gregor6569d682009-05-27 23:11:45 +00002178 for (TemplateParameterList::iterator Param = Params->begin(),
2179 ParamEnd = Params->end();
2180 Param != ParamEnd; ++Param) {
2181 NamedDecl *Named = cast<NamedDecl>(*Param);
2182 if (Named->getDeclName()) {
2183 S->AddDecl(DeclPtrTy::make(Named));
2184 IdResolver.AddDecl(Named);
2185 }
2186 }
2187}
2188
Douglas Gregor72b505b2008-12-16 21:30:33 +00002189/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2190/// parsing a top-level (non-nested) C++ class, and we are now
2191/// parsing those parts of the given Method declaration that could
2192/// not be parsed earlier (C++ [class.mem]p2), such as default
2193/// arguments. This action should enter the scope of the given
2194/// Method declaration as if we had just parsed the qualified method
2195/// name. However, it should not bring the parameters into scope;
2196/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002197void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002198 if (!MethodD)
2199 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002201 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Douglas Gregor72b505b2008-12-16 21:30:33 +00002203 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002204 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002205 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002206 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2207 SS.setScopeRep(
2208 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002209 ActOnCXXEnterDeclaratorScope(S, SS);
2210}
2211
2212/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2213/// C++ method declaration. We're (re-)introducing the given
2214/// function parameter into scope for use in parsing later parts of
2215/// the method declaration. For example, we could see an
2216/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002217void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002218 if (!ParamD)
2219 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Chris Lattnerb28317a2009-03-28 19:18:32 +00002221 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002222
2223 // If this parameter has an unparsed default argument, clear it out
2224 // to make way for the parsed default argument.
2225 if (Param->hasUnparsedDefaultArg())
2226 Param->setDefaultArg(0);
2227
Chris Lattnerb28317a2009-03-28 19:18:32 +00002228 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002229 if (Param->getDeclName())
2230 IdResolver.AddDecl(Param);
2231}
2232
2233/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2234/// processing the delayed method declaration for Method. The method
2235/// declaration is now considered finished. There may be a separate
2236/// ActOnStartOfFunctionDef action later (not necessarily
2237/// immediately!) for this method, if it was also defined inside the
2238/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002239void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002240 if (!MethodD)
2241 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002243 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Chris Lattnerb28317a2009-03-28 19:18:32 +00002245 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002246 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002247 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002248 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2249 SS.setScopeRep(
2250 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002251 ActOnCXXExitDeclaratorScope(S, SS);
2252
2253 // Now that we have our default arguments, check the constructor
2254 // again. It could produce additional diagnostics or affect whether
2255 // the class has implicitly-declared destructors, among other
2256 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002257 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2258 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002259
2260 // Check the default arguments, which we may have added.
2261 if (!Method->isInvalidDecl())
2262 CheckCXXDefaultArguments(Method);
2263}
2264
Douglas Gregor42a552f2008-11-05 20:51:48 +00002265/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002266/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002267/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002268/// emit diagnostics and set the invalid bit to true. In any case, the type
2269/// will be updated to reflect a well-formed type for the constructor and
2270/// returned.
2271QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2272 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002273 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002274
2275 // C++ [class.ctor]p3:
2276 // A constructor shall not be virtual (10.3) or static (9.4). A
2277 // constructor can be invoked for a const, volatile or const
2278 // volatile object. A constructor shall not be declared const,
2279 // volatile, or const volatile (9.3.2).
2280 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002281 if (!D.isInvalidType())
2282 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2283 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2284 << SourceRange(D.getIdentifierLoc());
2285 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002286 }
2287 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002288 if (!D.isInvalidType())
2289 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2290 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2291 << SourceRange(D.getIdentifierLoc());
2292 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002293 SC = FunctionDecl::None;
2294 }
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Chris Lattner65401802009-04-25 08:28:21 +00002296 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2297 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002298 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002299 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2300 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002301 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002302 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2303 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002304 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002305 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2306 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregor42a552f2008-11-05 20:51:48 +00002309 // Rebuild the function type "R" without any type qualifiers (in
2310 // case any of the errors above fired) and with "void" as the
2311 // return type, since constructors don't have return types. We
2312 // *always* have to do this, because GetTypeForDeclarator will
2313 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002314 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002315 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2316 Proto->getNumArgs(),
2317 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002318}
2319
Douglas Gregor72b505b2008-12-16 21:30:33 +00002320/// CheckConstructor - Checks a fully-formed constructor for
2321/// well-formedness, issuing any diagnostics required. Returns true if
2322/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002323void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002324 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002325 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2326 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002327 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002328
2329 // C++ [class.copy]p3:
2330 // A declaration of a constructor for a class X is ill-formed if
2331 // its first parameter is of type (optionally cv-qualified) X and
2332 // either there are no other parameters or else all other
2333 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002334 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002335 ((Constructor->getNumParams() == 1) ||
2336 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002337 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002338 QualType ParamType = Constructor->getParamDecl(0)->getType();
2339 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2340 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002341 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2342 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002343 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002344 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002345 }
2346 }
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor72b505b2008-12-16 21:30:33 +00002348 // Notify the class that we've added a constructor.
2349 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002350}
2351
Mike Stump1eb44332009-09-09 15:08:12 +00002352static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002353FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2354 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2355 FTI.ArgInfo[0].Param &&
2356 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2357}
2358
Douglas Gregor42a552f2008-11-05 20:51:48 +00002359/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2360/// the well-formednes of the destructor declarator @p D with type @p
2361/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002362/// emit diagnostics and set the declarator to invalid. Even if this happens,
2363/// will be updated to reflect a well-formed type for the destructor and
2364/// returned.
2365QualType Sema::CheckDestructorDeclarator(Declarator &D,
2366 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002367 // C++ [class.dtor]p1:
2368 // [...] A typedef-name that names a class is a class-name
2369 // (7.1.3); however, a typedef-name that names a class shall not
2370 // be used as the identifier in the declarator for a destructor
2371 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002372 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002373 if (isa<TypedefType>(DeclaratorType)) {
2374 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002375 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002376 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002377 }
2378
2379 // C++ [class.dtor]p2:
2380 // A destructor is used to destroy objects of its class type. A
2381 // destructor takes no parameters, and no return type can be
2382 // specified for it (not even void). The address of a destructor
2383 // shall not be taken. A destructor shall not be static. A
2384 // destructor can be invoked for a const, volatile or const
2385 // volatile object. A destructor shall not be declared const,
2386 // volatile or const volatile (9.3.2).
2387 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002388 if (!D.isInvalidType())
2389 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2390 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2391 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002392 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002393 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002394 }
Chris Lattner65401802009-04-25 08:28:21 +00002395 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002396 // Destructors don't have return types, but the parser will
2397 // happily parse something like:
2398 //
2399 // class X {
2400 // float ~X();
2401 // };
2402 //
2403 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002404 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2405 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2406 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002407 }
Mike Stump1eb44332009-09-09 15:08:12 +00002408
Chris Lattner65401802009-04-25 08:28:21 +00002409 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2410 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002411 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002412 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2413 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002414 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002415 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2416 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002417 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002418 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2419 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002420 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002421 }
2422
2423 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002424 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002425 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2426
2427 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002428 FTI.freeArgs();
2429 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002430 }
2431
Mike Stump1eb44332009-09-09 15:08:12 +00002432 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002433 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002434 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002435 D.setInvalidType();
2436 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002437
2438 // Rebuild the function type "R" without any type qualifiers or
2439 // parameters (in case any of the errors above fired) and with
2440 // "void" as the return type, since destructors don't have return
2441 // types. We *always* have to do this, because GetTypeForDeclarator
2442 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002443 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002444}
2445
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002446/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2447/// well-formednes of the conversion function declarator @p D with
2448/// type @p R. If there are any errors in the declarator, this routine
2449/// will emit diagnostics and return true. Otherwise, it will return
2450/// false. Either way, the type @p R will be updated to reflect a
2451/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002452void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002453 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002454 // C++ [class.conv.fct]p1:
2455 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002456 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002457 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002458 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002459 if (!D.isInvalidType())
2460 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2461 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2462 << SourceRange(D.getIdentifierLoc());
2463 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002464 SC = FunctionDecl::None;
2465 }
Chris Lattner6e475012009-04-25 08:35:12 +00002466 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002467 // Conversion functions don't have return types, but the parser will
2468 // happily parse something like:
2469 //
2470 // class X {
2471 // float operator bool();
2472 // };
2473 //
2474 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002475 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2476 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2477 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002478 }
2479
2480 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002481 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002482 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2483
2484 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002485 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002486 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002487 }
2488
Mike Stump1eb44332009-09-09 15:08:12 +00002489 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002490 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002491 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002492 D.setInvalidType();
2493 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002494
2495 // C++ [class.conv.fct]p4:
2496 // The conversion-type-id shall not represent a function type nor
2497 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002498 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002499 if (ConvType->isArrayType()) {
2500 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2501 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002502 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002503 } else if (ConvType->isFunctionType()) {
2504 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2505 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002506 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002507 }
2508
2509 // Rebuild the function type "R" without any parameters (in case any
2510 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002511 // return type.
2512 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002513 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002514
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002515 // C++0x explicit conversion operators.
2516 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002517 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002518 diag::warn_explicit_conversion_functions)
2519 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002520}
2521
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002522/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2523/// the declaration of the given C++ conversion function. This routine
2524/// is responsible for recording the conversion function in the C++
2525/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002526Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002527 assert(Conversion && "Expected to receive a conversion function declaration");
2528
Douglas Gregor9d350972008-12-12 08:25:50 +00002529 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002530
2531 // Make sure we aren't redeclaring the conversion function.
2532 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002533
2534 // C++ [class.conv.fct]p1:
2535 // [...] A conversion function is never used to convert a
2536 // (possibly cv-qualified) object to the (possibly cv-qualified)
2537 // same object type (or a reference to it), to a (possibly
2538 // cv-qualified) base class of that type (or a reference to it),
2539 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002540 // FIXME: Suppress this warning if the conversion function ends up being a
2541 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002542 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002543 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002544 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002545 ConvType = ConvTypeRef->getPointeeType();
2546 if (ConvType->isRecordType()) {
2547 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2548 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002549 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002550 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002551 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002552 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002553 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002554 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002555 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002556 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002557 }
2558
Douglas Gregor70316a02008-12-26 15:00:45 +00002559 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002560 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002561 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002562 = Conversion->getDescribedFunctionTemplate())
2563 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002564 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002565 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002566 Conv = Conversions->function_begin(),
2567 ConvEnd = Conversions->function_end();
2568 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002569 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002570 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002571 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002572 }
2573 }
2574 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002575 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002576 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002577 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002578 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002579 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002580
Chris Lattnerb28317a2009-03-28 19:18:32 +00002581 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002582}
2583
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002584//===----------------------------------------------------------------------===//
2585// Namespace Handling
2586//===----------------------------------------------------------------------===//
2587
2588/// ActOnStartNamespaceDef - This is called at the start of a namespace
2589/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002590Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2591 SourceLocation IdentLoc,
2592 IdentifierInfo *II,
2593 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002594 NamespaceDecl *Namespc =
2595 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2596 Namespc->setLBracLoc(LBrace);
2597
2598 Scope *DeclRegionScope = NamespcScope->getParent();
2599
2600 if (II) {
2601 // C++ [namespace.def]p2:
2602 // The identifier in an original-namespace-definition shall not have been
2603 // previously defined in the declarative region in which the
2604 // original-namespace-definition appears. The identifier in an
2605 // original-namespace-definition is the name of the namespace. Subsequently
2606 // in that declarative region, it is treated as an original-namespace-name.
2607
John McCallf36e02d2009-10-09 21:13:30 +00002608 NamedDecl *PrevDecl
2609 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Douglas Gregor44b43212008-12-11 16:49:14 +00002611 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2612 // This is an extended namespace definition.
2613 // Attach this namespace decl to the chain of extended namespace
2614 // definitions.
2615 OrigNS->setNextNamespace(Namespc);
2616 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002617
Mike Stump1eb44332009-09-09 15:08:12 +00002618 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002619 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002620 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002621 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002622 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002623 } else if (PrevDecl) {
2624 // This is an invalid name redefinition.
2625 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2626 << Namespc->getDeclName();
2627 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2628 Namespc->setInvalidDecl();
2629 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002630 } else if (II->isStr("std") &&
2631 CurContext->getLookupContext()->isTranslationUnit()) {
2632 // This is the first "real" definition of the namespace "std", so update
2633 // our cache of the "std" namespace to point at this definition.
2634 if (StdNamespace) {
2635 // We had already defined a dummy namespace "std". Link this new
2636 // namespace definition to the dummy namespace "std".
2637 StdNamespace->setNextNamespace(Namespc);
2638 StdNamespace->setLocation(IdentLoc);
2639 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2640 }
2641
2642 // Make our StdNamespace cache point at the first real definition of the
2643 // "std" namespace.
2644 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002645 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002646
2647 PushOnScopeChains(Namespc, DeclRegionScope);
2648 } else {
John McCall9aeed322009-10-01 00:25:31 +00002649 // Anonymous namespaces.
2650
2651 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2652 // behaves as if it were replaced by
2653 // namespace unique { /* empty body */ }
2654 // using namespace unique;
2655 // namespace unique { namespace-body }
2656 // where all occurrences of 'unique' in a translation unit are
2657 // replaced by the same identifier and this identifier differs
2658 // from all other identifiers in the entire program.
2659
2660 // We just create the namespace with an empty name and then add an
2661 // implicit using declaration, just like the standard suggests.
2662 //
2663 // CodeGen enforces the "universally unique" aspect by giving all
2664 // declarations semantically contained within an anonymous
2665 // namespace internal linkage.
2666
2667 assert(Namespc->isAnonymousNamespace());
2668 CurContext->addDecl(Namespc);
2669
2670 UsingDirectiveDecl* UD
2671 = UsingDirectiveDecl::Create(Context, CurContext,
2672 /* 'using' */ LBrace,
2673 /* 'namespace' */ SourceLocation(),
2674 /* qualifier */ SourceRange(),
2675 /* NNS */ NULL,
2676 /* identifier */ SourceLocation(),
2677 Namespc,
2678 /* Ancestor */ CurContext);
2679 UD->setImplicit();
2680 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002681 }
2682
2683 // Although we could have an invalid decl (i.e. the namespace name is a
2684 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002685 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2686 // for the namespace has the declarations that showed up in that particular
2687 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002688 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002689 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002690}
2691
2692/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2693/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002694void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2695 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002696 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2697 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2698 Namespc->setRBracLoc(RBrace);
2699 PopDeclContext();
2700}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002701
Chris Lattnerb28317a2009-03-28 19:18:32 +00002702Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2703 SourceLocation UsingLoc,
2704 SourceLocation NamespcLoc,
2705 const CXXScopeSpec &SS,
2706 SourceLocation IdentLoc,
2707 IdentifierInfo *NamespcName,
2708 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002709 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2710 assert(NamespcName && "Invalid NamespcName.");
2711 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002712 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002713
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002714 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002715
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002716 // Lookup namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002717 LookupResult R;
2718 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002719 if (R.isAmbiguous()) {
2720 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002721 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002722 }
John McCallf36e02d2009-10-09 21:13:30 +00002723 if (!R.empty()) {
2724 NamedDecl *NS = R.getFoundDecl();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002725 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002726 // C++ [namespace.udir]p1:
2727 // A using-directive specifies that the names in the nominated
2728 // namespace can be used in the scope in which the
2729 // using-directive appears after the using-directive. During
2730 // unqualified name lookup (3.4.1), the names appear as if they
2731 // were declared in the nearest enclosing namespace which
2732 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002733 // namespace. [Note: in this context, "contains" means "contains
2734 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002735
2736 // Find enclosing context containing both using-directive and
2737 // nominated namespace.
2738 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2739 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2740 CommonAncestor = CommonAncestor->getParent();
2741
Mike Stump1eb44332009-09-09 15:08:12 +00002742 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002743 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002744 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002745 SS.getRange(),
2746 (NestedNameSpecifier *)SS.getScopeRep(),
2747 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002748 cast<NamespaceDecl>(NS),
2749 CommonAncestor);
2750 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002751 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002752 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002753 }
2754
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002755 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002756 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002757 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002758}
2759
2760void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2761 // If scope has associated entity, then using directive is at namespace
2762 // or translation unit scope. We add UsingDirectiveDecls, into
2763 // it's lookup structure.
2764 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002765 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002766 else
2767 // Otherwise it is block-sope. using-directives will affect lookup
2768 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002769 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002770}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002771
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002772
2773Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002774 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002775 SourceLocation UsingLoc,
2776 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002777 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002778 AttributeList *AttrList,
2779 bool IsTypeName) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002780 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Douglas Gregor12c118a2009-11-04 16:30:06 +00002782 switch (Name.getKind()) {
2783 case UnqualifiedId::IK_Identifier:
2784 case UnqualifiedId::IK_OperatorFunctionId:
2785 case UnqualifiedId::IK_ConversionFunctionId:
2786 break;
2787
2788 case UnqualifiedId::IK_ConstructorName:
2789 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2790 << SS.getRange();
2791 return DeclPtrTy();
2792
2793 case UnqualifiedId::IK_DestructorName:
2794 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2795 << SS.getRange();
2796 return DeclPtrTy();
2797
2798 case UnqualifiedId::IK_TemplateId:
2799 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2800 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2801 return DeclPtrTy();
2802 }
2803
2804 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2805 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2806 Name.getSourceRange().getBegin(),
2807 TargetName, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002808 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002809 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002810 UD->setAccess(AS);
2811 }
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Anders Carlssonc72160b2009-08-28 05:40:36 +00002813 return DeclPtrTy::make(UD);
2814}
2815
2816NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2817 const CXXScopeSpec &SS,
2818 SourceLocation IdentLoc,
2819 DeclarationName Name,
2820 AttributeList *AttrList,
2821 bool IsTypeName) {
2822 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2823 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002824
Anders Carlsson550b14b2009-08-28 05:49:21 +00002825 // FIXME: We ignore attributes for now.
2826 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002828 if (SS.isEmpty()) {
2829 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002830 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002831 }
Mike Stump1eb44332009-09-09 15:08:12 +00002832
2833 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002834 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2835
Anders Carlsson550b14b2009-08-28 05:49:21 +00002836 if (isUnknownSpecialization(SS)) {
2837 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2838 SS.getRange(), NNS,
2839 IdentLoc, Name, IsTypeName);
2840 }
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002842 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002844 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2845 // C++0x N2914 [namespace.udecl]p3:
2846 // A using-declaration used as a member-declaration shall refer to a member
2847 // of a base class of the class being defined, shall refer to a member of an
2848 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002849 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002850 // a member of a base class of the class being defined.
2851 const Type *Ty = NNS->getAsType();
2852 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2853 Diag(SS.getRange().getBegin(),
2854 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2855 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002856 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002857 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002858
2859 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2860 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002861 } else {
2862 // C++0x N2914 [namespace.udecl]p8:
2863 // A using-declaration for a class member shall be a member-declaration.
2864 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002865 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002866 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002867 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002868 }
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002870 // C++0x N2914 [namespace.udecl]p9:
2871 // In a using-declaration, a prefix :: refers to the global namespace.
2872 if (NNS->getKind() == NestedNameSpecifier::Global)
2873 LookupContext = Context.getTranslationUnitDecl();
2874 else
2875 LookupContext = NNS->getAsNamespace();
2876 }
2877
2878
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002879 // Lookup target name.
John McCallf36e02d2009-10-09 21:13:30 +00002880 LookupResult R;
2881 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002882
John McCallf36e02d2009-10-09 21:13:30 +00002883 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002884 Diag(IdentLoc, diag::err_no_member)
2885 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002886 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002887 }
2888
John McCallf36e02d2009-10-09 21:13:30 +00002889 // FIXME: handle ambiguity?
2890 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002891
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002892 if (IsTypeName && !isa<TypeDecl>(ND)) {
2893 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002894 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002895 }
2896
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002897 // C++0x N2914 [namespace.udecl]p6:
2898 // A using-declaration shall not name a namespace.
2899 if (isa<NamespaceDecl>(ND)) {
2900 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2901 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002902 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002903 }
Mike Stump1eb44332009-09-09 15:08:12 +00002904
Anders Carlssonc72160b2009-08-28 05:40:36 +00002905 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2906 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002907}
2908
Anders Carlsson81c85c42009-03-28 23:53:49 +00002909/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2910/// is a namespace alias, returns the namespace it points to.
2911static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2912 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2913 return AD->getNamespace();
2914 return dyn_cast_or_null<NamespaceDecl>(D);
2915}
2916
Mike Stump1eb44332009-09-09 15:08:12 +00002917Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002918 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002919 SourceLocation AliasLoc,
2920 IdentifierInfo *Alias,
2921 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002922 SourceLocation IdentLoc,
2923 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Anders Carlsson81c85c42009-03-28 23:53:49 +00002925 // Lookup the namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002926 LookupResult R;
2927 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlsson81c85c42009-03-28 23:53:49 +00002928
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002929 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00002930 if (NamedDecl *PrevDecl
2931 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002932 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002933 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002934 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00002935 if (!R.isAmbiguous() && !R.empty() &&
2936 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00002937 return DeclPtrTy();
2938 }
Mike Stump1eb44332009-09-09 15:08:12 +00002939
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002940 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2941 diag::err_redefinition_different_kind;
2942 Diag(AliasLoc, DiagID) << Alias;
2943 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002944 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002945 }
2946
Anders Carlsson5721c682009-03-28 06:42:02 +00002947 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002948 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002949 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002950 }
Mike Stump1eb44332009-09-09 15:08:12 +00002951
John McCallf36e02d2009-10-09 21:13:30 +00002952 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00002953 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002954 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002955 }
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002957 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002958 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2959 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002960 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00002961 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002962
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002963 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002964 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002965}
2966
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002967void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2968 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002969 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2970 !Constructor->isUsed()) &&
2971 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002973 CXXRecordDecl *ClassDecl
2974 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002975 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump1eb44332009-09-09 15:08:12 +00002976 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002977 // implicitly defined, all the implicitly-declared default constructors
2978 // for its base class and its non-static data members shall have been
2979 // implicitly defined.
2980 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002981 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2982 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002983 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002984 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002985 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002986 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002987 BaseClassDecl->getDefaultConstructor(Context))
2988 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002989 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002990 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00002991 << Context.getTagDeclType(ClassDecl) << 0
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002992 << Context.getTagDeclType(BaseClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002993 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002994 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002995 err = true;
2996 }
2997 }
2998 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002999 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3000 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003001 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3002 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3003 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003004 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003005 CXXRecordDecl *FieldClassDecl
3006 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00003007 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003008 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003009 FieldClassDecl->getDefaultConstructor(Context))
3010 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003011 else {
Mike Stump1eb44332009-09-09 15:08:12 +00003012 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00003013 << Context.getTagDeclType(ClassDecl) << 1 <<
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00003014 Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00003015 Diag((*Field)->getLocation(), diag::note_field_decl);
Mike Stump1eb44332009-09-09 15:08:12 +00003016 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00003017 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003018 err = true;
3019 }
3020 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003021 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003022 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00003023 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003024 Diag((*Field)->getLocation(), diag::note_declared_at);
3025 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003026 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003027 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00003028 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003029 Diag((*Field)->getLocation(), diag::note_declared_at);
3030 err = true;
3031 }
3032 }
3033 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003034 Constructor->setUsed();
3035 else
3036 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003037}
3038
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003039void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003040 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003041 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3042 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003044 CXXRecordDecl *ClassDecl
3045 = cast<CXXRecordDecl>(Destructor->getDeclContext());
3046 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3047 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003048 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003049 // implicitly defined, all the implicitly-declared default destructors
3050 // for its base class and its non-static data members shall have been
3051 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3053 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003054 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003055 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003056 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003057 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003058 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3059 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3060 else
Mike Stump1eb44332009-09-09 15:08:12 +00003061 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003062 "DefineImplicitDestructor - missing dtor in a base class");
3063 }
3064 }
Mike Stump1eb44332009-09-09 15:08:12 +00003065
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003066 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3067 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003068 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3069 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3070 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003071 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003072 CXXRecordDecl *FieldClassDecl
3073 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3074 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003075 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003076 const_cast<CXXDestructorDecl*>(
3077 FieldClassDecl->getDestructor(Context)))
3078 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3079 else
Mike Stump1eb44332009-09-09 15:08:12 +00003080 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003081 "DefineImplicitDestructor - missing dtor in class of a data member");
3082 }
3083 }
3084 }
3085 Destructor->setUsed();
3086}
3087
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003088void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3089 CXXMethodDecl *MethodDecl) {
3090 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3091 MethodDecl->getOverloadedOperator() == OO_Equal &&
3092 !MethodDecl->isUsed()) &&
3093 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003095 CXXRecordDecl *ClassDecl
3096 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003098 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003099 // Before the implicitly-declared copy assignment operator for a class is
3100 // implicitly defined, all implicitly-declared copy assignment operators
3101 // for its direct base classes and its nonstatic data members shall have
3102 // been implicitly defined.
3103 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003104 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3105 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003106 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003107 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003108 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003109 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3110 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3111 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003112 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3113 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003114 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3115 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3116 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003117 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003118 CXXRecordDecl *FieldClassDecl
3119 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003120 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003121 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3122 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003123 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003124 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003125 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3126 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003127 Diag(CurrentLocation, diag::note_first_required_here);
3128 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003129 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003130 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003131 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3132 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003133 Diag(CurrentLocation, diag::note_first_required_here);
3134 err = true;
3135 }
3136 }
3137 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003138 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003139}
3140
3141CXXMethodDecl *
3142Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3143 CXXRecordDecl *ClassDecl) {
3144 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3145 QualType RHSType(LHSType);
3146 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003147 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003148 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003149 RHSType = Context.getCVRQualifiedType(RHSType,
3150 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003151 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3152 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003153 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003154 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3155 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003156 SourceLocation()));
3157 Expr *Args[2] = { &*LHS, &*RHS };
3158 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003159 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003160 CandidateSet);
3161 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003162 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003163 ClassDecl->getLocation(), Best) == OR_Success)
3164 return cast<CXXMethodDecl>(Best->Function);
3165 assert(false &&
3166 "getAssignOperatorMethod - copy assignment operator method not found");
3167 return 0;
3168}
3169
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003170void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3171 CXXConstructorDecl *CopyConstructor,
3172 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003173 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003174 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3175 !CopyConstructor->isUsed()) &&
3176 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003178 CXXRecordDecl *ClassDecl
3179 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3180 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003181 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003182 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003183 // implicitly defined, all the implicitly-declared copy constructors
3184 // for its base class and its non-static data members shall have been
3185 // implicitly defined.
3186 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3187 Base != ClassDecl->bases_end(); ++Base) {
3188 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003189 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003190 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003191 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003192 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003193 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003194 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3195 FieldEnd = ClassDecl->field_end();
3196 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003197 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3198 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3199 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003200 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003201 CXXRecordDecl *FieldClassDecl
3202 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003203 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003204 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003205 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003206 }
3207 }
3208 CopyConstructor->setUsed();
3209}
3210
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003211Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003212Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003213 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003214 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003215 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003216
Douglas Gregor39da0b82009-09-09 23:08:42 +00003217 // C++ [class.copy]p15:
3218 // Whenever a temporary class object is copied using a copy constructor, and
3219 // this object and the copy have the same cv-unqualified type, an
3220 // implementation is permitted to treat the original and the copy as two
3221 // different ways of referring to the same object and not perform a copy at
3222 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003223
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003224 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003225 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003226 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003227 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3228 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003229 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3230 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3231 E = ICE->getSubExpr();
3232
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003233 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3234 Elidable = true;
3235 }
Mike Stump1eb44332009-09-09 15:08:12 +00003236
3237 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003238 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003239}
3240
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003241/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3242/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003243Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003244Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3245 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003246 MultiExprArg ExprArgs) {
3247 unsigned NumExprs = ExprArgs.size();
3248 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003249
Douglas Gregor39da0b82009-09-09 23:08:42 +00003250 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3251 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003252}
3253
Anders Carlssone7624a72009-08-27 05:08:22 +00003254Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003255Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3256 QualType Ty,
3257 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003258 MultiExprArg Args,
3259 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003260 unsigned NumExprs = Args.size();
3261 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Douglas Gregor39da0b82009-09-09 23:08:42 +00003263 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3264 TyBeginLoc, Exprs,
3265 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003266}
3267
3268
Mike Stump1eb44332009-09-09 15:08:12 +00003269bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003270 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003271 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003272 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003273 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003274 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003275 if (TempResult.isInvalid())
3276 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003278 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003279 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003280 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003281 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Anders Carlssonfe2de492009-08-25 05:18:00 +00003283 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003284}
3285
Mike Stump1eb44332009-09-09 15:08:12 +00003286void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003287 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003288 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003289 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003290 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003291 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003292 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003293}
3294
Mike Stump1eb44332009-09-09 15:08:12 +00003295/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003296/// ActOnDeclarator, when a C++ direct initializer is present.
3297/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003298void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3299 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003300 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003301 SourceLocation *CommaLocs,
3302 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003303 unsigned NumExprs = Exprs.size();
3304 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003305 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003306
3307 // If there is no declaration, there was an error parsing it. Just ignore
3308 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003309 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003310 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003311
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003312 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3313 if (!VDecl) {
3314 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3315 RealDecl->setInvalidDecl();
3316 return;
3317 }
3318
Douglas Gregor83ddad32009-08-26 21:14:46 +00003319 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003320 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003321 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3322 //
3323 // Clients that want to distinguish between the two forms, can check for
3324 // direct initializer using VarDecl::hasCXXDirectInitializer().
3325 // A major benefit is that clients that don't particularly care about which
3326 // exactly form was it (like the CodeGen) can handle both cases without
3327 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003328
Douglas Gregor83ddad32009-08-26 21:14:46 +00003329 // If either the declaration has a dependent type or if any of the expressions
3330 // is type-dependent, we represent the initialization via a ParenListExpr for
3331 // later use during template instantiation.
3332 if (VDecl->getType()->isDependentType() ||
3333 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3334 // Let clients know that initialization was done with a direct initializer.
3335 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Douglas Gregor83ddad32009-08-26 21:14:46 +00003337 // Store the initialization expressions as a ParenListExpr.
3338 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003339 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003340 new (Context) ParenListExpr(Context, LParenLoc,
3341 (Expr **)Exprs.release(),
3342 NumExprs, RParenLoc));
3343 return;
3344 }
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Douglas Gregor83ddad32009-08-26 21:14:46 +00003346
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003347 // C++ 8.5p11:
3348 // The form of initialization (using parentheses or '=') is generally
3349 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003350 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003351 QualType DeclInitType = VDecl->getType();
3352 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003353 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003354
Douglas Gregor615c5d42009-03-24 16:43:20 +00003355 // FIXME: This isn't the right place to complete the type.
3356 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3357 diag::err_typecheck_decl_incomplete_type)) {
3358 VDecl->setInvalidDecl();
3359 return;
3360 }
3361
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003362 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003363 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3364
Douglas Gregor18fe5682008-11-03 20:45:27 +00003365 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003366 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003367 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003368 VDecl->getLocation(),
3369 SourceRange(VDecl->getLocation(),
3370 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003371 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003372 IK_Direct,
3373 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003374 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003375 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003376 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003377 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003378 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003379 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003380 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003381 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003382 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003383 return;
3384 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003385
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003386 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003387 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3388 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003389 RealDecl->setInvalidDecl();
3390 return;
3391 }
3392
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003393 // Let clients know that initialization was done with a direct initializer.
3394 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003395
3396 assert(NumExprs == 1 && "Expected 1 expression");
3397 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003398 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3399 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003400}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003401
Douglas Gregor39da0b82009-09-09 23:08:42 +00003402/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3403/// may occur as part of direct-initialization or copy-initialization.
3404///
3405/// \param ClassType the type of the object being initialized, which must have
3406/// class type.
3407///
3408/// \param ArgsPtr the arguments provided to initialize the object
3409///
3410/// \param Loc the source location where the initialization occurs
3411///
3412/// \param Range the source range that covers the entire initialization
3413///
3414/// \param InitEntity the name of the entity being initialized, if known
3415///
3416/// \param Kind the type of initialization being performed
3417///
3418/// \param ConvertedArgs a vector that will be filled in with the
3419/// appropriately-converted arguments to the constructor (if initialization
3420/// succeeded).
3421///
3422/// \returns the constructor used to initialize the object, if successful.
3423/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003424CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003425Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003426 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003427 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003428 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003429 InitializationKind Kind,
3430 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003431 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003432 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003433 Expr **Args = (Expr **)ArgsPtr.get();
3434 unsigned NumArgs = ArgsPtr.size();
3435
Mike Stump1eb44332009-09-09 15:08:12 +00003436 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003437 // If the initialization is direct-initialization, or if it is
3438 // copy-initialization where the cv-unqualified version of the
3439 // source type is the same class as, or a derived class of, the
3440 // class of the destination, constructors are considered. The
3441 // applicable constructors are enumerated (13.3.1.3), and the
3442 // best one is chosen through overload resolution (13.3). The
3443 // constructor so selected is called to initialize the object,
3444 // with the initializer expression(s) as its argument(s). If no
3445 // constructor applies, or the overload resolution is ambiguous,
3446 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003447 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3448 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003449
3450 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003451 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003452 = Context.DeclarationNames.getCXXConstructorName(
3453 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003454 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003455 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003456 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003457 // Find the constructor (which may be a template).
3458 CXXConstructorDecl *Constructor = 0;
3459 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3460 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003461 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003462 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3463 else
3464 Constructor = cast<CXXConstructorDecl>(*Con);
3465
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003466 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003467 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003468 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003469 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3470 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003471 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003472 Args, NumArgs, CandidateSet);
3473 else
3474 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3475 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003476 }
3477
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003478 // FIXME: When we decide not to synthesize the implicitly-declared
3479 // constructors, we'll need to make them appear here.
3480
Douglas Gregor18fe5682008-11-03 20:45:27 +00003481 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003482 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003483 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003484 // We found a constructor. Break out so that we can convert the arguments
3485 // appropriately.
3486 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003487
Douglas Gregor18fe5682008-11-03 20:45:27 +00003488 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003489 if (InitEntity)
3490 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003491 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003492 else
3493 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003494 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003495 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003496 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Douglas Gregor18fe5682008-11-03 20:45:27 +00003498 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003499 if (InitEntity)
3500 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3501 else
3502 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003503 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3504 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003505
3506 case OR_Deleted:
3507 if (InitEntity)
3508 Diag(Loc, diag::err_ovl_deleted_init)
3509 << Best->Function->isDeleted()
3510 << InitEntity << Range;
3511 else
3512 Diag(Loc, diag::err_ovl_deleted_init)
3513 << Best->Function->isDeleted()
3514 << InitEntity << Range;
3515 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3516 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003517 }
Mike Stump1eb44332009-09-09 15:08:12 +00003518
Douglas Gregor39da0b82009-09-09 23:08:42 +00003519 // Convert the arguments, fill in default arguments, etc.
3520 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3521 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3522 return 0;
3523
3524 return Constructor;
3525}
3526
3527/// \brief Given a constructor and the set of arguments provided for the
3528/// constructor, convert the arguments and add any required default arguments
3529/// to form a proper call to this constructor.
3530///
3531/// \returns true if an error occurred, false otherwise.
3532bool
3533Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3534 MultiExprArg ArgsPtr,
3535 SourceLocation Loc,
3536 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3537 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3538 unsigned NumArgs = ArgsPtr.size();
3539 Expr **Args = (Expr **)ArgsPtr.get();
3540
3541 const FunctionProtoType *Proto
3542 = Constructor->getType()->getAs<FunctionProtoType>();
3543 assert(Proto && "Constructor without a prototype?");
3544 unsigned NumArgsInProto = Proto->getNumArgs();
3545 unsigned NumArgsToCheck = NumArgs;
3546
3547 // If too few arguments are available, we'll fill in the rest with defaults.
3548 if (NumArgs < NumArgsInProto) {
3549 NumArgsToCheck = NumArgsInProto;
3550 ConvertedArgs.reserve(NumArgsInProto);
3551 } else {
3552 ConvertedArgs.reserve(NumArgs);
3553 if (NumArgs > NumArgsInProto)
3554 NumArgsToCheck = NumArgsInProto;
3555 }
3556
3557 // Convert arguments
3558 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3559 QualType ProtoArgType = Proto->getArgType(i);
3560
3561 Expr *Arg;
3562 if (i < NumArgs) {
3563 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003564
3565 // Pass the argument.
3566 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3567 return true;
3568
3569 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003570 } else {
3571 ParmVarDecl *Param = Constructor->getParamDecl(i);
3572
3573 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3574 if (DefArg.isInvalid())
3575 return true;
3576
3577 Arg = DefArg.takeAs<Expr>();
3578 }
3579
3580 ConvertedArgs.push_back(Arg);
3581 }
3582
3583 // If this is a variadic call, handle args passed through "...".
3584 if (Proto->isVariadic()) {
3585 // Promote the arguments (C99 6.5.2.2p7).
3586 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3587 Expr *Arg = Args[i];
3588 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3589 return true;
3590
3591 ConvertedArgs.push_back(Arg);
3592 Args[i] = 0;
3593 }
3594 }
3595
3596 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003597}
3598
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003599/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3600/// determine whether they are reference-related,
3601/// reference-compatible, reference-compatible with added
3602/// qualification, or incompatible, for use in C++ initialization by
3603/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3604/// type, and the first type (T1) is the pointee type of the reference
3605/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003606Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00003607Sema::CompareReferenceRelationship(SourceLocation Loc,
3608 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003609 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003610 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003611 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00003612 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003613
Douglas Gregor393896f2009-11-05 13:06:35 +00003614 QualType T1 = Context.getCanonicalType(OrigT1);
3615 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003616 QualType UnqualT1 = T1.getUnqualifiedType();
3617 QualType UnqualT2 = T2.getUnqualifiedType();
3618
3619 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003620 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003621 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003622 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003623 if (UnqualT1 == UnqualT2)
3624 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00003625 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3626 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3627 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00003628 DerivedToBase = true;
3629 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003630 return Ref_Incompatible;
3631
3632 // At this point, we know that T1 and T2 are reference-related (at
3633 // least).
3634
3635 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003636 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003637 // reference-related to T2 and cv1 is the same cv-qualification
3638 // as, or greater cv-qualification than, cv2. For purposes of
3639 // overload resolution, cases for which cv1 is greater
3640 // cv-qualification than cv2 are identified as
3641 // reference-compatible with added qualification (see 13.3.3.2).
3642 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3643 return Ref_Compatible;
3644 else if (T1.isMoreQualifiedThan(T2))
3645 return Ref_Compatible_With_Added_Qualification;
3646 else
3647 return Ref_Related;
3648}
3649
3650/// CheckReferenceInit - Check the initialization of a reference
3651/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3652/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003653/// list), and DeclType is the type of the declaration. When ICS is
3654/// non-null, this routine will compute the implicit conversion
3655/// sequence according to C++ [over.ics.ref] and will not produce any
3656/// diagnostics; when ICS is null, it will emit diagnostics when any
3657/// errors are found. Either way, a return value of true indicates
3658/// that there was a failure, a return value of false indicates that
3659/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003660///
3661/// When @p SuppressUserConversions, user-defined conversions are
3662/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003663/// When @p AllowExplicit, we also permit explicit user-defined
3664/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003665/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003666bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003667Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003668 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003669 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003670 bool AllowExplicit, bool ForceRValue,
3671 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003672 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3673
Ted Kremenek6217b802009-07-29 21:53:49 +00003674 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003675 QualType T2 = Init->getType();
3676
Douglas Gregor904eed32008-11-10 20:40:00 +00003677 // If the initializer is the address of an overloaded function, try
3678 // to resolve the overloaded function. If all goes well, T2 is the
3679 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003680 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003681 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003682 ICS != 0);
3683 if (Fn) {
3684 // Since we're performing this reference-initialization for
3685 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003686 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003687 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003688 return true;
3689
Anders Carlsson96ad5332009-10-21 17:16:23 +00003690 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003691 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003692
3693 T2 = Fn->getType();
3694 }
3695 }
3696
Douglas Gregor15da57e2008-10-29 02:00:59 +00003697 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003698 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003699 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003700 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3701 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003702 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00003703 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003704
3705 // Most paths end in a failed conversion.
3706 if (ICS)
3707 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003708
3709 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003710 // A reference to type "cv1 T1" is initialized by an expression
3711 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003712
3713 // -- If the initializer expression
3714
Sebastian Redla9845802009-03-29 15:27:50 +00003715 // Rvalue references cannot bind to lvalues (N2812).
3716 // There is absolutely no situation where they can. In particular, note that
3717 // this is ill-formed, even if B has a user-defined conversion to A&&:
3718 // B b;
3719 // A&& r = b;
3720 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3721 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003722 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003723 << Init->getSourceRange();
3724 return true;
3725 }
3726
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003727 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003728 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3729 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003730 //
3731 // Note that the bit-field check is skipped if we are just computing
3732 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003733 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003734 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003735 BindsDirectly = true;
3736
Douglas Gregor15da57e2008-10-29 02:00:59 +00003737 if (ICS) {
3738 // C++ [over.ics.ref]p1:
3739 // When a parameter of reference type binds directly (8.5.3)
3740 // to an argument expression, the implicit conversion sequence
3741 // is the identity conversion, unless the argument expression
3742 // has a type that is a derived class of the parameter type,
3743 // in which case the implicit conversion sequence is a
3744 // derived-to-base Conversion (13.3.3.1).
3745 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3746 ICS->Standard.First = ICK_Identity;
3747 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3748 ICS->Standard.Third = ICK_Identity;
3749 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3750 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003751 ICS->Standard.ReferenceBinding = true;
3752 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003753 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003754 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003755
3756 // Nothing more to do: the inaccessibility/ambiguity check for
3757 // derived-to-base conversions is suppressed when we're
3758 // computing the implicit conversion sequence (C++
3759 // [over.best.ics]p2).
3760 return false;
3761 } else {
3762 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003763 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3764 if (DerivedToBase)
3765 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003766 else if(CheckExceptionSpecCompatibility(Init, T1))
3767 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003768 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003769 }
3770 }
3771
3772 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003773 // implicitly converted to an lvalue of type "cv3 T3,"
3774 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003775 // 92) (this conversion is selected by enumerating the
3776 // applicable conversion functions (13.3.1.6) and choosing
3777 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003778 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003779 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003780 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003781 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003782
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003783 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003784 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003785 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003786 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003787 = Conversions->function_begin();
3788 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003789 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003790 = dyn_cast<FunctionTemplateDecl>(*Func);
3791 CXXConversionDecl *Conv;
3792 if (ConvTemplate)
3793 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3794 else
3795 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003796
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003797 // If the conversion function doesn't return a reference type,
3798 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003799 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003800 (AllowExplicit || !Conv->isExplicit())) {
3801 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003802 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003803 CandidateSet);
3804 else
3805 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3806 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003807 }
3808
3809 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003810 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003811 case OR_Success:
3812 // This is a direct binding.
3813 BindsDirectly = true;
3814
3815 if (ICS) {
3816 // C++ [over.ics.ref]p1:
3817 //
3818 // [...] If the parameter binds directly to the result of
3819 // applying a conversion function to the argument
3820 // expression, the implicit conversion sequence is a
3821 // user-defined conversion sequence (13.3.3.1.2), with the
3822 // second standard conversion sequence either an identity
3823 // conversion or, if the conversion function returns an
3824 // entity of a type that is a derived class of the parameter
3825 // type, a derived-to-base Conversion.
3826 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3827 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3828 ICS->UserDefined.After = Best->FinalConversion;
3829 ICS->UserDefined.ConversionFunction = Best->Function;
3830 assert(ICS->UserDefined.After.ReferenceBinding &&
3831 ICS->UserDefined.After.DirectBinding &&
3832 "Expected a direct reference binding!");
3833 return false;
3834 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003835 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003836 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003837 CastExpr::CK_UserDefinedConversion,
3838 cast<CXXMethodDecl>(Best->Function),
3839 Owned(Init));
3840 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003841
3842 if (CheckExceptionSpecCompatibility(Init, T1))
3843 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003844 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3845 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003846 }
3847 break;
3848
3849 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003850 if (ICS) {
3851 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3852 Cand != CandidateSet.end(); ++Cand)
3853 if (Cand->Viable)
3854 ICS->ConversionFunctionSet.push_back(Cand->Function);
3855 break;
3856 }
3857 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3858 << Init->getSourceRange();
3859 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003860 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003862 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003863 case OR_Deleted:
3864 // There was no suitable conversion, or we found a deleted
3865 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003866 break;
3867 }
3868 }
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003870 if (BindsDirectly) {
3871 // C++ [dcl.init.ref]p4:
3872 // [...] In all cases where the reference-related or
3873 // reference-compatible relationship of two types is used to
3874 // establish the validity of a reference binding, and T1 is a
3875 // base class of T2, a program that necessitates such a binding
3876 // is ill-formed if T1 is an inaccessible (clause 11) or
3877 // ambiguous (10.2) base class of T2.
3878 //
3879 // Note that we only check this condition when we're allowed to
3880 // complain about errors, because we should not be checking for
3881 // ambiguity (or inaccessibility) unless the reference binding
3882 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003883 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003884 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003885 Init->getSourceRange());
3886 else
3887 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003888 }
3889
3890 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003891 // type (i.e., cv1 shall be const), or the reference shall be an
3892 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003893 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003894 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003895 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003896 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3897 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003898 return true;
3899 }
3900
3901 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003902 // class type, and "cv1 T1" is reference-compatible with
3903 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003904 // following ways (the choice is implementation-defined):
3905 //
3906 // -- The reference is bound to the object represented by
3907 // the rvalue (see 3.10) or to a sub-object within that
3908 // object.
3909 //
Eli Friedman33a31382009-08-05 19:21:58 +00003910 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003911 // a constructor is called to copy the entire rvalue
3912 // object into the temporary. The reference is bound to
3913 // the temporary or to a sub-object within the
3914 // temporary.
3915 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003916 // The constructor that would be used to make the copy
3917 // shall be callable whether or not the copy is actually
3918 // done.
3919 //
Sebastian Redla9845802009-03-29 15:27:50 +00003920 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003921 // freedom, so we will always take the first option and never build
3922 // a temporary in this case. FIXME: We will, however, have to check
3923 // for the presence of a copy constructor in C++98/03 mode.
3924 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003925 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3926 if (ICS) {
3927 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3928 ICS->Standard.First = ICK_Identity;
3929 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3930 ICS->Standard.Third = ICK_Identity;
3931 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3932 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003933 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003934 ICS->Standard.DirectBinding = false;
3935 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003936 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003937 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003938 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3939 if (DerivedToBase)
3940 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003941 else if(CheckExceptionSpecCompatibility(Init, T1))
3942 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003943 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003944 }
3945 return false;
3946 }
3947
Eli Friedman33a31382009-08-05 19:21:58 +00003948 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003949 // initialized from the initializer expression using the
3950 // rules for a non-reference copy initialization (8.5). The
3951 // reference is then bound to the temporary. If T1 is
3952 // reference-related to T2, cv1 must be the same
3953 // cv-qualification as, or greater cv-qualification than,
3954 // cv2; otherwise, the program is ill-formed.
3955 if (RefRelationship == Ref_Related) {
3956 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3957 // we would be reference-compatible or reference-compatible with
3958 // added qualification. But that wasn't the case, so the reference
3959 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003960 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003961 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003962 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3963 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003964 return true;
3965 }
3966
Douglas Gregor734d9862009-01-30 23:27:23 +00003967 // If at least one of the types is a class type, the types are not
3968 // related, and we aren't allowed any user conversions, the
3969 // reference binding fails. This case is important for breaking
3970 // recursion, since TryImplicitConversion below will attempt to
3971 // create a temporary through the use of a copy constructor.
3972 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3973 (T1->isRecordType() || T2->isRecordType())) {
3974 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003975 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00003976 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3977 return true;
3978 }
3979
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003980 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003981 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003982 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003983 //
Sebastian Redla9845802009-03-29 15:27:50 +00003984 // When a parameter of reference type is not bound directly to
3985 // an argument expression, the conversion sequence is the one
3986 // required to convert the argument expression to the
3987 // underlying type of the reference according to
3988 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3989 // to copy-initializing a temporary of the underlying type with
3990 // the argument expression. Any difference in top-level
3991 // cv-qualification is subsumed by the initialization itself
3992 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003993 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3994 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003995 /*ForceRValue=*/false,
3996 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Sebastian Redla9845802009-03-29 15:27:50 +00003998 // Of course, that's still a reference binding.
3999 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4000 ICS->Standard.ReferenceBinding = true;
4001 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004002 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004003 ImplicitConversionSequence::UserDefinedConversion) {
4004 ICS->UserDefined.After.ReferenceBinding = true;
4005 ICS->UserDefined.After.RRefBinding = isRValRef;
4006 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004007 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4008 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004009 ImplicitConversionSequence Conversions;
4010 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4011 false, false,
4012 Conversions);
4013 if (badConversion) {
4014 if ((Conversions.ConversionKind ==
4015 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004016 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004017 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004018 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4019 for (int j = Conversions.ConversionFunctionSet.size()-1;
4020 j >= 0; j--) {
4021 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4022 Diag(Func->getLocation(), diag::err_ovl_candidate);
4023 }
4024 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004025 else {
4026 if (isRValRef)
4027 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4028 << Init->getSourceRange();
4029 else
4030 Diag(DeclLoc, diag::err_invalid_initialization)
4031 << DeclType << Init->getType() << Init->getSourceRange();
4032 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004033 }
4034 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004035 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004036}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004037
4038/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4039/// of this overloaded operator is well-formed. If so, returns false;
4040/// otherwise, emits appropriate diagnostics and returns true.
4041bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004042 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004043 "Expected an overloaded operator declaration");
4044
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004045 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4046
Mike Stump1eb44332009-09-09 15:08:12 +00004047 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004048 // The allocation and deallocation functions, operator new,
4049 // operator new[], operator delete and operator delete[], are
4050 // described completely in 3.7.3. The attributes and restrictions
4051 // found in the rest of this subclause do not apply to them unless
4052 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00004053 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004054 if (Op == OO_New || Op == OO_Array_New ||
4055 Op == OO_Delete || Op == OO_Array_Delete)
4056 return false;
4057
4058 // C++ [over.oper]p6:
4059 // An operator function shall either be a non-static member
4060 // function or be a non-member function and have at least one
4061 // parameter whose type is a class, a reference to a class, an
4062 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004063 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4064 if (MethodDecl->isStatic())
4065 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004066 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004067 } else {
4068 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004069 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4070 ParamEnd = FnDecl->param_end();
4071 Param != ParamEnd; ++Param) {
4072 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004073 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4074 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004075 ClassOrEnumParam = true;
4076 break;
4077 }
4078 }
4079
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004080 if (!ClassOrEnumParam)
4081 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004082 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004083 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004084 }
4085
4086 // C++ [over.oper]p8:
4087 // An operator function cannot have default arguments (8.3.6),
4088 // except where explicitly stated below.
4089 //
Mike Stump1eb44332009-09-09 15:08:12 +00004090 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004091 // (C++ [over.call]p1).
4092 if (Op != OO_Call) {
4093 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4094 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004095 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004096 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004097 diag::err_operator_overload_default_arg)
4098 << FnDecl->getDeclName();
4099 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004100 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004101 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004102 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004103 }
4104 }
4105
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004106 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4107 { false, false, false }
4108#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4109 , { Unary, Binary, MemberOnly }
4110#include "clang/Basic/OperatorKinds.def"
4111 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004112
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004113 bool CanBeUnaryOperator = OperatorUses[Op][0];
4114 bool CanBeBinaryOperator = OperatorUses[Op][1];
4115 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004116
4117 // C++ [over.oper]p8:
4118 // [...] Operator functions cannot have more or fewer parameters
4119 // than the number required for the corresponding operator, as
4120 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004121 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004122 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004123 if (Op != OO_Call &&
4124 ((NumParams == 1 && !CanBeUnaryOperator) ||
4125 (NumParams == 2 && !CanBeBinaryOperator) ||
4126 (NumParams < 1) || (NumParams > 2))) {
4127 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004128 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004129 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004130 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004131 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004132 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004133 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004134 assert(CanBeBinaryOperator &&
4135 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004136 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004137 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004138
Chris Lattner416e46f2008-11-21 07:57:12 +00004139 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004140 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004141 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004142
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004143 // Overloaded operators other than operator() cannot be variadic.
4144 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004145 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004146 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004147 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004148 }
4149
4150 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004151 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4152 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004153 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004154 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004155 }
4156
4157 // C++ [over.inc]p1:
4158 // The user-defined function called operator++ implements the
4159 // prefix and postfix ++ operator. If this function is a member
4160 // function with no parameters, or a non-member function with one
4161 // parameter of class or enumeration type, it defines the prefix
4162 // increment operator ++ for objects of that type. If the function
4163 // is a member function with one parameter (which shall be of type
4164 // int) or a non-member function with two parameters (the second
4165 // of which shall be of type int), it defines the postfix
4166 // increment operator ++ for objects of that type.
4167 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4168 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4169 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004170 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004171 ParamIsInt = BT->getKind() == BuiltinType::Int;
4172
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004173 if (!ParamIsInt)
4174 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004175 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004176 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004177 }
4178
Sebastian Redl64b45f72009-01-05 20:52:13 +00004179 // Notify the class if it got an assignment operator.
4180 if (Op == OO_Equal) {
4181 // Would have returned earlier otherwise.
4182 assert(isa<CXXMethodDecl>(FnDecl) &&
4183 "Overloaded = not member, but not filtered.");
4184 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00004185 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004186 Method->getParent()->addedAssignmentOperator(Context, Method);
4187 }
4188
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004189 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004190}
Chris Lattner5a003a42008-12-17 07:09:26 +00004191
Douglas Gregor074149e2009-01-05 19:45:36 +00004192/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4193/// linkage specification, including the language and (if present)
4194/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4195/// the location of the language string literal, which is provided
4196/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4197/// the '{' brace. Otherwise, this linkage specification does not
4198/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004199Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4200 SourceLocation ExternLoc,
4201 SourceLocation LangLoc,
4202 const char *Lang,
4203 unsigned StrSize,
4204 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004205 LinkageSpecDecl::LanguageIDs Language;
4206 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4207 Language = LinkageSpecDecl::lang_c;
4208 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4209 Language = LinkageSpecDecl::lang_cxx;
4210 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004211 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004212 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004213 }
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Chris Lattnercc98eac2008-12-17 07:13:27 +00004215 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004216
Douglas Gregor074149e2009-01-05 19:45:36 +00004217 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004218 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004219 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004220 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004221 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004222 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004223}
4224
Douglas Gregor074149e2009-01-05 19:45:36 +00004225/// ActOnFinishLinkageSpecification - Completely the definition of
4226/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4227/// valid, it's the position of the closing '}' brace in a linkage
4228/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004229Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4230 DeclPtrTy LinkageSpec,
4231 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004232 if (LinkageSpec)
4233 PopDeclContext();
4234 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004235}
4236
Douglas Gregord308e622009-05-18 20:51:54 +00004237/// \brief Perform semantic analysis for the variable declaration that
4238/// occurs within a C++ catch clause, returning the newly-created
4239/// variable.
4240VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004241 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004242 IdentifierInfo *Name,
4243 SourceLocation Loc,
4244 SourceRange Range) {
4245 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004246
4247 // Arrays and functions decay.
4248 if (ExDeclType->isArrayType())
4249 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4250 else if (ExDeclType->isFunctionType())
4251 ExDeclType = Context.getPointerType(ExDeclType);
4252
4253 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4254 // The exception-declaration shall not denote a pointer or reference to an
4255 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004256 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004257 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004258 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004259 Invalid = true;
4260 }
Douglas Gregord308e622009-05-18 20:51:54 +00004261
Sebastian Redl4b07b292008-12-22 19:15:10 +00004262 QualType BaseType = ExDeclType;
4263 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004264 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004265 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004266 BaseType = Ptr->getPointeeType();
4267 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004268 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004269 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004270 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004271 BaseType = Ref->getPointeeType();
4272 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004273 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004274 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004275 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004276 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004277 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004278
Mike Stump1eb44332009-09-09 15:08:12 +00004279 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004280 RequireNonAbstractType(Loc, ExDeclType,
4281 diag::err_abstract_type_in_decl,
4282 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004283 Invalid = true;
4284
Douglas Gregord308e622009-05-18 20:51:54 +00004285 // FIXME: Need to test for ability to copy-construct and destroy the
4286 // exception variable.
4287
Sebastian Redl8351da02008-12-22 21:35:02 +00004288 // FIXME: Need to check for abstract classes.
4289
Mike Stump1eb44332009-09-09 15:08:12 +00004290 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004291 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004292
4293 if (Invalid)
4294 ExDecl->setInvalidDecl();
4295
4296 return ExDecl;
4297}
4298
4299/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4300/// handler.
4301Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004302 DeclaratorInfo *DInfo = 0;
4303 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004304
4305 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004306 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004307 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004308 // The scope should be freshly made just for us. There is just no way
4309 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004310 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004311 if (PrevDecl->isTemplateParameter()) {
4312 // Maybe we will complain about the shadowed template parameter.
4313 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004314 }
4315 }
4316
Chris Lattnereaaebc72009-04-25 08:06:05 +00004317 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004318 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4319 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004320 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004321 }
4322
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004323 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004324 D.getIdentifier(),
4325 D.getIdentifierLoc(),
4326 D.getDeclSpec().getSourceRange());
4327
Chris Lattnereaaebc72009-04-25 08:06:05 +00004328 if (Invalid)
4329 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Sebastian Redl4b07b292008-12-22 19:15:10 +00004331 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004332 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004333 PushOnScopeChains(ExDecl, S);
4334 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004335 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004336
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004337 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004338 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004339}
Anders Carlssonfb311762009-03-14 00:25:26 +00004340
Mike Stump1eb44332009-09-09 15:08:12 +00004341Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004342 ExprArg assertexpr,
4343 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004344 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004345 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004346 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4347
Anders Carlssonc3082412009-03-14 00:33:21 +00004348 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4349 llvm::APSInt Value(32);
4350 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4351 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4352 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004353 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004354 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004355
Anders Carlssonc3082412009-03-14 00:33:21 +00004356 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004357 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004358 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004359 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004360 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004361 }
4362 }
Mike Stump1eb44332009-09-09 15:08:12 +00004363
Anders Carlsson77d81422009-03-15 17:35:16 +00004364 assertexpr.release();
4365 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004366 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004367 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004369 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004370 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004371}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004372
John McCalldd4a3b02009-09-16 22:47:08 +00004373/// Handle a friend type declaration. This works in tandem with
4374/// ActOnTag.
4375///
4376/// Notes on friend class templates:
4377///
4378/// We generally treat friend class declarations as if they were
4379/// declaring a class. So, for example, the elaborated type specifier
4380/// in a friend declaration is required to obey the restrictions of a
4381/// class-head (i.e. no typedefs in the scope chain), template
4382/// parameters are required to match up with simple template-ids, &c.
4383/// However, unlike when declaring a template specialization, it's
4384/// okay to refer to a template specialization without an empty
4385/// template parameter declaration, e.g.
4386/// friend class A<T>::B<unsigned>;
4387/// We permit this as a special case; if there are any template
4388/// parameters present at all, require proper matching, i.e.
4389/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004390Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004391 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004392 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004393
4394 assert(DS.isFriendSpecified());
4395 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4396
John McCalldd4a3b02009-09-16 22:47:08 +00004397 // Try to convert the decl specifier to a type. This works for
4398 // friend templates because ActOnTag never produces a ClassTemplateDecl
4399 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004400 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004401 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4402 if (TheDeclarator.isInvalidType())
4403 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004404
John McCalldd4a3b02009-09-16 22:47:08 +00004405 // This is definitely an error in C++98. It's probably meant to
4406 // be forbidden in C++0x, too, but the specification is just
4407 // poorly written.
4408 //
4409 // The problem is with declarations like the following:
4410 // template <T> friend A<T>::foo;
4411 // where deciding whether a class C is a friend or not now hinges
4412 // on whether there exists an instantiation of A that causes
4413 // 'foo' to equal C. There are restrictions on class-heads
4414 // (which we declare (by fiat) elaborated friend declarations to
4415 // be) that makes this tractable.
4416 //
4417 // FIXME: handle "template <> friend class A<T>;", which
4418 // is possibly well-formed? Who even knows?
4419 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4420 Diag(Loc, diag::err_tagless_friend_type_template)
4421 << DS.getSourceRange();
4422 return DeclPtrTy();
4423 }
4424
John McCall02cace72009-08-28 07:59:38 +00004425 // C++ [class.friend]p2:
4426 // An elaborated-type-specifier shall be used in a friend declaration
4427 // for a class.*
4428 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004429 // This is one of the rare places in Clang where it's legitimate to
4430 // ask about the "spelling" of the type.
4431 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4432 // If we evaluated the type to a record type, suggest putting
4433 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004434 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004435 RecordDecl *RD = RT->getDecl();
4436
4437 std::string InsertionText = std::string(" ") + RD->getKindName();
4438
John McCalle3af0232009-10-07 23:34:25 +00004439 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4440 << (unsigned) RD->getTagKind()
4441 << T
4442 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004443 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4444 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004445 return DeclPtrTy();
4446 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004447 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4448 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004449 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004450 }
4451 }
4452
John McCalle3af0232009-10-07 23:34:25 +00004453 // Enum types cannot be friends.
4454 if (T->getAs<EnumType>()) {
4455 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4456 << SourceRange(DS.getFriendSpecLoc());
4457 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004458 }
John McCall02cace72009-08-28 07:59:38 +00004459
John McCall02cace72009-08-28 07:59:38 +00004460 // C++98 [class.friend]p1: A friend of a class is a function
4461 // or class that is not a member of the class . . .
4462 // But that's a silly restriction which nobody implements for
4463 // inner classes, and C++0x removes it anyway, so we only report
4464 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004465 if (!getLangOptions().CPlusPlus0x)
4466 if (const RecordType *RT = T->getAs<RecordType>())
4467 if (RT->getDecl()->getDeclContext() == CurContext)
4468 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004469
John McCalldd4a3b02009-09-16 22:47:08 +00004470 Decl *D;
4471 if (TempParams.size())
4472 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4473 TempParams.size(),
4474 (TemplateParameterList**) TempParams.release(),
4475 T.getTypePtr(),
4476 DS.getFriendSpecLoc());
4477 else
4478 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4479 DS.getFriendSpecLoc());
4480 D->setAccess(AS_public);
4481 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004482
John McCalldd4a3b02009-09-16 22:47:08 +00004483 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004484}
4485
John McCallbbbcdd92009-09-11 21:02:39 +00004486Sema::DeclPtrTy
4487Sema::ActOnFriendFunctionDecl(Scope *S,
4488 Declarator &D,
4489 bool IsDefinition,
4490 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004491 const DeclSpec &DS = D.getDeclSpec();
4492
4493 assert(DS.isFriendSpecified());
4494 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4495
4496 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004497 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004498 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004499
4500 // C++ [class.friend]p1
4501 // A friend of a class is a function or class....
4502 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004503 // It *doesn't* see through dependent types, which is correct
4504 // according to [temp.arg.type]p3:
4505 // If a declaration acquires a function type through a
4506 // type dependent on a template-parameter and this causes
4507 // a declaration that does not use the syntactic form of a
4508 // function declarator to have a function type, the program
4509 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004510 if (!T->isFunctionType()) {
4511 Diag(Loc, diag::err_unexpected_friend);
4512
4513 // It might be worthwhile to try to recover by creating an
4514 // appropriate declaration.
4515 return DeclPtrTy();
4516 }
4517
4518 // C++ [namespace.memdef]p3
4519 // - If a friend declaration in a non-local class first declares a
4520 // class or function, the friend class or function is a member
4521 // of the innermost enclosing namespace.
4522 // - The name of the friend is not found by simple name lookup
4523 // until a matching declaration is provided in that namespace
4524 // scope (either before or after the class declaration granting
4525 // friendship).
4526 // - If a friend function is called, its name may be found by the
4527 // name lookup that considers functions from namespaces and
4528 // classes associated with the types of the function arguments.
4529 // - When looking for a prior declaration of a class or a function
4530 // declared as a friend, scopes outside the innermost enclosing
4531 // namespace scope are not considered.
4532
John McCall02cace72009-08-28 07:59:38 +00004533 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4534 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004535 assert(Name);
4536
John McCall67d1a672009-08-06 02:15:43 +00004537 // The context we found the declaration in, or in which we should
4538 // create the declaration.
4539 DeclContext *DC;
4540
4541 // FIXME: handle local classes
4542
4543 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004544 NamedDecl *PrevDecl = 0;
John McCall67d1a672009-08-06 02:15:43 +00004545 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004546 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004547 DC = computeDeclContext(ScopeQual);
4548
4549 // FIXME: handle dependent contexts
4550 if (!DC) return DeclPtrTy();
4551
John McCallf36e02d2009-10-09 21:13:30 +00004552 LookupResult R;
4553 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4554 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004555
4556 // If searching in that context implicitly found a declaration in
4557 // a different context, treat it like it wasn't found at all.
4558 // TODO: better diagnostics for this case. Suggesting the right
4559 // qualified scope would be nice...
Douglas Gregor182ddf02009-09-28 00:08:27 +00004560 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004561 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004562 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4563 return DeclPtrTy();
4564 }
4565
4566 // C++ [class.friend]p1: A friend of a class is a function or
4567 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004568 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004569 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4570
John McCall67d1a672009-08-06 02:15:43 +00004571 // Otherwise walk out to the nearest namespace scope looking for matches.
4572 } else {
4573 // TODO: handle local class contexts.
4574
4575 DC = CurContext;
4576 while (true) {
4577 // Skip class contexts. If someone can cite chapter and verse
4578 // for this behavior, that would be nice --- it's what GCC and
4579 // EDG do, and it seems like a reasonable intent, but the spec
4580 // really only says that checks for unqualified existing
4581 // declarations should stop at the nearest enclosing namespace,
4582 // not that they should only consider the nearest enclosing
4583 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004584 while (DC->isRecord())
4585 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004586
John McCallf36e02d2009-10-09 21:13:30 +00004587 LookupResult R;
4588 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4589 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004590
4591 // TODO: decide what we think about using declarations.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004592 if (PrevDecl)
John McCall67d1a672009-08-06 02:15:43 +00004593 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004594
John McCall67d1a672009-08-06 02:15:43 +00004595 if (DC->isFileContext()) break;
4596 DC = DC->getParent();
4597 }
4598
4599 // C++ [class.friend]p1: A friend of a class is a function or
4600 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004601 // C++0x changes this for both friend types and functions.
4602 // Most C++ 98 compilers do seem to give an error here, so
4603 // we do, too.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004604 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004605 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4606 }
4607
Douglas Gregor182ddf02009-09-28 00:08:27 +00004608 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004609 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004610 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4611 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4612 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00004613 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004614 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4615 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004616 return DeclPtrTy();
4617 }
John McCall67d1a672009-08-06 02:15:43 +00004618 }
4619
Douglas Gregor182ddf02009-09-28 00:08:27 +00004620 bool Redeclaration = false;
4621 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregora735b202009-10-13 14:39:41 +00004622 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004623 IsDefinition,
4624 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004625 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004626
Douglas Gregor182ddf02009-09-28 00:08:27 +00004627 assert(ND->getDeclContext() == DC);
4628 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004629
John McCallab88d972009-08-31 22:39:49 +00004630 // Add the function declaration to the appropriate lookup tables,
4631 // adjusting the redeclarations list as necessary. We don't
4632 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004633 //
John McCallab88d972009-08-31 22:39:49 +00004634 // Also update the scope-based lookup if the target context's
4635 // lookup context is in lexical scope.
4636 if (!CurContext->isDependentContext()) {
4637 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004638 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004639 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004640 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004641 }
John McCall02cace72009-08-28 07:59:38 +00004642
4643 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004644 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004645 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004646 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004647 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004648
Douglas Gregor182ddf02009-09-28 00:08:27 +00004649 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004650}
4651
Chris Lattnerb28317a2009-03-28 19:18:32 +00004652void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004653 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004654
Chris Lattnerb28317a2009-03-28 19:18:32 +00004655 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004656 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4657 if (!Fn) {
4658 Diag(DelLoc, diag::err_deleted_non_function);
4659 return;
4660 }
4661 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4662 Diag(DelLoc, diag::err_deleted_decl_not_first);
4663 Diag(Prev->getLocation(), diag::note_previous_declaration);
4664 // If the declaration wasn't the first, we delete the function anyway for
4665 // recovery.
4666 }
4667 Fn->setDeleted();
4668}
Sebastian Redl13e88542009-04-27 21:33:24 +00004669
4670static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4671 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4672 ++CI) {
4673 Stmt *SubStmt = *CI;
4674 if (!SubStmt)
4675 continue;
4676 if (isa<ReturnStmt>(SubStmt))
4677 Self.Diag(SubStmt->getSourceRange().getBegin(),
4678 diag::err_return_in_constructor_handler);
4679 if (!isa<Expr>(SubStmt))
4680 SearchForReturnInStmt(Self, SubStmt);
4681 }
4682}
4683
4684void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4685 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4686 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4687 SearchForReturnInStmt(*this, Handler);
4688 }
4689}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004690
Mike Stump1eb44332009-09-09 15:08:12 +00004691bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004692 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004693 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4694 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004695
4696 QualType CNewTy = Context.getCanonicalType(NewTy);
4697 QualType COldTy = Context.getCanonicalType(OldTy);
4698
Mike Stump1eb44332009-09-09 15:08:12 +00004699 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004700 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4701 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004703 // Check if the return types are covariant
4704 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004706 /// Both types must be pointers or references to classes.
4707 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4708 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4709 NewClassTy = NewPT->getPointeeType();
4710 OldClassTy = OldPT->getPointeeType();
4711 }
4712 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4713 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4714 NewClassTy = NewRT->getPointeeType();
4715 OldClassTy = OldRT->getPointeeType();
4716 }
4717 }
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004719 // The return types aren't either both pointers or references to a class type.
4720 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004721 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004722 diag::err_different_return_type_for_overriding_virtual_function)
4723 << New->getDeclName() << NewTy << OldTy;
4724 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004725
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004726 return true;
4727 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004728
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004729 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4730 // Check if the new class derives from the old class.
4731 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4732 Diag(New->getLocation(),
4733 diag::err_covariant_return_not_derived)
4734 << New->getDeclName() << NewTy << OldTy;
4735 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4736 return true;
4737 }
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004739 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004740 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004741 diag::err_covariant_return_inaccessible_base,
4742 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4743 // FIXME: Should this point to the return type?
4744 New->getLocation(), SourceRange(), New->getDeclName())) {
4745 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4746 return true;
4747 }
4748 }
Mike Stump1eb44332009-09-09 15:08:12 +00004749
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004750 // The qualifiers of the return types must be the same.
4751 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4752 Diag(New->getLocation(),
4753 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004754 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004755 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4756 return true;
4757 };
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004759
4760 // The new class type must have the same or less qualifiers as the old type.
4761 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4762 Diag(New->getLocation(),
4763 diag::err_covariant_return_type_class_type_more_qualified)
4764 << New->getDeclName() << NewTy << OldTy;
4765 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4766 return true;
4767 };
Mike Stump1eb44332009-09-09 15:08:12 +00004768
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004769 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004770}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004771
4772/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4773/// initializer for the declaration 'Dcl'.
4774/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4775/// static data member of class X, names should be looked up in the scope of
4776/// class X.
4777void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004778 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004779
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004780 Decl *D = Dcl.getAs<Decl>();
4781 // If there is no declaration, there was an error parsing it.
4782 if (D == 0)
4783 return;
4784
4785 // Check whether it is a declaration with a nested name specifier like
4786 // int foo::bar;
4787 if (!D->isOutOfLine())
4788 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004789
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004790 // C++ [basic.lookup.unqual]p13
4791 //
4792 // A name used in the definition of a static data member of class X
4793 // (after the qualified-id of the static member) is looked up as if the name
4794 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004795
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004796 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004797 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004798}
4799
4800/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4801/// initializer for the declaration 'Dcl'.
4802void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004803 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004804
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004805 Decl *D = Dcl.getAs<Decl>();
4806 // If there is no declaration, there was an error parsing it.
4807 if (D == 0)
4808 return;
4809
4810 // Check whether it is a declaration with a nested name specifier like
4811 // int foo::bar;
4812 if (!D->isOutOfLine())
4813 return;
4814
4815 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004816 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004817}