blob: 7df86ee66c3b117a77e7d133b244e0cba9e95053 [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"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000019#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000020#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000021#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000022#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000025#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
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.
Benjamin Kramer85b45212009-11-28 19:45:26 +000042 class 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()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000267 // FIXME: If the parameter doesn't have an identifier then the location
268 // points to the '=' which means that the fixit hint won't remove any
269 // extra spaces between the type and the '='.
270 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000271 if (NewParam->getIdentifier())
272 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000273
Mike Stump1eb44332009-09-09 15:08:12 +0000274 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000275 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000276 << NewParam->getDefaultArgRange()
277 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
278 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000279
280 // Look for the function declaration where the default argument was
281 // actually written, which may be a declaration prior to Old.
282 for (FunctionDecl *Older = Old->getPreviousDeclaration();
283 Older; Older = Older->getPreviousDeclaration()) {
284 if (!Older->getParamDecl(p)->hasDefaultArg())
285 break;
286
287 OldParam = Older->getParamDecl(p);
288 }
289
290 Diag(OldParam->getLocation(), diag::note_previous_definition)
291 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000292 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000293 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000294 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000295 if (OldParam->hasUninstantiatedDefaultArg())
296 NewParam->setUninstantiatedDefaultArg(
297 OldParam->getUninstantiatedDefaultArg());
298 else
299 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000300 } else if (NewParam->hasDefaultArg()) {
301 if (New->getDescribedFunctionTemplate()) {
302 // Paragraph 4, quoted above, only applies to non-template functions.
303 Diag(NewParam->getLocation(),
304 diag::err_param_default_argument_template_redecl)
305 << NewParam->getDefaultArgRange();
306 Diag(Old->getLocation(), diag::note_template_prev_declaration)
307 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000308 } else if (New->getTemplateSpecializationKind()
309 != TSK_ImplicitInstantiation &&
310 New->getTemplateSpecializationKind() != TSK_Undeclared) {
311 // C++ [temp.expr.spec]p21:
312 // Default function arguments shall not be specified in a declaration
313 // or a definition for one of the following explicit specializations:
314 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000315 // - the explicit specialization of a member function template;
316 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000317 // template where the class template specialization to which the
318 // member function specialization belongs is implicitly
319 // instantiated.
320 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
321 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
322 << New->getDeclName()
323 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000324 } else if (New->getDeclContext()->isDependentContext()) {
325 // C++ [dcl.fct.default]p6 (DR217):
326 // Default arguments for a member function of a class template shall
327 // be specified on the initial declaration of the member function
328 // within the class template.
329 //
330 // Reading the tea leaves a bit in DR217 and its reference to DR205
331 // leads me to the conclusion that one cannot add default function
332 // arguments for an out-of-line definition of a member function of a
333 // dependent type.
334 int WhichKind = 2;
335 if (CXXRecordDecl *Record
336 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
337 if (Record->getDescribedClassTemplate())
338 WhichKind = 0;
339 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
340 WhichKind = 1;
341 else
342 WhichKind = 2;
343 }
344
345 Diag(NewParam->getLocation(),
346 diag::err_param_default_argument_member_template_redecl)
347 << WhichKind
348 << NewParam->getDefaultArgRange();
349 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000350 }
351 }
352
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000353 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000354 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000355 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000356 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000357
Douglas Gregorcda9c672009-02-16 17:45:42 +0000358 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000359}
360
361/// CheckCXXDefaultArguments - Verify that the default arguments for a
362/// function declaration are well-formed according to C++
363/// [dcl.fct.default].
364void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
365 unsigned NumParams = FD->getNumParams();
366 unsigned p;
367
368 // Find first parameter with a default argument
369 for (p = 0; p < NumParams; ++p) {
370 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000371 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000372 break;
373 }
374
375 // C++ [dcl.fct.default]p4:
376 // In a given function declaration, all parameters
377 // subsequent to a parameter with a default argument shall
378 // have default arguments supplied in this or previous
379 // declarations. A default argument shall not be redefined
380 // by a later declaration (not even to the same value).
381 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000382 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000384 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000385 if (Param->isInvalidDecl())
386 /* We already complained about this parameter. */;
387 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000388 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000389 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000390 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000391 else
Mike Stump1eb44332009-09-09 15:08:12 +0000392 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000393 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner3d1cee32008-04-08 05:04:30 +0000395 LastMissingDefaultArg = p;
396 }
397 }
398
399 if (LastMissingDefaultArg > 0) {
400 // Some default arguments were missing. Clear out all of the
401 // default arguments up to (and including) the last missing
402 // default argument, so that we leave the function parameters
403 // in a semantically valid state.
404 for (p = 0; p <= LastMissingDefaultArg; ++p) {
405 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000406 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000407 if (!Param->hasUnparsedDefaultArg())
408 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000409 Param->setDefaultArg(0);
410 }
411 }
412 }
413}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000414
Douglas Gregorb48fe382008-10-31 09:07:45 +0000415/// isCurrentClassName - Determine whether the identifier II is the
416/// name of the class type currently being defined. In the case of
417/// nested classes, this will only return true if II is the name of
418/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000419bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
420 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000421 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000422 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000423 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000424 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
425 } else
426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
427
428 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000429 return &II == CurDecl->getIdentifier();
430 else
431 return false;
432}
433
Mike Stump1eb44332009-09-09 15:08:12 +0000434/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000435///
436/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
437/// and returns NULL otherwise.
438CXXBaseSpecifier *
439Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
440 SourceRange SpecifierRange,
441 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000442 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000443 SourceLocation BaseLoc) {
444 // C++ [class.union]p1:
445 // A union shall not have base classes.
446 if (Class->isUnion()) {
447 Diag(Class->getLocation(), diag::err_base_clause_on_union)
448 << SpecifierRange;
449 return 0;
450 }
451
452 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000453 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000454 Class->getTagKind() == RecordDecl::TK_class,
455 Access, BaseType);
456
457 // Base specifiers must be record types.
458 if (!BaseType->isRecordType()) {
459 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
460 return 0;
461 }
462
463 // C++ [class.union]p1:
464 // A union shall not be used as a base class.
465 if (BaseType->isUnionType()) {
466 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
467 return 0;
468 }
469
470 // C++ [class.derived]p2:
471 // The class-name in a base-specifier shall not be an incompletely
472 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000473 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000474 PDiag(diag::err_incomplete_base_class)
475 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000476 return 0;
477
Eli Friedman1d954f62009-08-15 21:55:26 +0000478 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000479 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000480 assert(BaseDecl && "Record type has no declaration");
481 BaseDecl = BaseDecl->getDefinition(Context);
482 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000483 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
484 assert(CXXBaseDecl && "Base type is not a C++ type");
485 if (!CXXBaseDecl->isEmpty())
486 Class->setEmpty(false);
487 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000488 Class->setPolymorphic(true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000489 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
490 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
491 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000492 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
493 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000494 return 0;
495 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000496
497 // C++ [dcl.init.aggr]p1:
498 // An aggregate is [...] a class with [...] no base classes [...].
499 Class->setAggregate(false);
500 Class->setPOD(false);
501
Anders Carlsson347ba892009-04-16 00:08:20 +0000502 if (Virtual) {
503 // C++ [class.ctor]p5:
504 // A constructor is trivial if its class has no virtual base classes.
505 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000506
507 // C++ [class.copy]p6:
508 // A copy constructor is trivial if its class has no virtual base classes.
509 Class->setHasTrivialCopyConstructor(false);
510
511 // C++ [class.copy]p11:
512 // A copy assignment operator is trivial if its class has no virtual
513 // base classes.
514 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000515
516 // C++0x [meta.unary.prop] is_empty:
517 // T is a class type, but not a union type, with ... no virtual base
518 // classes
519 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000520 } else {
521 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000522 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000523 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000524 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
525 Class->setHasTrivialConstructor(false);
526
527 // C++ [class.copy]p6:
528 // A copy constructor is trivial if all the direct base classes of its
529 // class have trivial copy constructors.
530 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
531 Class->setHasTrivialCopyConstructor(false);
532
533 // C++ [class.copy]p11:
534 // A copy assignment operator is trivial if all the direct base classes
535 // of its class have trivial copy assignment operators.
536 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
537 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000538 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000539
540 // C++ [class.ctor]p3:
541 // A destructor is trivial if all the direct base classes of its class
542 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000543 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
544 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Douglas Gregor2943aed2009-03-03 04:44:36 +0000546 // Create the base specifier.
547 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000548 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
549 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000550 Access, BaseType);
551}
552
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000553/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
554/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000555/// example:
556/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000557/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000558Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000559Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000560 bool Virtual, AccessSpecifier Access,
561 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000562 if (!classdecl)
563 return true;
564
Douglas Gregor40808ce2009-03-09 23:48:35 +0000565 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000566 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000567 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000568 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
569 Virtual, Access,
570 BaseType, BaseLoc))
571 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Douglas Gregor2943aed2009-03-03 04:44:36 +0000573 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000574}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000575
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576/// \brief Performs the actual work of attaching the given base class
577/// specifiers to a C++ class.
578bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
579 unsigned NumBases) {
580 if (NumBases == 0)
581 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000582
583 // Used to keep track of which base types we have already seen, so
584 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000585 // that the key is always the unqualified canonical type of the base
586 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000587 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
588
589 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000590 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000592 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000593 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000595 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000596
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000597 if (KnownBaseTypes[NewBaseType]) {
598 // C++ [class.mi]p3:
599 // A class shall not be specified as a direct base class of a
600 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000602 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000603 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000604 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000605
606 // Delete the duplicate base class specifier; we're going to
607 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000608 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609
610 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000611 } else {
612 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000613 KnownBaseTypes[NewBaseType] = Bases[idx];
614 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000615 }
616 }
617
618 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000619 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000620
621 // Delete the remaining (good) base class specifiers, since their
622 // data has been copied into the CXXRecordDecl.
623 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000624 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000625
626 return Invalid;
627}
628
629/// ActOnBaseSpecifiers - Attach the given base specifiers to the
630/// class, after checking whether there are any duplicate base
631/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000632void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633 unsigned NumBases) {
634 if (!ClassDecl || !Bases || !NumBases)
635 return;
636
637 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000638 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000640}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000641
Douglas Gregora8f32e02009-10-06 17:59:45 +0000642/// \brief Determine whether the type \p Derived is a C++ class that is
643/// derived from the type \p Base.
644bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
645 if (!getLangOptions().CPlusPlus)
646 return false;
647
648 const RecordType *DerivedRT = Derived->getAs<RecordType>();
649 if (!DerivedRT)
650 return false;
651
652 const RecordType *BaseRT = Base->getAs<RecordType>();
653 if (!BaseRT)
654 return false;
655
656 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
657 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
658 return DerivedRD->isDerivedFrom(BaseRD);
659}
660
661/// \brief Determine whether the type \p Derived is a C++ class that is
662/// derived from the type \p Base.
663bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
664 if (!getLangOptions().CPlusPlus)
665 return false;
666
667 const RecordType *DerivedRT = Derived->getAs<RecordType>();
668 if (!DerivedRT)
669 return false;
670
671 const RecordType *BaseRT = Base->getAs<RecordType>();
672 if (!BaseRT)
673 return false;
674
675 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
676 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
677 return DerivedRD->isDerivedFrom(BaseRD, Paths);
678}
679
680/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
681/// conversion (where Derived and Base are class types) is
682/// well-formed, meaning that the conversion is unambiguous (and
683/// that all of the base classes are accessible). Returns true
684/// and emits a diagnostic if the code is ill-formed, returns false
685/// otherwise. Loc is the location where this routine should point to
686/// if there is an error, and Range is the source range to highlight
687/// if there is an error.
688bool
689Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
690 unsigned InaccessibleBaseID,
691 unsigned AmbigiousBaseConvID,
692 SourceLocation Loc, SourceRange Range,
693 DeclarationName Name) {
694 // First, determine whether the path from Derived to Base is
695 // ambiguous. This is slightly more expensive than checking whether
696 // the Derived to Base conversion exists, because here we need to
697 // explore multiple paths to determine if there is an ambiguity.
698 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
699 /*DetectVirtual=*/false);
700 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
701 assert(DerivationOkay &&
702 "Can only be used with a derived-to-base conversion");
703 (void)DerivationOkay;
704
705 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000706 if (InaccessibleBaseID == 0)
707 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000708 // Check that the base class can be accessed.
709 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
710 Name);
711 }
712
713 // We know that the derived-to-base conversion is ambiguous, and
714 // we're going to produce a diagnostic. Perform the derived-to-base
715 // search just one more time to compute all of the possible paths so
716 // that we can print them out. This is more expensive than any of
717 // the previous derived-to-base checks we've done, but at this point
718 // performance isn't as much of an issue.
719 Paths.clear();
720 Paths.setRecordingPaths(true);
721 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
722 assert(StillOkay && "Can only be used with a derived-to-base conversion");
723 (void)StillOkay;
724
725 // Build up a textual representation of the ambiguous paths, e.g.,
726 // D -> B -> A, that will be used to illustrate the ambiguous
727 // conversions in the diagnostic. We only print one of the paths
728 // to each base class subobject.
729 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
730
731 Diag(Loc, AmbigiousBaseConvID)
732 << Derived << Base << PathDisplayStr << Range << Name;
733 return true;
734}
735
736bool
737Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000738 SourceLocation Loc, SourceRange Range,
739 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000740 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000741 IgnoreAccess ? 0 :
742 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000743 diag::err_ambiguous_derived_to_base_conv,
744 Loc, Range, DeclarationName());
745}
746
747
748/// @brief Builds a string representing ambiguous paths from a
749/// specific derived class to different subobjects of the same base
750/// class.
751///
752/// This function builds a string that can be used in error messages
753/// to show the different paths that one can take through the
754/// inheritance hierarchy to go from the derived class to different
755/// subobjects of a base class. The result looks something like this:
756/// @code
757/// struct D -> struct B -> struct A
758/// struct D -> struct C -> struct A
759/// @endcode
760std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
761 std::string PathDisplayStr;
762 std::set<unsigned> DisplayedPaths;
763 for (CXXBasePaths::paths_iterator Path = Paths.begin();
764 Path != Paths.end(); ++Path) {
765 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
766 // We haven't displayed a path to this particular base
767 // class subobject yet.
768 PathDisplayStr += "\n ";
769 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
770 for (CXXBasePath::const_iterator Element = Path->begin();
771 Element != Path->end(); ++Element)
772 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
773 }
774 }
775
776 return PathDisplayStr;
777}
778
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000779//===----------------------------------------------------------------------===//
780// C++ class member Handling
781//===----------------------------------------------------------------------===//
782
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000783/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
784/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
785/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000786/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000787Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000788Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000789 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000790 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
791 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000792 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000793 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000794 Expr *BitWidth = static_cast<Expr*>(BW);
795 Expr *Init = static_cast<Expr*>(InitExpr);
796 SourceLocation Loc = D.getIdentifierLoc();
797
Sebastian Redl669d5d72008-11-14 23:42:31 +0000798 bool isFunc = D.isFunctionDeclarator();
799
John McCall67d1a672009-08-06 02:15:43 +0000800 assert(!DS.isFriendSpecified());
801
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000802 // C++ 9.2p6: A member shall not be declared to have automatic storage
803 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000804 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
805 // data members and cannot be applied to names declared const or static,
806 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000807 switch (DS.getStorageClassSpec()) {
808 case DeclSpec::SCS_unspecified:
809 case DeclSpec::SCS_typedef:
810 case DeclSpec::SCS_static:
811 // FALL THROUGH.
812 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000813 case DeclSpec::SCS_mutable:
814 if (isFunc) {
815 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000816 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000817 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000818 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Sebastian Redla11f42f2008-11-17 23:24:37 +0000820 // FIXME: It would be nicer if the keyword was ignored only for this
821 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000822 D.getMutableDeclSpec().ClearStorageClassSpecs();
823 } else {
824 QualType T = GetTypeForDeclarator(D, S);
825 diag::kind err = static_cast<diag::kind>(0);
826 if (T->isReferenceType())
827 err = diag::err_mutable_reference;
828 else if (T.isConstQualified())
829 err = diag::err_mutable_const;
830 if (err != 0) {
831 if (DS.getStorageClassSpecLoc().isValid())
832 Diag(DS.getStorageClassSpecLoc(), err);
833 else
834 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000835 // FIXME: It would be nicer if the keyword was ignored only for this
836 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000837 D.getMutableDeclSpec().ClearStorageClassSpecs();
838 }
839 }
840 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000841 default:
842 if (DS.getStorageClassSpecLoc().isValid())
843 Diag(DS.getStorageClassSpecLoc(),
844 diag::err_storageclass_invalid_for_member);
845 else
846 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
847 D.getMutableDeclSpec().ClearStorageClassSpecs();
848 }
849
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000850 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000851 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000852 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000853 // Check also for this case:
854 //
855 // typedef int f();
856 // f a;
857 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000858 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000859 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000860 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000861
Sebastian Redl669d5d72008-11-14 23:42:31 +0000862 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
863 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000864 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000865
866 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000867 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000868 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000869 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
870 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000871 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000872 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000873 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000874 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000875 if (!Member) {
876 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000877 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000878 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000879
880 // Non-instance-fields can't have a bitfield.
881 if (BitWidth) {
882 if (Member->isInvalidDecl()) {
883 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000884 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000885 // C++ 9.6p3: A bit-field shall not be a static member.
886 // "static member 'A' cannot be a bit-field"
887 Diag(Loc, diag::err_static_not_bitfield)
888 << Name << BitWidth->getSourceRange();
889 } else if (isa<TypedefDecl>(Member)) {
890 // "typedef member 'x' cannot be a bit-field"
891 Diag(Loc, diag::err_typedef_not_bitfield)
892 << Name << BitWidth->getSourceRange();
893 } else {
894 // A function typedef ("typedef int f(); f a;").
895 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
896 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000897 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000898 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner8b963ef2009-03-05 23:01:03 +0000901 DeleteExpr(BitWidth);
902 BitWidth = 0;
903 Member->setInvalidDecl();
904 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000905
906 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Douglas Gregor37b372b2009-08-20 22:52:58 +0000908 // If we have declared a member function template, set the access of the
909 // templated declaration as well.
910 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
911 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000912 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000913
Douglas Gregor10bd3682008-11-17 22:58:34 +0000914 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000915
Douglas Gregor021c3b32009-03-11 23:00:04 +0000916 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000917 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000918 if (Deleted) // FIXME: Source location is not very good.
919 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000920
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000921 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000922 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000923 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000924 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000925 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000926}
927
Douglas Gregor7ad83902008-11-05 04:29:56 +0000928/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000929Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000930Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000931 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000932 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000933 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000934 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000935 SourceLocation IdLoc,
936 SourceLocation LParenLoc,
937 ExprTy **Args, unsigned NumArgs,
938 SourceLocation *CommaLocs,
939 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000940 if (!ConstructorD)
941 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000943 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
945 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000946 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000947 if (!Constructor) {
948 // The user wrote a constructor initializer on a function that is
949 // not a C++ constructor. Ignore the error for now, because we may
950 // have more member initializers coming; we'll diagnose it just
951 // once in ActOnMemInitializers.
952 return true;
953 }
954
955 CXXRecordDecl *ClassDecl = Constructor->getParent();
956
957 // C++ [class.base.init]p2:
958 // Names in a mem-initializer-id are looked up in the scope of the
959 // constructor’s class and, if not found in that scope, are looked
960 // up in the scope containing the constructor’s
961 // definition. [Note: if the constructor’s class contains a member
962 // with the same name as a direct or virtual base class of the
963 // class, a mem-initializer-id naming the member or base class and
964 // composed of a single identifier refers to the class member. A
965 // mem-initializer-id for the hidden base class may be specified
966 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000967 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000968 // Look for a member, first.
969 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000970 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000971 = ClassDecl->lookup(MemberOrBase);
972 if (Result.first != Result.second)
973 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000974
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000975 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000976
Eli Friedman59c04372009-07-29 19:44:27 +0000977 if (Member)
978 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
979 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000980 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000981 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000982 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000983 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000984 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000985 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
986 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000988 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000989
Eli Friedman59c04372009-07-29 19:44:27 +0000990 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
991 RParenLoc, ClassDecl);
992}
993
John McCallb4190042009-11-04 23:02:40 +0000994/// Checks an initializer expression for use of uninitialized fields, such as
995/// containing the field that is being initialized. Returns true if there is an
996/// uninitialized field was used an updates the SourceLocation parameter; false
997/// otherwise.
998static bool InitExprContainsUninitializedFields(const Stmt* S,
999 const FieldDecl* LhsField,
1000 SourceLocation* L) {
1001 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1002 if (ME) {
1003 const NamedDecl* RhsField = ME->getMemberDecl();
1004 if (RhsField == LhsField) {
1005 // Initializing a field with itself. Throw a warning.
1006 // But wait; there are exceptions!
1007 // Exception #1: The field may not belong to this record.
1008 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1009 const Expr* base = ME->getBase();
1010 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1011 // Even though the field matches, it does not belong to this record.
1012 return false;
1013 }
1014 // None of the exceptions triggered; return true to indicate an
1015 // uninitialized field was used.
1016 *L = ME->getMemberLoc();
1017 return true;
1018 }
1019 }
1020 bool found = false;
1021 for (Stmt::const_child_iterator it = S->child_begin();
1022 it != S->child_end() && found == false;
1023 ++it) {
1024 if (isa<CallExpr>(S)) {
1025 // Do not descend into function calls or constructors, as the use
1026 // of an uninitialized field may be valid. One would have to inspect
1027 // the contents of the function/ctor to determine if it is safe or not.
1028 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1029 // may be safe, depending on what the function/ctor does.
1030 continue;
1031 }
1032 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1033 }
1034 return found;
1035}
1036
Eli Friedman59c04372009-07-29 19:44:27 +00001037Sema::MemInitResult
1038Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1039 unsigned NumArgs, SourceLocation IdLoc,
1040 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001041 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1042 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1043 ExprTemporaries.clear();
1044
John McCallb4190042009-11-04 23:02:40 +00001045 // Diagnose value-uses of fields to initialize themselves, e.g.
1046 // foo(foo)
1047 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001048 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001049 for (unsigned i = 0; i < NumArgs; ++i) {
1050 SourceLocation L;
1051 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1052 // FIXME: Return true in the case when other fields are used before being
1053 // uninitialized. For example, let this field be the i'th field. When
1054 // initializing the i'th field, throw a warning if any of the >= i'th
1055 // fields are used, as they are not yet initialized.
1056 // Right now we are only handling the case where the i'th field uses
1057 // itself in its initializer.
1058 Diag(L, diag::warn_field_is_uninit);
1059 }
1060 }
1061
Eli Friedman59c04372009-07-29 19:44:27 +00001062 bool HasDependentArg = false;
1063 for (unsigned i = 0; i < NumArgs; i++)
1064 HasDependentArg |= Args[i]->isTypeDependent();
1065
1066 CXXConstructorDecl *C = 0;
1067 QualType FieldType = Member->getType();
1068 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1069 FieldType = Array->getElementType();
1070 if (FieldType->isDependentType()) {
1071 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001072 } else if (FieldType->isRecordType()) {
1073 // Member is a record (struct/union/class), so pass the initializer
1074 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001075 if (!HasDependentArg) {
1076 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1077
1078 C = PerformInitializationByConstructor(FieldType,
1079 MultiExprArg(*this,
1080 (void**)Args,
1081 NumArgs),
1082 IdLoc,
1083 SourceRange(IdLoc, RParenLoc),
1084 Member->getDeclName(), IK_Direct,
1085 ConstructorArgs);
1086
1087 if (C) {
1088 // Take over the constructor arguments as our own.
1089 NumArgs = ConstructorArgs.size();
1090 Args = (Expr **)ConstructorArgs.take();
1091 }
1092 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001093 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001094 // The member type is not a record type (or an array of record
1095 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001096 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001097 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1098 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001099 Expr *NewExp;
1100 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001101 if (FieldType->isReferenceType()) {
1102 Diag(IdLoc, diag::err_null_intialized_reference_member)
1103 << Member->getDeclName();
1104 return Diag(Member->getLocation(), diag::note_declared_at);
1105 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001106 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1107 NumArgs = 1;
1108 }
1109 else
1110 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001111 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1112 return true;
1113 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001114 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001115
1116 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1117 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1118 ExprTemporaries.clear();
1119
Eli Friedman59c04372009-07-29 19:44:27 +00001120 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001121 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001122 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001123}
1124
1125Sema::MemInitResult
1126Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1127 unsigned NumArgs, SourceLocation IdLoc,
1128 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1129 bool HasDependentArg = false;
1130 for (unsigned i = 0; i < NumArgs; i++)
1131 HasDependentArg |= Args[i]->isTypeDependent();
1132
1133 if (!BaseType->isDependentType()) {
1134 if (!BaseType->isRecordType())
1135 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1136 << BaseType << SourceRange(IdLoc, RParenLoc);
1137
1138 // C++ [class.base.init]p2:
1139 // [...] Unless the mem-initializer-id names a nonstatic data
1140 // member of the constructor’s class or a direct or virtual base
1141 // of that class, the mem-initializer is ill-formed. A
1142 // mem-initializer-list can initialize a base class using any
1143 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Eli Friedman59c04372009-07-29 19:44:27 +00001145 // First, check for a direct base class.
1146 const CXXBaseSpecifier *DirectBaseSpec = 0;
1147 for (CXXRecordDecl::base_class_const_iterator Base =
1148 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001149 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001150 // We found a direct base of this type. That's what we're
1151 // initializing.
1152 DirectBaseSpec = &*Base;
1153 break;
1154 }
1155 }
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Eli Friedman59c04372009-07-29 19:44:27 +00001157 // Check for a virtual base class.
1158 // FIXME: We might be able to short-circuit this if we know in advance that
1159 // there are no virtual bases.
1160 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1161 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1162 // We haven't found a base yet; search the class hierarchy for a
1163 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1165 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001166 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001167 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001168 Path != Paths.end(); ++Path) {
1169 if (Path->back().Base->isVirtual()) {
1170 VirtualBaseSpec = Path->back().Base;
1171 break;
1172 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001173 }
1174 }
1175 }
Eli Friedman59c04372009-07-29 19:44:27 +00001176
1177 // C++ [base.class.init]p2:
1178 // If a mem-initializer-id is ambiguous because it designates both
1179 // a direct non-virtual base class and an inherited virtual base
1180 // class, the mem-initializer is ill-formed.
1181 if (DirectBaseSpec && VirtualBaseSpec)
1182 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1183 << BaseType << SourceRange(IdLoc, RParenLoc);
1184 // C++ [base.class.init]p2:
1185 // Unless the mem-initializer-id names a nonstatic data membeer of the
1186 // constructor's class ot a direst or virtual base of that class, the
1187 // mem-initializer is ill-formed.
1188 if (!DirectBaseSpec && !VirtualBaseSpec)
1189 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1190 << BaseType << ClassDecl->getNameAsCString()
1191 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001192 }
1193
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001194 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001195 if (!BaseType->isDependentType() && !HasDependentArg) {
1196 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001197 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001198 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1199
1200 C = PerformInitializationByConstructor(BaseType,
1201 MultiExprArg(*this,
1202 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001203 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001204 Name, IK_Direct,
1205 ConstructorArgs);
1206 if (C) {
1207 // Take over the constructor arguments as our own.
1208 NumArgs = ConstructorArgs.size();
1209 Args = (Expr **)ConstructorArgs.take();
1210 }
Eli Friedman59c04372009-07-29 19:44:27 +00001211 }
1212
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001213 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1214 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1215 ExprTemporaries.clear();
1216
Mike Stump1eb44332009-09-09 15:08:12 +00001217 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001218 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001219}
1220
Eli Friedman80c30da2009-11-09 19:20:36 +00001221bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001222Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001223 CXXBaseOrMemberInitializer **Initializers,
1224 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001225 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001226 // We need to build the initializer AST according to order of construction
1227 // and not what user specified in the Initializers list.
1228 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1229 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1230 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1231 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001232 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001234 for (unsigned i = 0; i < NumInitializers; i++) {
1235 CXXBaseOrMemberInitializer *Member = Initializers[i];
1236 if (Member->isBaseInitializer()) {
1237 if (Member->getBaseClass()->isDependentType())
1238 HasDependentBaseInit = true;
1239 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1240 } else {
1241 AllBaseFields[Member->getMember()] = Member;
1242 }
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001245 if (HasDependentBaseInit) {
1246 // FIXME. This does not preserve the ordering of the initializers.
1247 // Try (with -Wreorder)
1248 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001249 // template<class X> struct B : A<X> {
1250 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001251 // int x1;
1252 // };
1253 // B<int> x;
1254 // On seeing one dependent type, we should essentially exit this routine
1255 // while preserving user-declared initializer list. When this routine is
1256 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001257 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001259 // If we have a dependent base initialization, we can't determine the
1260 // association between initializers and bases; just dump the known
1261 // initializers into the list, and don't try to deal with other bases.
1262 for (unsigned i = 0; i < NumInitializers; i++) {
1263 CXXBaseOrMemberInitializer *Member = Initializers[i];
1264 if (Member->isBaseInitializer())
1265 AllToInit.push_back(Member);
1266 }
1267 } else {
1268 // Push virtual bases before others.
1269 for (CXXRecordDecl::base_class_iterator VBase =
1270 ClassDecl->vbases_begin(),
1271 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1272 if (VBase->getType()->isDependentType())
1273 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001274 if (CXXBaseOrMemberInitializer *Value
1275 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001276 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001277 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001278 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001279 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001280 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001281 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001282 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001283 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001284 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1285 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1286 << 0 << VBase->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001287 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001288 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001289 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001290 continue;
1291 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001292
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001293 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1294 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1295 Constructor->getLocation(), CtorArgs))
1296 continue;
1297
1298 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1299
Anders Carlsson8db68da2009-11-13 20:11:49 +00001300 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1301 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1302 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001303 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001304 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1305 CtorArgs.takeAs<Expr>(),
1306 CtorArgs.size(), Ctor,
1307 SourceLocation(),
1308 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001309 AllToInit.push_back(Member);
1310 }
1311 }
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001313 for (CXXRecordDecl::base_class_iterator Base =
1314 ClassDecl->bases_begin(),
1315 E = ClassDecl->bases_end(); Base != E; ++Base) {
1316 // Virtuals are in the virtual base list and already constructed.
1317 if (Base->isVirtual())
1318 continue;
1319 // Skip dependent types.
1320 if (Base->getType()->isDependentType())
1321 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001322 if (CXXBaseOrMemberInitializer *Value
1323 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001324 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001325 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001326 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001327 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001328 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001329 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001330 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001331 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001332 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1333 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1334 << 0 << Base->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001335 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001336 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001337 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001338 continue;
1339 }
1340
1341 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1342 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1343 Constructor->getLocation(), CtorArgs))
1344 continue;
1345
1346 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001347
Anders Carlsson8db68da2009-11-13 20:11:49 +00001348 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1349 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1350 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001351 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001352 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1353 CtorArgs.takeAs<Expr>(),
1354 CtorArgs.size(), Ctor,
1355 SourceLocation(),
1356 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001357 AllToInit.push_back(Member);
1358 }
1359 }
1360 }
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001362 // non-static data members.
1363 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1364 E = ClassDecl->field_end(); Field != E; ++Field) {
1365 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001366 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001367 Field->getType()->getAs<RecordType>()) {
1368 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001369 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001370 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001371 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1372 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1373 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1374 // set to the anonymous union data member used in the initializer
1375 // list.
1376 Value->setMember(*Field);
1377 Value->setAnonUnionMember(*FA);
1378 AllToInit.push_back(Value);
1379 break;
1380 }
1381 }
1382 }
1383 continue;
1384 }
1385 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1386 AllToInit.push_back(Value);
1387 continue;
1388 }
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Eli Friedman49c16da2009-11-09 01:05:47 +00001390 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001391 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001392
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001393 QualType FT = Context.getBaseElementType((*Field)->getType());
1394 if (const RecordType* RT = FT->getAs<RecordType>()) {
1395 CXXConstructorDecl *Ctor =
1396 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001397 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001398 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1399 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1400 << 1 << (*Field)->getDeclName();
1401 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001402 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001403 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001404 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001405 continue;
1406 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001407
1408 if (FT.isConstQualified() && Ctor->isTrivial()) {
1409 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1410 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1411 << 1 << (*Field)->getDeclName();
1412 Diag((*Field)->getLocation(), diag::note_declared_at);
1413 HadError = true;
1414 }
1415
1416 // Don't create initializers for trivial constructors, since they don't
1417 // actually need to be run.
1418 if (Ctor->isTrivial())
1419 continue;
1420
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001421 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1422 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1423 Constructor->getLocation(), CtorArgs))
1424 continue;
1425
Anders Carlsson8db68da2009-11-13 20:11:49 +00001426 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1427 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1428 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001429 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001430 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1431 CtorArgs.size(), Ctor,
1432 SourceLocation(),
1433 SourceLocation());
1434
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001435 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001436 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001437 }
1438 else if (FT->isReferenceType()) {
1439 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001440 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1441 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001442 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001443 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001444 }
1445 else if (FT.isConstQualified()) {
1446 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001447 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1448 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001449 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001450 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001451 }
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001454 NumInitializers = AllToInit.size();
1455 if (NumInitializers > 0) {
1456 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1457 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1458 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001460 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1461 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1462 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1463 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001464
1465 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001466}
1467
Eli Friedman6347f422009-07-21 19:28:10 +00001468static void *GetKeyForTopLevelField(FieldDecl *Field) {
1469 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001470 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001471 if (RT->getDecl()->isAnonymousStructOrUnion())
1472 return static_cast<void *>(RT->getDecl());
1473 }
1474 return static_cast<void *>(Field);
1475}
1476
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001477static void *GetKeyForBase(QualType BaseType) {
1478 if (const RecordType *RT = BaseType->getAs<RecordType>())
1479 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001481 assert(0 && "Unexpected base type!");
1482 return 0;
1483}
1484
Mike Stump1eb44332009-09-09 15:08:12 +00001485static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001486 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001487 // For fields injected into the class via declaration of an anonymous union,
1488 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001489 if (Member->isMemberInitializer()) {
1490 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Eli Friedman49c16da2009-11-09 01:05:47 +00001492 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001493 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001494 // in AnonUnionMember field.
1495 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1496 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001497 if (Field->getDeclContext()->isRecord()) {
1498 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1499 if (RD->isAnonymousStructOrUnion())
1500 return static_cast<void *>(RD);
1501 }
1502 return static_cast<void *>(Field);
1503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001505 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001506}
1507
John McCall6aee6212009-11-04 23:13:52 +00001508/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001509void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001510 SourceLocation ColonLoc,
1511 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001512 if (!ConstructorDecl)
1513 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001514
1515 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
1517 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001518 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Anders Carlssona7b35212009-03-25 02:58:17 +00001520 if (!Constructor) {
1521 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1522 return;
1523 }
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001525 if (!Constructor->isDependentContext()) {
1526 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1527 bool err = false;
1528 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001529 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001530 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1531 void *KeyToMember = GetKeyForMember(Member);
1532 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1533 if (!PrevMember) {
1534 PrevMember = Member;
1535 continue;
1536 }
1537 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001538 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001539 diag::error_multiple_mem_initialization)
1540 << Field->getNameAsString();
1541 else {
1542 Type *BaseClass = Member->getBaseClass();
1543 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001544 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001545 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001546 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001547 }
1548 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1549 << 0;
1550 err = true;
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001553 if (err)
1554 return;
1555 }
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Eli Friedman49c16da2009-11-09 01:05:47 +00001557 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001558 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001559 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001561 if (Constructor->isDependentContext())
1562 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
1564 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001565 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001566 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001567 Diagnostic::Ignored)
1568 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001570 // Also issue warning if order of ctor-initializer list does not match order
1571 // of 1) base class declarations and 2) order of non-static data members.
1572 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001574 CXXRecordDecl *ClassDecl
1575 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1576 // Push virtual bases before others.
1577 for (CXXRecordDecl::base_class_iterator VBase =
1578 ClassDecl->vbases_begin(),
1579 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001580 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001582 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1583 E = ClassDecl->bases_end(); Base != E; ++Base) {
1584 // Virtuals are alread in the virtual base list and are constructed
1585 // first.
1586 if (Base->isVirtual())
1587 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001588 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1592 E = ClassDecl->field_end(); Field != E; ++Field)
1593 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001595 int Last = AllBaseOrMembers.size();
1596 int curIndex = 0;
1597 CXXBaseOrMemberInitializer *PrevMember = 0;
1598 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001599 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001600 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1601 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001602
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001603 for (; curIndex < Last; curIndex++)
1604 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1605 break;
1606 if (curIndex == Last) {
1607 assert(PrevMember && "Member not in member list?!");
1608 // Initializer as specified in ctor-initializer list is out of order.
1609 // Issue a warning diagnostic.
1610 if (PrevMember->isBaseInitializer()) {
1611 // Diagnostics is for an initialized base class.
1612 Type *BaseClass = PrevMember->getBaseClass();
1613 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001614 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001615 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001616 } else {
1617 FieldDecl *Field = PrevMember->getMember();
1618 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001619 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001620 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001621 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001622 // Also the note!
1623 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001624 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001625 diag::note_fieldorbase_initialized_here) << 0
1626 << Field->getNameAsString();
1627 else {
1628 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001629 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001630 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001631 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001632 }
1633 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001634 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001635 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001636 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001637 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001638 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001639}
1640
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001641void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001642Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1643 // Ignore dependent destructors.
1644 if (Destructor->isDependentContext())
1645 return;
1646
1647 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Anders Carlsson9f853df2009-11-17 04:44:12 +00001649 // Non-static data members.
1650 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1651 E = ClassDecl->field_end(); I != E; ++I) {
1652 FieldDecl *Field = *I;
1653
1654 QualType FieldType = Context.getBaseElementType(Field->getType());
1655
1656 const RecordType* RT = FieldType->getAs<RecordType>();
1657 if (!RT)
1658 continue;
1659
1660 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1661 if (FieldClassDecl->hasTrivialDestructor())
1662 continue;
1663
1664 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1665 MarkDeclarationReferenced(Destructor->getLocation(),
1666 const_cast<CXXDestructorDecl*>(Dtor));
1667 }
1668
1669 // Bases.
1670 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1671 E = ClassDecl->bases_end(); Base != E; ++Base) {
1672 // Ignore virtual bases.
1673 if (Base->isVirtual())
1674 continue;
1675
1676 // Ignore trivial destructors.
1677 CXXRecordDecl *BaseClassDecl
1678 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1679 if (BaseClassDecl->hasTrivialDestructor())
1680 continue;
1681
1682 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1683 MarkDeclarationReferenced(Destructor->getLocation(),
1684 const_cast<CXXDestructorDecl*>(Dtor));
1685 }
1686
1687 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001688 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1689 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001690 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001691 CXXRecordDecl *BaseClassDecl
1692 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1693 if (BaseClassDecl->hasTrivialDestructor())
1694 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001695
1696 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1697 MarkDeclarationReferenced(Destructor->getLocation(),
1698 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001699 }
1700}
1701
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001702void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001703 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001704 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001706 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
1708 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001709 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001710 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001711}
1712
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001713namespace {
1714 /// PureVirtualMethodCollector - traverses a class and its superclasses
1715 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001716 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001717 ASTContext &Context;
1718
Sebastian Redldfe292d2009-03-22 21:28:55 +00001719 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001720 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001721
1722 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001723 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001725 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001727 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001728 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001729 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001731 MethodList List;
1732 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001734 // Copy the temporary list to methods, and make sure to ignore any
1735 // null entries.
1736 for (size_t i = 0, e = List.size(); i != e; ++i) {
1737 if (List[i])
1738 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001739 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001740 }
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001742 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001744 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1745 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001746 };
Mike Stump1eb44332009-09-09 15:08:12 +00001747
1748 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001749 MethodList& Methods) {
1750 // First, collect the pure virtual methods for the base classes.
1751 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1752 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001753 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001754 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001755 if (BaseDecl && BaseDecl->isAbstract())
1756 Collect(BaseDecl, Methods);
1757 }
1758 }
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001760 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001761 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001763 MethodSetTy OverriddenMethods;
1764 size_t MethodsSize = Methods.size();
1765
Mike Stump1eb44332009-09-09 15:08:12 +00001766 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001767 i != e; ++i) {
1768 // Traverse the record, looking for methods.
1769 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001770 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001771 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001772 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Anders Carlsson27823022009-10-18 19:34:08 +00001774 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001775 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1776 E = MD->end_overridden_methods(); I != E; ++I) {
1777 // Keep track of the overridden methods.
1778 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001779 }
1780 }
1781 }
Mike Stump1eb44332009-09-09 15:08:12 +00001782
1783 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001784 // overridden.
1785 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1786 if (OverriddenMethods.count(Methods[i]))
1787 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001790 }
1791}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001792
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001793
Mike Stump1eb44332009-09-09 15:08:12 +00001794bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001795 unsigned DiagID, AbstractDiagSelID SelID,
1796 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001797 if (SelID == -1)
1798 return RequireNonAbstractType(Loc, T,
1799 PDiag(DiagID), CurrentRD);
1800 else
1801 return RequireNonAbstractType(Loc, T,
1802 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001803}
1804
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001805bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1806 const PartialDiagnostic &PD,
1807 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001808 if (!getLangOptions().CPlusPlus)
1809 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Anders Carlsson11f21a02009-03-23 19:10:31 +00001811 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001812 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001813 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Ted Kremenek6217b802009-07-29 21:53:49 +00001815 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001816 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001818 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001820 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001821 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001822 }
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Ted Kremenek6217b802009-07-29 21:53:49 +00001824 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001825 if (!RT)
1826 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001828 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1829 if (!RD)
1830 return false;
1831
Anders Carlssone65a3c82009-03-24 17:23:42 +00001832 if (CurrentRD && CurrentRD != RD)
1833 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001835 if (!RD->isAbstract())
1836 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001838 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001840 // Check if we've already emitted the list of pure virtual functions for this
1841 // class.
1842 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1843 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001845 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
1847 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001848 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1849 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001850
1851 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001852 MD->getDeclName();
1853 }
1854
1855 if (!PureVirtualClassDiagSet)
1856 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1857 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001859 return true;
1860}
1861
Anders Carlsson8211eff2009-03-24 01:19:16 +00001862namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00001863 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001864 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1865 Sema &SemaRef;
1866 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Anders Carlssone65a3c82009-03-24 17:23:42 +00001868 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001869 bool Invalid = false;
1870
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001871 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1872 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001873 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001874
Anders Carlsson8211eff2009-03-24 01:19:16 +00001875 return Invalid;
1876 }
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Anders Carlssone65a3c82009-03-24 17:23:42 +00001878 public:
1879 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1880 : SemaRef(SemaRef), AbstractClass(ac) {
1881 Visit(SemaRef.Context.getTranslationUnitDecl());
1882 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001883
Anders Carlssone65a3c82009-03-24 17:23:42 +00001884 bool VisitFunctionDecl(const FunctionDecl *FD) {
1885 if (FD->isThisDeclarationADefinition()) {
1886 // No need to do the check if we're in a definition, because it requires
1887 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001888 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001889 return VisitDeclContext(FD);
1890 }
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Anders Carlssone65a3c82009-03-24 17:23:42 +00001892 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001893 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001894 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001895 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1896 diag::err_abstract_type_in_decl,
1897 Sema::AbstractReturnType,
1898 AbstractClass);
1899
Mike Stump1eb44332009-09-09 15:08:12 +00001900 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001901 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001902 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001903 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001904 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001905 VD->getOriginalType(),
1906 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001907 Sema::AbstractParamType,
1908 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001909 }
1910
1911 return Invalid;
1912 }
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlssone65a3c82009-03-24 17:23:42 +00001914 bool VisitDecl(const Decl* D) {
1915 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1916 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Anders Carlssone65a3c82009-03-24 17:23:42 +00001918 return false;
1919 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001920 };
1921}
1922
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001923void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001924 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001925 SourceLocation LBrac,
1926 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001927 if (!TagDecl)
1928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Douglas Gregor42af25f2009-05-11 19:58:34 +00001930 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001931 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001932 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001933 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001934
Chris Lattnerb28317a2009-03-28 19:18:32 +00001935 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001936 if (!RD->isAbstract()) {
1937 // Collect all the pure virtual methods and see if this is an abstract
1938 // class after all.
1939 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001940 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001941 RD->setAbstract(true);
1942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943
1944 if (RD->isAbstract())
Douglas Gregor6490ae52009-11-17 06:14:37 +00001945 (void)AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Douglas Gregor663b5a02009-10-14 20:14:33 +00001947 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001948 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001949}
1950
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001951/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1952/// special functions, such as the default constructor, copy
1953/// constructor, or destructor, to the given C++ class (C++
1954/// [special]p1). This routine can only be executed just before the
1955/// definition of the class is complete.
1956void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001957 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001958 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001959
Sebastian Redl465226e2009-05-27 22:11:52 +00001960 // FIXME: Implicit declarations have exception specifications, which are
1961 // the union of the specifications of the implicitly called functions.
1962
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001963 if (!ClassDecl->hasUserDeclaredConstructor()) {
1964 // C++ [class.ctor]p5:
1965 // A default constructor for a class X is a constructor of class X
1966 // that can be called without an argument. If there is no
1967 // user-declared constructor for class X, a default constructor is
1968 // implicitly declared. An implicitly-declared default constructor
1969 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001970 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001971 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001972 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001973 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001974 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001975 Context.getFunctionType(Context.VoidTy,
1976 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001977 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001978 /*isExplicit=*/false,
1979 /*isInline=*/true,
1980 /*isImplicitlyDeclared=*/true);
1981 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001982 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001983 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001984 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001985 }
1986
1987 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1988 // C++ [class.copy]p4:
1989 // If the class definition does not explicitly declare a copy
1990 // constructor, one is declared implicitly.
1991
1992 // C++ [class.copy]p5:
1993 // The implicitly-declared copy constructor for a class X will
1994 // have the form
1995 //
1996 // X::X(const X&)
1997 //
1998 // if
1999 bool HasConstCopyConstructor = true;
2000
2001 // -- each direct or virtual base class B of X has a copy
2002 // constructor whose first parameter is of type const B& or
2003 // const volatile B&, and
2004 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2005 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2006 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002007 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002008 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002009 = BaseClassDecl->hasConstCopyConstructor(Context);
2010 }
2011
2012 // -- for all the nonstatic data members of X that are of a
2013 // class type M (or array thereof), each such class type
2014 // has a copy constructor whose first parameter is of type
2015 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002016 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2017 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002018 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002019 QualType FieldType = (*Field)->getType();
2020 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2021 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002022 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002023 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002024 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002025 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002026 = FieldClassDecl->hasConstCopyConstructor(Context);
2027 }
2028 }
2029
Sebastian Redl64b45f72009-01-05 20:52:13 +00002030 // Otherwise, the implicitly declared copy constructor will have
2031 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002032 //
2033 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002034 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002035 if (HasConstCopyConstructor)
2036 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002037 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002038
Sebastian Redl64b45f72009-01-05 20:52:13 +00002039 // An implicitly-declared copy constructor is an inline public
2040 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002041 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002042 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002043 CXXConstructorDecl *CopyConstructor
2044 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002045 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002046 Context.getFunctionType(Context.VoidTy,
2047 &ArgType, 1,
2048 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002049 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002050 /*isExplicit=*/false,
2051 /*isInline=*/true,
2052 /*isImplicitlyDeclared=*/true);
2053 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002054 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002055 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002056
2057 // Add the parameter to the constructor.
2058 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2059 ClassDecl->getLocation(),
2060 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002061 ArgType, /*DInfo=*/0,
2062 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002063 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002064 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002065 }
2066
Sebastian Redl64b45f72009-01-05 20:52:13 +00002067 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2068 // Note: The following rules are largely analoguous to the copy
2069 // constructor rules. Note that virtual bases are not taken into account
2070 // for determining the argument type of the operator. Note also that
2071 // operators taking an object instead of a reference are allowed.
2072 //
2073 // C++ [class.copy]p10:
2074 // If the class definition does not explicitly declare a copy
2075 // assignment operator, one is declared implicitly.
2076 // The implicitly-defined copy assignment operator for a class X
2077 // will have the form
2078 //
2079 // X& X::operator=(const X&)
2080 //
2081 // if
2082 bool HasConstCopyAssignment = true;
2083
2084 // -- each direct base class B of X has a copy assignment operator
2085 // whose parameter is of type const B&, const volatile B& or B,
2086 // and
2087 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2088 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002089 assert(!Base->getType()->isDependentType() &&
2090 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002091 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002092 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002093 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002094 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002095 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002096 }
2097
2098 // -- for all the nonstatic data members of X that are of a class
2099 // type M (or array thereof), each such class type has a copy
2100 // assignment operator whose parameter is of type const M&,
2101 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002102 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2103 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002104 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002105 QualType FieldType = (*Field)->getType();
2106 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2107 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002108 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002109 const CXXRecordDecl *FieldClassDecl
2110 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002111 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002112 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002113 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002114 }
2115 }
2116
2117 // Otherwise, the implicitly declared copy assignment operator will
2118 // have the form
2119 //
2120 // X& X::operator=(X&)
2121 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002122 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002123 if (HasConstCopyAssignment)
2124 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002125 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002126
2127 // An implicitly-declared copy assignment operator is an inline public
2128 // member of its class.
2129 DeclarationName Name =
2130 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2131 CXXMethodDecl *CopyAssignment =
2132 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2133 Context.getFunctionType(RetType, &ArgType, 1,
2134 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002135 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002136 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002137 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002138 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002139 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002140
2141 // Add the parameter to the operator.
2142 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2143 ClassDecl->getLocation(),
2144 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002145 ArgType, /*DInfo=*/0,
2146 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002147 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002148
2149 // Don't call addedAssignmentOperator. There is no way to distinguish an
2150 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002151 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002152 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002153 }
2154
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002155 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002156 // C++ [class.dtor]p2:
2157 // If a class has no user-declared destructor, a destructor is
2158 // declared implicitly. An implicitly-declared destructor is an
2159 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002160 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002161 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002162 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002163 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002164 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002165 Context.getFunctionType(Context.VoidTy,
2166 0, 0, false, 0),
2167 /*isInline=*/true,
2168 /*isImplicitlyDeclared=*/true);
2169 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002170 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002171 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002172 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002173
2174 AddOverriddenMethods(ClassDecl, Destructor);
Fariborz Jahanian6bc97682009-12-01 23:18:25 +00002175 CheckDestructor(Destructor, false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002176 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002177}
2178
Douglas Gregor6569d682009-05-27 23:11:45 +00002179void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002180 Decl *D = TemplateD.getAs<Decl>();
2181 if (!D)
2182 return;
2183
2184 TemplateParameterList *Params = 0;
2185 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2186 Params = Template->getTemplateParameters();
2187 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2188 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2189 Params = PartialSpec->getTemplateParameters();
2190 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002191 return;
2192
Douglas Gregor6569d682009-05-27 23:11:45 +00002193 for (TemplateParameterList::iterator Param = Params->begin(),
2194 ParamEnd = Params->end();
2195 Param != ParamEnd; ++Param) {
2196 NamedDecl *Named = cast<NamedDecl>(*Param);
2197 if (Named->getDeclName()) {
2198 S->AddDecl(DeclPtrTy::make(Named));
2199 IdResolver.AddDecl(Named);
2200 }
2201 }
2202}
2203
Douglas Gregor72b505b2008-12-16 21:30:33 +00002204/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2205/// parsing a top-level (non-nested) C++ class, and we are now
2206/// parsing those parts of the given Method declaration that could
2207/// not be parsed earlier (C++ [class.mem]p2), such as default
2208/// arguments. This action should enter the scope of the given
2209/// Method declaration as if we had just parsed the qualified method
2210/// name. However, it should not bring the parameters into scope;
2211/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002212void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002213 if (!MethodD)
2214 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002216 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Douglas Gregor72b505b2008-12-16 21:30:33 +00002218 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002219 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002220 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002221 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2222 SS.setScopeRep(
2223 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002224 ActOnCXXEnterDeclaratorScope(S, SS);
2225}
2226
2227/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2228/// C++ method declaration. We're (re-)introducing the given
2229/// function parameter into scope for use in parsing later parts of
2230/// the method declaration. For example, we could see an
2231/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002232void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002233 if (!ParamD)
2234 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Chris Lattnerb28317a2009-03-28 19:18:32 +00002236 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002237
2238 // If this parameter has an unparsed default argument, clear it out
2239 // to make way for the parsed default argument.
2240 if (Param->hasUnparsedDefaultArg())
2241 Param->setDefaultArg(0);
2242
Chris Lattnerb28317a2009-03-28 19:18:32 +00002243 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002244 if (Param->getDeclName())
2245 IdResolver.AddDecl(Param);
2246}
2247
2248/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2249/// processing the delayed method declaration for Method. The method
2250/// declaration is now considered finished. There may be a separate
2251/// ActOnStartOfFunctionDef action later (not necessarily
2252/// immediately!) for this method, if it was also defined inside the
2253/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002254void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002255 if (!MethodD)
2256 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002258 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Chris Lattnerb28317a2009-03-28 19:18:32 +00002260 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002261 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002262 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002263 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2264 SS.setScopeRep(
2265 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002266 ActOnCXXExitDeclaratorScope(S, SS);
2267
2268 // Now that we have our default arguments, check the constructor
2269 // again. It could produce additional diagnostics or affect whether
2270 // the class has implicitly-declared destructors, among other
2271 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002272 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2273 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002274
2275 // Check the default arguments, which we may have added.
2276 if (!Method->isInvalidDecl())
2277 CheckCXXDefaultArguments(Method);
2278}
2279
Douglas Gregor42a552f2008-11-05 20:51:48 +00002280/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002281/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002282/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002283/// emit diagnostics and set the invalid bit to true. In any case, the type
2284/// will be updated to reflect a well-formed type for the constructor and
2285/// returned.
2286QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2287 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002288 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002289
2290 // C++ [class.ctor]p3:
2291 // A constructor shall not be virtual (10.3) or static (9.4). A
2292 // constructor can be invoked for a const, volatile or const
2293 // volatile object. A constructor shall not be declared const,
2294 // volatile, or const volatile (9.3.2).
2295 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002296 if (!D.isInvalidType())
2297 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2298 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2299 << SourceRange(D.getIdentifierLoc());
2300 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002301 }
2302 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002303 if (!D.isInvalidType())
2304 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2305 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2306 << SourceRange(D.getIdentifierLoc());
2307 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002308 SC = FunctionDecl::None;
2309 }
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Chris Lattner65401802009-04-25 08:28:21 +00002311 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2312 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002313 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002314 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2315 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002316 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002317 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2318 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002319 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002320 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2321 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002322 }
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Douglas Gregor42a552f2008-11-05 20:51:48 +00002324 // Rebuild the function type "R" without any type qualifiers (in
2325 // case any of the errors above fired) and with "void" as the
2326 // return type, since constructors don't have return types. We
2327 // *always* have to do this, because GetTypeForDeclarator will
2328 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002329 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002330 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2331 Proto->getNumArgs(),
2332 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002333}
2334
Douglas Gregor72b505b2008-12-16 21:30:33 +00002335/// CheckConstructor - Checks a fully-formed constructor for
2336/// well-formedness, issuing any diagnostics required. Returns true if
2337/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002338void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002339 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002340 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2341 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002342 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002343
2344 // C++ [class.copy]p3:
2345 // A declaration of a constructor for a class X is ill-formed if
2346 // its first parameter is of type (optionally cv-qualified) X and
2347 // either there are no other parameters or else all other
2348 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002349 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002350 ((Constructor->getNumParams() == 1) ||
2351 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002352 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2353 Constructor->getTemplateSpecializationKind()
2354 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002355 QualType ParamType = Constructor->getParamDecl(0)->getType();
2356 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2357 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002358 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2359 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002360 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002361
2362 // FIXME: Rather that making the constructor invalid, we should endeavor
2363 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002364 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002365 }
2366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregor72b505b2008-12-16 21:30:33 +00002368 // Notify the class that we've added a constructor.
2369 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002370}
2371
Anders Carlsson37909802009-11-30 21:24:50 +00002372/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2373/// issuing any diagnostics required. Returns true on error.
Fariborz Jahanian6bc97682009-12-01 23:18:25 +00002374bool Sema::CheckDestructor(CXXDestructorDecl *Destructor, bool Diagnose) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002375 CXXRecordDecl *RD = Destructor->getParent();
2376
2377 if (Destructor->isVirtual()) {
2378 SourceLocation Loc;
2379
2380 if (!Destructor->isImplicit())
2381 Loc = Destructor->getLocation();
2382 else
2383 Loc = RD->getLocation();
2384
2385 // If we have a virtual destructor, look up the deallocation function
2386 FunctionDecl *OperatorDelete = 0;
2387 DeclarationName Name =
2388 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Fariborz Jahanian6bc97682009-12-01 23:18:25 +00002389 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, Diagnose))
Anders Carlsson37909802009-11-30 21:24:50 +00002390 return true;
2391
2392 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002393 }
Anders Carlsson37909802009-11-30 21:24:50 +00002394
2395 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002396}
2397
Mike Stump1eb44332009-09-09 15:08:12 +00002398static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002399FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2400 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2401 FTI.ArgInfo[0].Param &&
2402 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2403}
2404
Douglas Gregor42a552f2008-11-05 20:51:48 +00002405/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2406/// the well-formednes of the destructor declarator @p D with type @p
2407/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002408/// emit diagnostics and set the declarator to invalid. Even if this happens,
2409/// will be updated to reflect a well-formed type for the destructor and
2410/// returned.
2411QualType Sema::CheckDestructorDeclarator(Declarator &D,
2412 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002413 // C++ [class.dtor]p1:
2414 // [...] A typedef-name that names a class is a class-name
2415 // (7.1.3); however, a typedef-name that names a class shall not
2416 // be used as the identifier in the declarator for a destructor
2417 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002418 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002419 if (isa<TypedefType>(DeclaratorType)) {
2420 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002421 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002422 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002423 }
2424
2425 // C++ [class.dtor]p2:
2426 // A destructor is used to destroy objects of its class type. A
2427 // destructor takes no parameters, and no return type can be
2428 // specified for it (not even void). The address of a destructor
2429 // shall not be taken. A destructor shall not be static. A
2430 // destructor can be invoked for a const, volatile or const
2431 // volatile object. A destructor shall not be declared const,
2432 // volatile or const volatile (9.3.2).
2433 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002434 if (!D.isInvalidType())
2435 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2436 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2437 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002438 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002439 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002440 }
Chris Lattner65401802009-04-25 08:28:21 +00002441 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002442 // Destructors don't have return types, but the parser will
2443 // happily parse something like:
2444 //
2445 // class X {
2446 // float ~X();
2447 // };
2448 //
2449 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002450 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2451 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2452 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002453 }
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Chris Lattner65401802009-04-25 08:28:21 +00002455 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2456 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002457 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002458 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2459 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002460 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002461 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2462 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002463 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002464 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2465 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002466 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002467 }
2468
2469 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002470 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002471 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2472
2473 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002474 FTI.freeArgs();
2475 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002476 }
2477
Mike Stump1eb44332009-09-09 15:08:12 +00002478 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002479 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002480 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002481 D.setInvalidType();
2482 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002483
2484 // Rebuild the function type "R" without any type qualifiers or
2485 // parameters (in case any of the errors above fired) and with
2486 // "void" as the return type, since destructors don't have return
2487 // types. We *always* have to do this, because GetTypeForDeclarator
2488 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002489 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002490}
2491
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002492/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2493/// well-formednes of the conversion function declarator @p D with
2494/// type @p R. If there are any errors in the declarator, this routine
2495/// will emit diagnostics and return true. Otherwise, it will return
2496/// false. Either way, the type @p R will be updated to reflect a
2497/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002498void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002499 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002500 // C++ [class.conv.fct]p1:
2501 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002502 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002503 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002504 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002505 if (!D.isInvalidType())
2506 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2507 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2508 << SourceRange(D.getIdentifierLoc());
2509 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002510 SC = FunctionDecl::None;
2511 }
Chris Lattner6e475012009-04-25 08:35:12 +00002512 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002513 // Conversion functions don't have return types, but the parser will
2514 // happily parse something like:
2515 //
2516 // class X {
2517 // float operator bool();
2518 // };
2519 //
2520 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002521 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2522 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2523 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002524 }
2525
2526 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002527 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002528 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2529
2530 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002531 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002532 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002533 }
2534
Mike Stump1eb44332009-09-09 15:08:12 +00002535 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002536 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002537 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002538 D.setInvalidType();
2539 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002540
2541 // C++ [class.conv.fct]p4:
2542 // The conversion-type-id shall not represent a function type nor
2543 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002544 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002545 if (ConvType->isArrayType()) {
2546 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2547 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002548 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002549 } else if (ConvType->isFunctionType()) {
2550 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2551 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002552 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002553 }
2554
2555 // Rebuild the function type "R" without any parameters (in case any
2556 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002557 // return type.
2558 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002559 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002560
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002561 // C++0x explicit conversion operators.
2562 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002563 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002564 diag::warn_explicit_conversion_functions)
2565 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002566}
2567
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002568/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2569/// the declaration of the given C++ conversion function. This routine
2570/// is responsible for recording the conversion function in the C++
2571/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002572Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002573 assert(Conversion && "Expected to receive a conversion function declaration");
2574
Douglas Gregor9d350972008-12-12 08:25:50 +00002575 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002576
2577 // Make sure we aren't redeclaring the conversion function.
2578 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002579
2580 // C++ [class.conv.fct]p1:
2581 // [...] A conversion function is never used to convert a
2582 // (possibly cv-qualified) object to the (possibly cv-qualified)
2583 // same object type (or a reference to it), to a (possibly
2584 // cv-qualified) base class of that type (or a reference to it),
2585 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002586 // FIXME: Suppress this warning if the conversion function ends up being a
2587 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002588 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002589 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002590 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002591 ConvType = ConvTypeRef->getPointeeType();
2592 if (ConvType->isRecordType()) {
2593 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2594 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002595 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002596 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002597 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002598 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002599 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002600 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002601 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002602 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002603 }
2604
Douglas Gregor70316a02008-12-26 15:00:45 +00002605 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002606 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002607 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002608 = Conversion->getDescribedFunctionTemplate())
2609 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002610 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2611 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002612 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002613 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002614 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002615 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002616 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002617 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002618
Chris Lattnerb28317a2009-03-28 19:18:32 +00002619 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002620}
2621
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002622//===----------------------------------------------------------------------===//
2623// Namespace Handling
2624//===----------------------------------------------------------------------===//
2625
2626/// ActOnStartNamespaceDef - This is called at the start of a namespace
2627/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002628Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2629 SourceLocation IdentLoc,
2630 IdentifierInfo *II,
2631 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002632 NamespaceDecl *Namespc =
2633 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2634 Namespc->setLBracLoc(LBrace);
2635
2636 Scope *DeclRegionScope = NamespcScope->getParent();
2637
2638 if (II) {
2639 // C++ [namespace.def]p2:
2640 // The identifier in an original-namespace-definition shall not have been
2641 // previously defined in the declarative region in which the
2642 // original-namespace-definition appears. The identifier in an
2643 // original-namespace-definition is the name of the namespace. Subsequently
2644 // in that declarative region, it is treated as an original-namespace-name.
2645
John McCallf36e02d2009-10-09 21:13:30 +00002646 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002647 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002648 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Douglas Gregor44b43212008-12-11 16:49:14 +00002650 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2651 // This is an extended namespace definition.
2652 // Attach this namespace decl to the chain of extended namespace
2653 // definitions.
2654 OrigNS->setNextNamespace(Namespc);
2655 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002656
Mike Stump1eb44332009-09-09 15:08:12 +00002657 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002658 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002659 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002660 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002661 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002662 } else if (PrevDecl) {
2663 // This is an invalid name redefinition.
2664 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2665 << Namespc->getDeclName();
2666 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2667 Namespc->setInvalidDecl();
2668 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002669 } else if (II->isStr("std") &&
2670 CurContext->getLookupContext()->isTranslationUnit()) {
2671 // This is the first "real" definition of the namespace "std", so update
2672 // our cache of the "std" namespace to point at this definition.
2673 if (StdNamespace) {
2674 // We had already defined a dummy namespace "std". Link this new
2675 // namespace definition to the dummy namespace "std".
2676 StdNamespace->setNextNamespace(Namespc);
2677 StdNamespace->setLocation(IdentLoc);
2678 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2679 }
2680
2681 // Make our StdNamespace cache point at the first real definition of the
2682 // "std" namespace.
2683 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002684 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002685
2686 PushOnScopeChains(Namespc, DeclRegionScope);
2687 } else {
John McCall9aeed322009-10-01 00:25:31 +00002688 // Anonymous namespaces.
2689
2690 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2691 // behaves as if it were replaced by
2692 // namespace unique { /* empty body */ }
2693 // using namespace unique;
2694 // namespace unique { namespace-body }
2695 // where all occurrences of 'unique' in a translation unit are
2696 // replaced by the same identifier and this identifier differs
2697 // from all other identifiers in the entire program.
2698
2699 // We just create the namespace with an empty name and then add an
2700 // implicit using declaration, just like the standard suggests.
2701 //
2702 // CodeGen enforces the "universally unique" aspect by giving all
2703 // declarations semantically contained within an anonymous
2704 // namespace internal linkage.
2705
2706 assert(Namespc->isAnonymousNamespace());
2707 CurContext->addDecl(Namespc);
2708
2709 UsingDirectiveDecl* UD
2710 = UsingDirectiveDecl::Create(Context, CurContext,
2711 /* 'using' */ LBrace,
2712 /* 'namespace' */ SourceLocation(),
2713 /* qualifier */ SourceRange(),
2714 /* NNS */ NULL,
2715 /* identifier */ SourceLocation(),
2716 Namespc,
2717 /* Ancestor */ CurContext);
2718 UD->setImplicit();
2719 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002720 }
2721
2722 // Although we could have an invalid decl (i.e. the namespace name is a
2723 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002724 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2725 // for the namespace has the declarations that showed up in that particular
2726 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002727 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002728 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002729}
2730
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002731/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2732/// is a namespace alias, returns the namespace it points to.
2733static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2734 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2735 return AD->getNamespace();
2736 return dyn_cast_or_null<NamespaceDecl>(D);
2737}
2738
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002739/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2740/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002741void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2742 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002743 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2744 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2745 Namespc->setRBracLoc(RBrace);
2746 PopDeclContext();
2747}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002748
Chris Lattnerb28317a2009-03-28 19:18:32 +00002749Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2750 SourceLocation UsingLoc,
2751 SourceLocation NamespcLoc,
2752 const CXXScopeSpec &SS,
2753 SourceLocation IdentLoc,
2754 IdentifierInfo *NamespcName,
2755 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002756 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2757 assert(NamespcName && "Invalid NamespcName.");
2758 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002759 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002760
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002761 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002762
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002763 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002764 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2765 LookupParsedName(R, S, &SS);
2766 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002767 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002768
John McCallf36e02d2009-10-09 21:13:30 +00002769 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002770 NamedDecl *Named = R.getFoundDecl();
2771 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2772 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002773 // C++ [namespace.udir]p1:
2774 // A using-directive specifies that the names in the nominated
2775 // namespace can be used in the scope in which the
2776 // using-directive appears after the using-directive. During
2777 // unqualified name lookup (3.4.1), the names appear as if they
2778 // were declared in the nearest enclosing namespace which
2779 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002780 // namespace. [Note: in this context, "contains" means "contains
2781 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002782
2783 // Find enclosing context containing both using-directive and
2784 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002785 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002786 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2787 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2788 CommonAncestor = CommonAncestor->getParent();
2789
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002790 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002791 SS.getRange(),
2792 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002793 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002794 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002795 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002796 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002797 }
2798
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002799 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002800 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002801 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002802}
2803
2804void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2805 // If scope has associated entity, then using directive is at namespace
2806 // or translation unit scope. We add UsingDirectiveDecls, into
2807 // it's lookup structure.
2808 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002809 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002810 else
2811 // Otherwise it is block-sope. using-directives will affect lookup
2812 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002813 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002814}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002815
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002816
2817Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002818 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002819 SourceLocation UsingLoc,
2820 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002821 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002822 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002823 bool IsTypeName,
2824 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002825 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Douglas Gregor12c118a2009-11-04 16:30:06 +00002827 switch (Name.getKind()) {
2828 case UnqualifiedId::IK_Identifier:
2829 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00002830 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00002831 case UnqualifiedId::IK_ConversionFunctionId:
2832 break;
2833
2834 case UnqualifiedId::IK_ConstructorName:
2835 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2836 << SS.getRange();
2837 return DeclPtrTy();
2838
2839 case UnqualifiedId::IK_DestructorName:
2840 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2841 << SS.getRange();
2842 return DeclPtrTy();
2843
2844 case UnqualifiedId::IK_TemplateId:
2845 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2846 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2847 return DeclPtrTy();
2848 }
2849
2850 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall9488ea12009-11-17 05:59:44 +00002851 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002852 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002853 TargetName, AttrList,
2854 /* IsInstantiation */ false,
2855 IsTypeName, TypenameLoc);
Anders Carlsson595adc12009-08-29 19:54:19 +00002856 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002857 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002858 UD->setAccess(AS);
2859 }
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Anders Carlssonc72160b2009-08-28 05:40:36 +00002861 return DeclPtrTy::make(UD);
2862}
2863
John McCall9488ea12009-11-17 05:59:44 +00002864/// Builds a shadow declaration corresponding to a 'using' declaration.
2865static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2866 AccessSpecifier AS,
2867 UsingDecl *UD, NamedDecl *Orig) {
2868 // FIXME: diagnose hiding, collisions
2869
2870 // If we resolved to another shadow declaration, just coalesce them.
2871 if (isa<UsingShadowDecl>(Orig)) {
2872 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2873 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2874 }
2875
2876 UsingShadowDecl *Shadow
2877 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2878 UD->getLocation(), UD, Orig);
2879 UD->addShadowDecl(Shadow);
2880
2881 if (S)
2882 SemaRef.PushOnScopeChains(Shadow, S);
2883 else
2884 SemaRef.CurContext->addDecl(Shadow);
2885 Shadow->setAccess(AS);
2886
2887 return Shadow;
2888}
2889
John McCall7ba107a2009-11-18 02:36:19 +00002890/// Builds a using declaration.
2891///
2892/// \param IsInstantiation - Whether this call arises from an
2893/// instantiation of an unresolved using declaration. We treat
2894/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00002895NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2896 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002897 const CXXScopeSpec &SS,
2898 SourceLocation IdentLoc,
2899 DeclarationName Name,
2900 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002901 bool IsInstantiation,
2902 bool IsTypeName,
2903 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002904 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2905 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002906
Anders Carlsson550b14b2009-08-28 05:49:21 +00002907 // FIXME: We ignore attributes for now.
2908 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002909
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002910 if (SS.isEmpty()) {
2911 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002912 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
2915 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002916 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2917
John McCallaf8e6ed2009-11-12 03:15:40 +00002918 DeclContext *LookupContext = computeDeclContext(SS);
2919 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00002920 if (IsTypeName) {
2921 return UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2922 UsingLoc, TypenameLoc,
2923 SS.getRange(), NNS,
2924 IdentLoc, Name);
2925 } else {
2926 return UnresolvedUsingValueDecl::Create(Context, CurContext,
2927 UsingLoc, SS.getRange(), NNS,
2928 IdentLoc, Name);
2929 }
Anders Carlsson550b14b2009-08-28 05:49:21 +00002930 }
Mike Stump1eb44332009-09-09 15:08:12 +00002931
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002932 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2933 // C++0x N2914 [namespace.udecl]p3:
2934 // A using-declaration used as a member-declaration shall refer to a member
2935 // of a base class of the class being defined, shall refer to a member of an
2936 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002937 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002938 // a member of a base class of the class being defined.
John McCall9488ea12009-11-17 05:59:44 +00002939
John McCallaf8e6ed2009-11-12 03:15:40 +00002940 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2941 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002942 Diag(SS.getRange().getBegin(),
2943 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2944 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002945 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002946 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002947 } else {
2948 // C++0x N2914 [namespace.udecl]p8:
2949 // A using-declaration for a class member shall be a member-declaration.
John McCallaf8e6ed2009-11-12 03:15:40 +00002950 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002951 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002952 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002953 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002954 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002955 }
2956
John McCall9488ea12009-11-17 05:59:44 +00002957 // Look up the target name. Unlike most lookups, we do not want to
2958 // hide tag declarations: tag names are visible through the using
2959 // declaration even if hidden by ordinary names.
John McCalla24dc2e2009-11-17 02:14:36 +00002960 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00002961
2962 // We don't hide tags behind ordinary decls if we're in a
2963 // non-dependent context, but in a dependent context, this is
2964 // important for the stability of two-phase lookup.
2965 if (!IsInstantiation)
2966 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00002967
John McCalla24dc2e2009-11-17 02:14:36 +00002968 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002969
John McCallf36e02d2009-10-09 21:13:30 +00002970 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002971 Diag(IdentLoc, diag::err_no_member)
2972 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002973 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002974 }
2975
John McCall9488ea12009-11-17 05:59:44 +00002976 if (R.isAmbiguous())
2977 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002978
John McCall7ba107a2009-11-18 02:36:19 +00002979 if (IsTypeName) {
2980 // If we asked for a typename and got a non-type decl, error out.
2981 if (R.getResultKind() != LookupResult::Found
2982 || !isa<TypeDecl>(R.getFoundDecl())) {
2983 Diag(IdentLoc, diag::err_using_typename_non_type);
2984 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2985 Diag((*I)->getUnderlyingDecl()->getLocation(),
2986 diag::note_using_decl_target);
2987 return 0;
2988 }
2989 } else {
2990 // If we asked for a non-typename and we got a type, error out,
2991 // but only if this is an instantiation of an unresolved using
2992 // decl. Otherwise just silently find the type name.
2993 if (IsInstantiation &&
2994 R.getResultKind() == LookupResult::Found &&
2995 isa<TypeDecl>(R.getFoundDecl())) {
2996 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
2997 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
2998 return 0;
2999 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003000 }
3001
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003002 // C++0x N2914 [namespace.udecl]p6:
3003 // A using-declaration shall not name a namespace.
John McCall9488ea12009-11-17 05:59:44 +00003004 if (R.getResultKind() == LookupResult::Found
3005 && isa<NamespaceDecl>(R.getFoundDecl())) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003006 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3007 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003008 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010
John McCall9488ea12009-11-17 05:59:44 +00003011 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc,
3012 SS.getRange(), UsingLoc, NNS, Name,
3013 IsTypeName);
3014
3015 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3016 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3017
3018 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003019}
3020
Mike Stump1eb44332009-09-09 15:08:12 +00003021Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003022 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003023 SourceLocation AliasLoc,
3024 IdentifierInfo *Alias,
3025 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003026 SourceLocation IdentLoc,
3027 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Anders Carlsson81c85c42009-03-28 23:53:49 +00003029 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003030 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3031 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003032
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003033 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003034 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003035 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003036 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003037 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003038 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003039 if (!R.isAmbiguous() && !R.empty() &&
3040 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003041 return DeclPtrTy();
3042 }
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003044 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3045 diag::err_redefinition_different_kind;
3046 Diag(AliasLoc, DiagID) << Alias;
3047 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003048 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003049 }
3050
John McCalla24dc2e2009-11-17 02:14:36 +00003051 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003052 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003053
John McCallf36e02d2009-10-09 21:13:30 +00003054 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003055 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003056 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003057 }
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003059 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003060 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3061 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003062 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003063 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003065 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003066 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003067}
3068
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003069void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3070 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003071 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3072 !Constructor->isUsed()) &&
3073 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Eli Friedman80c30da2009-11-09 19:20:36 +00003075 CXXRecordDecl *ClassDecl
3076 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3077 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003078
Eli Friedman80c30da2009-11-09 19:20:36 +00003079 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003080 Diag(CurrentLocation, diag::note_member_synthesized_at)
3081 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003082 Constructor->setInvalidDecl();
3083 } else {
3084 Constructor->setUsed();
3085 }
Eli Friedman49c16da2009-11-09 01:05:47 +00003086 return;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003087}
3088
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003089void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003090 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003091 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3092 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003093 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003094 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3095 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003096 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003097 // implicitly defined, all the implicitly-declared default destructors
3098 // for its base class and its non-static data members shall have been
3099 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003100 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3101 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003102 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003103 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003104 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003105 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003106 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3107 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3108 else
Mike Stump1eb44332009-09-09 15:08:12 +00003109 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003110 "DefineImplicitDestructor - missing dtor in a base class");
3111 }
3112 }
Mike Stump1eb44332009-09-09 15:08:12 +00003113
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003114 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3115 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003116 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3117 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3118 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003119 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003120 CXXRecordDecl *FieldClassDecl
3121 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3122 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003123 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003124 const_cast<CXXDestructorDecl*>(
3125 FieldClassDecl->getDestructor(Context)))
3126 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3127 else
Mike Stump1eb44332009-09-09 15:08:12 +00003128 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003129 "DefineImplicitDestructor - missing dtor in class of a data member");
3130 }
3131 }
3132 }
Anders Carlsson37909802009-11-30 21:24:50 +00003133
3134 // FIXME: If CheckDestructor fails, we should emit a note about where the
3135 // implicit destructor was needed.
3136 if (CheckDestructor(Destructor)) {
3137 Diag(CurrentLocation, diag::note_member_synthesized_at)
3138 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3139
3140 Destructor->setInvalidDecl();
3141 return;
3142 }
3143
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003144 Destructor->setUsed();
3145}
3146
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003147void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3148 CXXMethodDecl *MethodDecl) {
3149 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3150 MethodDecl->getOverloadedOperator() == OO_Equal &&
3151 !MethodDecl->isUsed()) &&
3152 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003153
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003154 CXXRecordDecl *ClassDecl
3155 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003157 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003158 // Before the implicitly-declared copy assignment operator for a class is
3159 // implicitly defined, all implicitly-declared copy assignment operators
3160 // for its direct base classes and its nonstatic data members shall have
3161 // been implicitly defined.
3162 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003163 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3164 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003165 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003166 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003167 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003168 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3169 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3170 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003171 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3172 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003173 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3174 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3175 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003176 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003177 CXXRecordDecl *FieldClassDecl
3178 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003179 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003180 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3181 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003182 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003183 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003184 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3185 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003186 Diag(CurrentLocation, diag::note_first_required_here);
3187 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003188 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003189 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003190 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3191 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003192 Diag(CurrentLocation, diag::note_first_required_here);
3193 err = true;
3194 }
3195 }
3196 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003197 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003198}
3199
3200CXXMethodDecl *
3201Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3202 CXXRecordDecl *ClassDecl) {
3203 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3204 QualType RHSType(LHSType);
3205 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003206 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003207 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003208 RHSType = Context.getCVRQualifiedType(RHSType,
3209 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003210 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3211 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003212 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003213 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3214 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003215 SourceLocation()));
3216 Expr *Args[2] = { &*LHS, &*RHS };
3217 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003218 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003219 CandidateSet);
3220 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003221 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003222 ClassDecl->getLocation(), Best) == OR_Success)
3223 return cast<CXXMethodDecl>(Best->Function);
3224 assert(false &&
3225 "getAssignOperatorMethod - copy assignment operator method not found");
3226 return 0;
3227}
3228
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003229void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3230 CXXConstructorDecl *CopyConstructor,
3231 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003232 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003233 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3234 !CopyConstructor->isUsed()) &&
3235 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003237 CXXRecordDecl *ClassDecl
3238 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3239 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003240 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003241 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003242 // implicitly defined, all the implicitly-declared copy constructors
3243 // for its base class and its non-static data members shall have been
3244 // implicitly defined.
3245 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3246 Base != ClassDecl->bases_end(); ++Base) {
3247 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003248 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003249 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003250 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003251 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003252 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003253 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3254 FieldEnd = ClassDecl->field_end();
3255 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003256 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3257 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3258 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003259 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003260 CXXRecordDecl *FieldClassDecl
3261 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003262 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003263 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003264 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003265 }
3266 }
3267 CopyConstructor->setUsed();
3268}
3269
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003270Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003271Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003272 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003273 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003274 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Douglas Gregor39da0b82009-09-09 23:08:42 +00003276 // C++ [class.copy]p15:
3277 // Whenever a temporary class object is copied using a copy constructor, and
3278 // this object and the copy have the same cv-unqualified type, an
3279 // implementation is permitted to treat the original and the copy as two
3280 // different ways of referring to the same object and not perform a copy at
3281 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003283 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003284 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003285 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003286 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3287 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003288 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3289 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3290 E = ICE->getSubExpr();
3291
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003292 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3293 Elidable = true;
3294 }
Mike Stump1eb44332009-09-09 15:08:12 +00003295
3296 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003297 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003298}
3299
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003300/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3301/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003302Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003303Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3304 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003305 MultiExprArg ExprArgs) {
3306 unsigned NumExprs = ExprArgs.size();
3307 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003308
Douglas Gregor7edfb692009-11-23 12:27:39 +00003309 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003310 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3311 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003312}
3313
Anders Carlssone7624a72009-08-27 05:08:22 +00003314Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003315Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3316 QualType Ty,
3317 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003318 MultiExprArg Args,
3319 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003320 unsigned NumExprs = Args.size();
3321 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Douglas Gregor7edfb692009-11-23 12:27:39 +00003323 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003324 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3325 TyBeginLoc, Exprs,
3326 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003327}
3328
3329
Mike Stump1eb44332009-09-09 15:08:12 +00003330bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003331 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003332 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003333 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003334 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003335 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003336 if (TempResult.isInvalid())
3337 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003339 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003340 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003341 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003342 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Anders Carlssonfe2de492009-08-25 05:18:00 +00003344 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003345}
3346
Mike Stump1eb44332009-09-09 15:08:12 +00003347void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003348 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003349 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003350 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003351 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003352 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003353 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003354}
3355
Mike Stump1eb44332009-09-09 15:08:12 +00003356/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003357/// ActOnDeclarator, when a C++ direct initializer is present.
3358/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003359void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3360 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003361 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003362 SourceLocation *CommaLocs,
3363 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003364 unsigned NumExprs = Exprs.size();
3365 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003366 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003367
3368 // If there is no declaration, there was an error parsing it. Just ignore
3369 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003370 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003371 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003373 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3374 if (!VDecl) {
3375 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3376 RealDecl->setInvalidDecl();
3377 return;
3378 }
3379
Douglas Gregor83ddad32009-08-26 21:14:46 +00003380 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003381 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003382 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3383 //
3384 // Clients that want to distinguish between the two forms, can check for
3385 // direct initializer using VarDecl::hasCXXDirectInitializer().
3386 // A major benefit is that clients that don't particularly care about which
3387 // exactly form was it (like the CodeGen) can handle both cases without
3388 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003389
Douglas Gregor83ddad32009-08-26 21:14:46 +00003390 // If either the declaration has a dependent type or if any of the expressions
3391 // is type-dependent, we represent the initialization via a ParenListExpr for
3392 // later use during template instantiation.
3393 if (VDecl->getType()->isDependentType() ||
3394 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3395 // Let clients know that initialization was done with a direct initializer.
3396 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Douglas Gregor83ddad32009-08-26 21:14:46 +00003398 // Store the initialization expressions as a ParenListExpr.
3399 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003400 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003401 new (Context) ParenListExpr(Context, LParenLoc,
3402 (Expr **)Exprs.release(),
3403 NumExprs, RParenLoc));
3404 return;
3405 }
Mike Stump1eb44332009-09-09 15:08:12 +00003406
Douglas Gregor83ddad32009-08-26 21:14:46 +00003407
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003408 // C++ 8.5p11:
3409 // The form of initialization (using parentheses or '=') is generally
3410 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003411 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003412 QualType DeclInitType = VDecl->getType();
3413 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003414 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003415
Douglas Gregor615c5d42009-03-24 16:43:20 +00003416 // FIXME: This isn't the right place to complete the type.
3417 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3418 diag::err_typecheck_decl_incomplete_type)) {
3419 VDecl->setInvalidDecl();
3420 return;
3421 }
3422
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003423 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003424 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3425
Douglas Gregor18fe5682008-11-03 20:45:27 +00003426 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003427 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003428 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003429 VDecl->getLocation(),
3430 SourceRange(VDecl->getLocation(),
3431 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003432 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003433 IK_Direct,
3434 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003435 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003436 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003437 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003438 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003439 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003440 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003441 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003442 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003443 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003444 return;
3445 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003446
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003447 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003448 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3449 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003450 RealDecl->setInvalidDecl();
3451 return;
3452 }
3453
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003454 // Let clients know that initialization was done with a direct initializer.
3455 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003456
3457 assert(NumExprs == 1 && "Expected 1 expression");
3458 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003459 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3460 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003461}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003462
Douglas Gregor19aeac62009-11-14 03:27:21 +00003463/// \brief Add the applicable constructor candidates for an initialization
3464/// by constructor.
3465static void AddConstructorInitializationCandidates(Sema &SemaRef,
3466 QualType ClassType,
3467 Expr **Args,
3468 unsigned NumArgs,
3469 Sema::InitializationKind Kind,
3470 OverloadCandidateSet &CandidateSet) {
3471 // C++ [dcl.init]p14:
3472 // If the initialization is direct-initialization, or if it is
3473 // copy-initialization where the cv-unqualified version of the
3474 // source type is the same class as, or a derived class of, the
3475 // class of the destination, constructors are considered. The
3476 // applicable constructors are enumerated (13.3.1.3), and the
3477 // best one is chosen through overload resolution (13.3). The
3478 // constructor so selected is called to initialize the object,
3479 // with the initializer expression(s) as its argument(s). If no
3480 // constructor applies, or the overload resolution is ambiguous,
3481 // the initialization is ill-formed.
3482 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3483 assert(ClassRec && "Can only initialize a class type here");
3484
3485 // FIXME: When we decide not to synthesize the implicitly-declared
3486 // constructors, we'll need to make them appear here.
3487
3488 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3489 DeclarationName ConstructorName
3490 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3491 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3492 DeclContext::lookup_const_iterator Con, ConEnd;
3493 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3494 Con != ConEnd; ++Con) {
3495 // Find the constructor (which may be a template).
3496 CXXConstructorDecl *Constructor = 0;
3497 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3498 if (ConstructorTmpl)
3499 Constructor
3500 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3501 else
3502 Constructor = cast<CXXConstructorDecl>(*Con);
3503
3504 if ((Kind == Sema::IK_Direct) ||
3505 (Kind == Sema::IK_Copy &&
3506 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3507 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3508 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00003509 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3510 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003511 Args, NumArgs, CandidateSet);
3512 else
3513 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3514 }
3515 }
3516}
3517
3518/// \brief Attempt to perform initialization by constructor
3519/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3520/// copy-initialization.
3521///
3522/// This routine determines whether initialization by constructor is possible,
3523/// but it does not emit any diagnostics in the case where the initialization
3524/// is ill-formed.
3525///
3526/// \param ClassType the type of the object being initialized, which must have
3527/// class type.
3528///
3529/// \param Args the arguments provided to initialize the object
3530///
3531/// \param NumArgs the number of arguments provided to initialize the object
3532///
3533/// \param Kind the type of initialization being performed
3534///
3535/// \returns the constructor used to initialize the object, if successful.
3536/// Otherwise, emits a diagnostic and returns NULL.
3537CXXConstructorDecl *
3538Sema::TryInitializationByConstructor(QualType ClassType,
3539 Expr **Args, unsigned NumArgs,
3540 SourceLocation Loc,
3541 InitializationKind Kind) {
3542 // Build the overload candidate set
3543 OverloadCandidateSet CandidateSet;
3544 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3545 CandidateSet);
3546
3547 // Determine whether we found a constructor we can use.
3548 OverloadCandidateSet::iterator Best;
3549 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3550 case OR_Success:
3551 case OR_Deleted:
3552 // We found a constructor. Return it.
3553 return cast<CXXConstructorDecl>(Best->Function);
3554
3555 case OR_No_Viable_Function:
3556 case OR_Ambiguous:
3557 // Overload resolution failed. Return nothing.
3558 return 0;
3559 }
3560
3561 // Silence GCC warning
3562 return 0;
3563}
3564
Douglas Gregor39da0b82009-09-09 23:08:42 +00003565/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3566/// may occur as part of direct-initialization or copy-initialization.
3567///
3568/// \param ClassType the type of the object being initialized, which must have
3569/// class type.
3570///
3571/// \param ArgsPtr the arguments provided to initialize the object
3572///
3573/// \param Loc the source location where the initialization occurs
3574///
3575/// \param Range the source range that covers the entire initialization
3576///
3577/// \param InitEntity the name of the entity being initialized, if known
3578///
3579/// \param Kind the type of initialization being performed
3580///
3581/// \param ConvertedArgs a vector that will be filled in with the
3582/// appropriately-converted arguments to the constructor (if initialization
3583/// succeeded).
3584///
3585/// \returns the constructor used to initialize the object, if successful.
3586/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003587CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003588Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003589 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003590 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003591 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003592 InitializationKind Kind,
3593 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00003594
3595 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00003596 Expr **Args = (Expr **)ArgsPtr.get();
3597 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003598 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00003599 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3600 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003601
Douglas Gregor18fe5682008-11-03 20:45:27 +00003602 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003603 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003604 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003605 // We found a constructor. Break out so that we can convert the arguments
3606 // appropriately.
3607 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003608
Douglas Gregor18fe5682008-11-03 20:45:27 +00003609 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003610 if (InitEntity)
3611 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003612 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003613 else
3614 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003615 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003616 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003617 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Douglas Gregor18fe5682008-11-03 20:45:27 +00003619 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003620 if (InitEntity)
3621 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3622 else
3623 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003624 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3625 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003626
3627 case OR_Deleted:
3628 if (InitEntity)
3629 Diag(Loc, diag::err_ovl_deleted_init)
3630 << Best->Function->isDeleted()
3631 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00003632 else {
3633 const CXXRecordDecl *RD =
3634 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003635 Diag(Loc, diag::err_ovl_deleted_init)
3636 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00003637 << RD->getDeclName() << Range;
3638 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003639 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3640 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003641 }
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Douglas Gregor39da0b82009-09-09 23:08:42 +00003643 // Convert the arguments, fill in default arguments, etc.
3644 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3645 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3646 return 0;
3647
3648 return Constructor;
3649}
3650
3651/// \brief Given a constructor and the set of arguments provided for the
3652/// constructor, convert the arguments and add any required default arguments
3653/// to form a proper call to this constructor.
3654///
3655/// \returns true if an error occurred, false otherwise.
3656bool
3657Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3658 MultiExprArg ArgsPtr,
3659 SourceLocation Loc,
3660 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3661 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3662 unsigned NumArgs = ArgsPtr.size();
3663 Expr **Args = (Expr **)ArgsPtr.get();
3664
3665 const FunctionProtoType *Proto
3666 = Constructor->getType()->getAs<FunctionProtoType>();
3667 assert(Proto && "Constructor without a prototype?");
3668 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003669
3670 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003671 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00003672 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003673 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00003674 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003675
3676 VariadicCallType CallType =
3677 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3678 llvm::SmallVector<Expr *, 8> AllArgs;
3679 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3680 Proto, 0, Args, NumArgs, AllArgs,
3681 CallType);
3682 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3683 ConvertedArgs.push_back(AllArgs[i]);
3684 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003685}
3686
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003687/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3688/// determine whether they are reference-related,
3689/// reference-compatible, reference-compatible with added
3690/// qualification, or incompatible, for use in C++ initialization by
3691/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3692/// type, and the first type (T1) is the pointee type of the reference
3693/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003694Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00003695Sema::CompareReferenceRelationship(SourceLocation Loc,
3696 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003697 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003698 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003699 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00003700 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003701
Douglas Gregor393896f2009-11-05 13:06:35 +00003702 QualType T1 = Context.getCanonicalType(OrigT1);
3703 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003704 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3705 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003706
3707 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003708 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003709 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003710 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003711 if (UnqualT1 == UnqualT2)
3712 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00003713 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3714 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3715 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00003716 DerivedToBase = true;
3717 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003718 return Ref_Incompatible;
3719
3720 // At this point, we know that T1 and T2 are reference-related (at
3721 // least).
3722
3723 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003724 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003725 // reference-related to T2 and cv1 is the same cv-qualification
3726 // as, or greater cv-qualification than, cv2. For purposes of
3727 // overload resolution, cases for which cv1 is greater
3728 // cv-qualification than cv2 are identified as
3729 // reference-compatible with added qualification (see 13.3.3.2).
3730 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3731 return Ref_Compatible;
3732 else if (T1.isMoreQualifiedThan(T2))
3733 return Ref_Compatible_With_Added_Qualification;
3734 else
3735 return Ref_Related;
3736}
3737
3738/// CheckReferenceInit - Check the initialization of a reference
3739/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3740/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003741/// list), and DeclType is the type of the declaration. When ICS is
3742/// non-null, this routine will compute the implicit conversion
3743/// sequence according to C++ [over.ics.ref] and will not produce any
3744/// diagnostics; when ICS is null, it will emit diagnostics when any
3745/// errors are found. Either way, a return value of true indicates
3746/// that there was a failure, a return value of false indicates that
3747/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003748///
3749/// When @p SuppressUserConversions, user-defined conversions are
3750/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003751/// When @p AllowExplicit, we also permit explicit user-defined
3752/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003753/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003754/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3755/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003756bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003757Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003758 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003759 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003760 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003761 ImplicitConversionSequence *ICS,
3762 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003763 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3764
Ted Kremenek6217b802009-07-29 21:53:49 +00003765 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003766 QualType T2 = Init->getType();
3767
Douglas Gregor904eed32008-11-10 20:40:00 +00003768 // If the initializer is the address of an overloaded function, try
3769 // to resolve the overloaded function. If all goes well, T2 is the
3770 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003771 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003772 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003773 ICS != 0);
3774 if (Fn) {
3775 // Since we're performing this reference-initialization for
3776 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003777 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003778 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003779 return true;
3780
Anders Carlsson96ad5332009-10-21 17:16:23 +00003781 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003782 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003783
3784 T2 = Fn->getType();
3785 }
3786 }
3787
Douglas Gregor15da57e2008-10-29 02:00:59 +00003788 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003789 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003790 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003791 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3792 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003793 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00003794 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003795
3796 // Most paths end in a failed conversion.
3797 if (ICS)
3798 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003799
3800 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003801 // A reference to type "cv1 T1" is initialized by an expression
3802 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003803
3804 // -- If the initializer expression
3805
Sebastian Redla9845802009-03-29 15:27:50 +00003806 // Rvalue references cannot bind to lvalues (N2812).
3807 // There is absolutely no situation where they can. In particular, note that
3808 // this is ill-formed, even if B has a user-defined conversion to A&&:
3809 // B b;
3810 // A&& r = b;
3811 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3812 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003813 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003814 << Init->getSourceRange();
3815 return true;
3816 }
3817
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003818 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003819 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3820 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003821 //
3822 // Note that the bit-field check is skipped if we are just computing
3823 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003824 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003825 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003826 BindsDirectly = true;
3827
Douglas Gregor15da57e2008-10-29 02:00:59 +00003828 if (ICS) {
3829 // C++ [over.ics.ref]p1:
3830 // When a parameter of reference type binds directly (8.5.3)
3831 // to an argument expression, the implicit conversion sequence
3832 // is the identity conversion, unless the argument expression
3833 // has a type that is a derived class of the parameter type,
3834 // in which case the implicit conversion sequence is a
3835 // derived-to-base Conversion (13.3.3.1).
3836 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3837 ICS->Standard.First = ICK_Identity;
3838 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3839 ICS->Standard.Third = ICK_Identity;
3840 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3841 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003842 ICS->Standard.ReferenceBinding = true;
3843 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003844 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003845 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003846
3847 // Nothing more to do: the inaccessibility/ambiguity check for
3848 // derived-to-base conversions is suppressed when we're
3849 // computing the implicit conversion sequence (C++
3850 // [over.best.ics]p2).
3851 return false;
3852 } else {
3853 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003854 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3855 if (DerivedToBase)
3856 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003857 else if(CheckExceptionSpecCompatibility(Init, T1))
3858 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003859 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003860 }
3861 }
3862
3863 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003864 // implicitly converted to an lvalue of type "cv3 T3,"
3865 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003866 // 92) (this conversion is selected by enumerating the
3867 // applicable conversion functions (13.3.1.6) and choosing
3868 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003869 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003870 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003871 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003872 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003873
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003874 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00003875 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003876 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003877 for (UnresolvedSet::iterator I = Conversions->begin(),
3878 E = Conversions->end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00003879 FunctionTemplateDecl *ConvTemplate
John McCallba135432009-11-21 08:51:07 +00003880 = dyn_cast<FunctionTemplateDecl>(*I);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003881 CXXConversionDecl *Conv;
3882 if (ConvTemplate)
3883 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3884 else
John McCallba135432009-11-21 08:51:07 +00003885 Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003886
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003887 // If the conversion function doesn't return a reference type,
3888 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003889 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003890 (AllowExplicit || !Conv->isExplicit())) {
3891 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003892 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003893 CandidateSet);
3894 else
3895 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3896 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003897 }
3898
3899 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003900 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003901 case OR_Success:
3902 // This is a direct binding.
3903 BindsDirectly = true;
3904
3905 if (ICS) {
3906 // C++ [over.ics.ref]p1:
3907 //
3908 // [...] If the parameter binds directly to the result of
3909 // applying a conversion function to the argument
3910 // expression, the implicit conversion sequence is a
3911 // user-defined conversion sequence (13.3.3.1.2), with the
3912 // second standard conversion sequence either an identity
3913 // conversion or, if the conversion function returns an
3914 // entity of a type that is a derived class of the parameter
3915 // type, a derived-to-base Conversion.
3916 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3917 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3918 ICS->UserDefined.After = Best->FinalConversion;
3919 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003920 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003921 assert(ICS->UserDefined.After.ReferenceBinding &&
3922 ICS->UserDefined.After.DirectBinding &&
3923 "Expected a direct reference binding!");
3924 return false;
3925 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003926 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003927 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003928 CastExpr::CK_UserDefinedConversion,
3929 cast<CXXMethodDecl>(Best->Function),
3930 Owned(Init));
3931 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003932
3933 if (CheckExceptionSpecCompatibility(Init, T1))
3934 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003935 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3936 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003937 }
3938 break;
3939
3940 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003941 if (ICS) {
3942 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3943 Cand != CandidateSet.end(); ++Cand)
3944 if (Cand->Viable)
3945 ICS->ConversionFunctionSet.push_back(Cand->Function);
3946 break;
3947 }
3948 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3949 << Init->getSourceRange();
3950 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003951 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003952
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003953 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003954 case OR_Deleted:
3955 // There was no suitable conversion, or we found a deleted
3956 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003957 break;
3958 }
3959 }
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003961 if (BindsDirectly) {
3962 // C++ [dcl.init.ref]p4:
3963 // [...] In all cases where the reference-related or
3964 // reference-compatible relationship of two types is used to
3965 // establish the validity of a reference binding, and T1 is a
3966 // base class of T2, a program that necessitates such a binding
3967 // is ill-formed if T1 is an inaccessible (clause 11) or
3968 // ambiguous (10.2) base class of T2.
3969 //
3970 // Note that we only check this condition when we're allowed to
3971 // complain about errors, because we should not be checking for
3972 // ambiguity (or inaccessibility) unless the reference binding
3973 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003974 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003975 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003976 Init->getSourceRange(),
3977 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003978 else
3979 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003980 }
3981
3982 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003983 // type (i.e., cv1 shall be const), or the reference shall be an
3984 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003985 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003986 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003987 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003988 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3989 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003990 return true;
3991 }
3992
3993 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003994 // class type, and "cv1 T1" is reference-compatible with
3995 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003996 // following ways (the choice is implementation-defined):
3997 //
3998 // -- The reference is bound to the object represented by
3999 // the rvalue (see 3.10) or to a sub-object within that
4000 // object.
4001 //
Eli Friedman33a31382009-08-05 19:21:58 +00004002 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004003 // a constructor is called to copy the entire rvalue
4004 // object into the temporary. The reference is bound to
4005 // the temporary or to a sub-object within the
4006 // temporary.
4007 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004008 // The constructor that would be used to make the copy
4009 // shall be callable whether or not the copy is actually
4010 // done.
4011 //
Sebastian Redla9845802009-03-29 15:27:50 +00004012 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004013 // freedom, so we will always take the first option and never build
4014 // a temporary in this case. FIXME: We will, however, have to check
4015 // for the presence of a copy constructor in C++98/03 mode.
4016 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004017 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4018 if (ICS) {
4019 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4020 ICS->Standard.First = ICK_Identity;
4021 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4022 ICS->Standard.Third = ICK_Identity;
4023 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4024 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004025 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004026 ICS->Standard.DirectBinding = false;
4027 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004028 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004029 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004030 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4031 if (DerivedToBase)
4032 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004033 else if(CheckExceptionSpecCompatibility(Init, T1))
4034 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004035 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004036 }
4037 return false;
4038 }
4039
Eli Friedman33a31382009-08-05 19:21:58 +00004040 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004041 // initialized from the initializer expression using the
4042 // rules for a non-reference copy initialization (8.5). The
4043 // reference is then bound to the temporary. If T1 is
4044 // reference-related to T2, cv1 must be the same
4045 // cv-qualification as, or greater cv-qualification than,
4046 // cv2; otherwise, the program is ill-formed.
4047 if (RefRelationship == Ref_Related) {
4048 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4049 // we would be reference-compatible or reference-compatible with
4050 // added qualification. But that wasn't the case, so the reference
4051 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004052 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004053 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00004054 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4055 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004056 return true;
4057 }
4058
Douglas Gregor734d9862009-01-30 23:27:23 +00004059 // If at least one of the types is a class type, the types are not
4060 // related, and we aren't allowed any user conversions, the
4061 // reference binding fails. This case is important for breaking
4062 // recursion, since TryImplicitConversion below will attempt to
4063 // create a temporary through the use of a copy constructor.
4064 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4065 (T1->isRecordType() || T2->isRecordType())) {
4066 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004067 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00004068 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4069 return true;
4070 }
4071
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004072 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004073 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004074 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004075 //
Sebastian Redla9845802009-03-29 15:27:50 +00004076 // When a parameter of reference type is not bound directly to
4077 // an argument expression, the conversion sequence is the one
4078 // required to convert the argument expression to the
4079 // underlying type of the reference according to
4080 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4081 // to copy-initializing a temporary of the underlying type with
4082 // the argument expression. Any difference in top-level
4083 // cv-qualification is subsumed by the initialization itself
4084 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004085 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4086 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004087 /*ForceRValue=*/false,
4088 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004089
Sebastian Redla9845802009-03-29 15:27:50 +00004090 // Of course, that's still a reference binding.
4091 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4092 ICS->Standard.ReferenceBinding = true;
4093 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004094 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004095 ImplicitConversionSequence::UserDefinedConversion) {
4096 ICS->UserDefined.After.ReferenceBinding = true;
4097 ICS->UserDefined.After.RRefBinding = isRValRef;
4098 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004099 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4100 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004101 ImplicitConversionSequence Conversions;
4102 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4103 false, false,
4104 Conversions);
4105 if (badConversion) {
4106 if ((Conversions.ConversionKind ==
4107 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004108 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004109 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004110 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4111 for (int j = Conversions.ConversionFunctionSet.size()-1;
4112 j >= 0; j--) {
4113 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4114 Diag(Func->getLocation(), diag::err_ovl_candidate);
4115 }
4116 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004117 else {
4118 if (isRValRef)
4119 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4120 << Init->getSourceRange();
4121 else
4122 Diag(DeclLoc, diag::err_invalid_initialization)
4123 << DeclType << Init->getType() << Init->getSourceRange();
4124 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004125 }
4126 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004127 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004128}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004129
4130/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4131/// of this overloaded operator is well-formed. If so, returns false;
4132/// otherwise, emits appropriate diagnostics and returns true.
4133bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004134 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004135 "Expected an overloaded operator declaration");
4136
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004137 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4138
Mike Stump1eb44332009-09-09 15:08:12 +00004139 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004140 // The allocation and deallocation functions, operator new,
4141 // operator new[], operator delete and operator delete[], are
4142 // described completely in 3.7.3. The attributes and restrictions
4143 // found in the rest of this subclause do not apply to them unless
4144 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00004145 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004146 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004147 return false;
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004148
4149 if (Op == OO_New || Op == OO_Array_New) {
4150 bool ret = false;
4151 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4152 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4153 QualType T = Context.getCanonicalType((*Param)->getType());
4154 if (!T->isDependentType() && SizeTy != T) {
4155 Diag(FnDecl->getLocation(),
4156 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4157 << SizeTy;
4158 ret = true;
4159 }
4160 }
4161 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4162 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4163 return Diag(FnDecl->getLocation(),
4164 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregorcffecd02009-11-12 16:49:45 +00004165 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004166 return ret;
4167 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004168
4169 // C++ [over.oper]p6:
4170 // An operator function shall either be a non-static member
4171 // function or be a non-member function and have at least one
4172 // parameter whose type is a class, a reference to a class, an
4173 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004174 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4175 if (MethodDecl->isStatic())
4176 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004177 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004178 } else {
4179 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004180 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4181 ParamEnd = FnDecl->param_end();
4182 Param != ParamEnd; ++Param) {
4183 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004184 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4185 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004186 ClassOrEnumParam = true;
4187 break;
4188 }
4189 }
4190
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004191 if (!ClassOrEnumParam)
4192 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004193 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004194 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004195 }
4196
4197 // C++ [over.oper]p8:
4198 // An operator function cannot have default arguments (8.3.6),
4199 // except where explicitly stated below.
4200 //
Mike Stump1eb44332009-09-09 15:08:12 +00004201 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004202 // (C++ [over.call]p1).
4203 if (Op != OO_Call) {
4204 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4205 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004206 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004207 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004208 diag::err_operator_overload_default_arg)
4209 << FnDecl->getDeclName();
4210 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004211 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004212 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004213 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004214 }
4215 }
4216
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004217 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4218 { false, false, false }
4219#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4220 , { Unary, Binary, MemberOnly }
4221#include "clang/Basic/OperatorKinds.def"
4222 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004223
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004224 bool CanBeUnaryOperator = OperatorUses[Op][0];
4225 bool CanBeBinaryOperator = OperatorUses[Op][1];
4226 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004227
4228 // C++ [over.oper]p8:
4229 // [...] Operator functions cannot have more or fewer parameters
4230 // than the number required for the corresponding operator, as
4231 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004232 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004233 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004234 if (Op != OO_Call &&
4235 ((NumParams == 1 && !CanBeUnaryOperator) ||
4236 (NumParams == 2 && !CanBeBinaryOperator) ||
4237 (NumParams < 1) || (NumParams > 2))) {
4238 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004239 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004240 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004241 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004242 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004243 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004244 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004245 assert(CanBeBinaryOperator &&
4246 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004247 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004248 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004249
Chris Lattner416e46f2008-11-21 07:57:12 +00004250 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004251 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004252 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004253
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004254 // Overloaded operators other than operator() cannot be variadic.
4255 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004256 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004257 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004258 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004259 }
4260
4261 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004262 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4263 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004264 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004265 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004266 }
4267
4268 // C++ [over.inc]p1:
4269 // The user-defined function called operator++ implements the
4270 // prefix and postfix ++ operator. If this function is a member
4271 // function with no parameters, or a non-member function with one
4272 // parameter of class or enumeration type, it defines the prefix
4273 // increment operator ++ for objects of that type. If the function
4274 // is a member function with one parameter (which shall be of type
4275 // int) or a non-member function with two parameters (the second
4276 // of which shall be of type int), it defines the postfix
4277 // increment operator ++ for objects of that type.
4278 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4279 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4280 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004281 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004282 ParamIsInt = BT->getKind() == BuiltinType::Int;
4283
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004284 if (!ParamIsInt)
4285 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004286 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004287 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004288 }
4289
Sebastian Redl64b45f72009-01-05 20:52:13 +00004290 // Notify the class if it got an assignment operator.
4291 if (Op == OO_Equal) {
4292 // Would have returned earlier otherwise.
4293 assert(isa<CXXMethodDecl>(FnDecl) &&
4294 "Overloaded = not member, but not filtered.");
4295 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4296 Method->getParent()->addedAssignmentOperator(Context, Method);
4297 }
4298
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004299 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004300}
Chris Lattner5a003a42008-12-17 07:09:26 +00004301
Douglas Gregor074149e2009-01-05 19:45:36 +00004302/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4303/// linkage specification, including the language and (if present)
4304/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4305/// the location of the language string literal, which is provided
4306/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4307/// the '{' brace. Otherwise, this linkage specification does not
4308/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004309Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4310 SourceLocation ExternLoc,
4311 SourceLocation LangLoc,
4312 const char *Lang,
4313 unsigned StrSize,
4314 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004315 LinkageSpecDecl::LanguageIDs Language;
4316 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4317 Language = LinkageSpecDecl::lang_c;
4318 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4319 Language = LinkageSpecDecl::lang_cxx;
4320 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004321 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004322 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004323 }
Mike Stump1eb44332009-09-09 15:08:12 +00004324
Chris Lattnercc98eac2008-12-17 07:13:27 +00004325 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004326
Douglas Gregor074149e2009-01-05 19:45:36 +00004327 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004328 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004329 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004330 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004331 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004332 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004333}
4334
Douglas Gregor074149e2009-01-05 19:45:36 +00004335/// ActOnFinishLinkageSpecification - Completely the definition of
4336/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4337/// valid, it's the position of the closing '}' brace in a linkage
4338/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004339Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4340 DeclPtrTy LinkageSpec,
4341 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004342 if (LinkageSpec)
4343 PopDeclContext();
4344 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004345}
4346
Douglas Gregord308e622009-05-18 20:51:54 +00004347/// \brief Perform semantic analysis for the variable declaration that
4348/// occurs within a C++ catch clause, returning the newly-created
4349/// variable.
4350VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004351 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004352 IdentifierInfo *Name,
4353 SourceLocation Loc,
4354 SourceRange Range) {
4355 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004356
4357 // Arrays and functions decay.
4358 if (ExDeclType->isArrayType())
4359 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4360 else if (ExDeclType->isFunctionType())
4361 ExDeclType = Context.getPointerType(ExDeclType);
4362
4363 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4364 // The exception-declaration shall not denote a pointer or reference to an
4365 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004366 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004367 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004368 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004369 Invalid = true;
4370 }
Douglas Gregord308e622009-05-18 20:51:54 +00004371
Sebastian Redl4b07b292008-12-22 19:15:10 +00004372 QualType BaseType = ExDeclType;
4373 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004374 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004375 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004376 BaseType = Ptr->getPointeeType();
4377 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004378 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004379 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004380 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004381 BaseType = Ref->getPointeeType();
4382 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004383 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004384 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004385 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004386 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004387 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004388
Mike Stump1eb44332009-09-09 15:08:12 +00004389 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004390 RequireNonAbstractType(Loc, ExDeclType,
4391 diag::err_abstract_type_in_decl,
4392 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004393 Invalid = true;
4394
Douglas Gregord308e622009-05-18 20:51:54 +00004395 // FIXME: Need to test for ability to copy-construct and destroy the
4396 // exception variable.
4397
Sebastian Redl8351da02008-12-22 21:35:02 +00004398 // FIXME: Need to check for abstract classes.
4399
Mike Stump1eb44332009-09-09 15:08:12 +00004400 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004401 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004402
4403 if (Invalid)
4404 ExDecl->setInvalidDecl();
4405
4406 return ExDecl;
4407}
4408
4409/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4410/// handler.
4411Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004412 DeclaratorInfo *DInfo = 0;
4413 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004414
4415 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004416 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004417 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004418 // The scope should be freshly made just for us. There is just no way
4419 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004420 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004421 if (PrevDecl->isTemplateParameter()) {
4422 // Maybe we will complain about the shadowed template parameter.
4423 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004424 }
4425 }
4426
Chris Lattnereaaebc72009-04-25 08:06:05 +00004427 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004428 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4429 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004430 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004431 }
4432
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004433 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004434 D.getIdentifier(),
4435 D.getIdentifierLoc(),
4436 D.getDeclSpec().getSourceRange());
4437
Chris Lattnereaaebc72009-04-25 08:06:05 +00004438 if (Invalid)
4439 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Sebastian Redl4b07b292008-12-22 19:15:10 +00004441 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004442 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004443 PushOnScopeChains(ExDecl, S);
4444 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004445 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004446
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004447 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004448 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004449}
Anders Carlssonfb311762009-03-14 00:25:26 +00004450
Mike Stump1eb44332009-09-09 15:08:12 +00004451Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004452 ExprArg assertexpr,
4453 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004454 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004455 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004456 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4457
Anders Carlssonc3082412009-03-14 00:33:21 +00004458 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4459 llvm::APSInt Value(32);
4460 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4461 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4462 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004463 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004464 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004465
Anders Carlssonc3082412009-03-14 00:33:21 +00004466 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004467 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004468 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004469 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004470 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004471 }
4472 }
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Anders Carlsson77d81422009-03-15 17:35:16 +00004474 assertexpr.release();
4475 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004476 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004477 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004478
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004479 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004480 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004481}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004482
John McCalldd4a3b02009-09-16 22:47:08 +00004483/// Handle a friend type declaration. This works in tandem with
4484/// ActOnTag.
4485///
4486/// Notes on friend class templates:
4487///
4488/// We generally treat friend class declarations as if they were
4489/// declaring a class. So, for example, the elaborated type specifier
4490/// in a friend declaration is required to obey the restrictions of a
4491/// class-head (i.e. no typedefs in the scope chain), template
4492/// parameters are required to match up with simple template-ids, &c.
4493/// However, unlike when declaring a template specialization, it's
4494/// okay to refer to a template specialization without an empty
4495/// template parameter declaration, e.g.
4496/// friend class A<T>::B<unsigned>;
4497/// We permit this as a special case; if there are any template
4498/// parameters present at all, require proper matching, i.e.
4499/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004500Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004501 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004502 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004503
4504 assert(DS.isFriendSpecified());
4505 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4506
John McCalldd4a3b02009-09-16 22:47:08 +00004507 // Try to convert the decl specifier to a type. This works for
4508 // friend templates because ActOnTag never produces a ClassTemplateDecl
4509 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004510 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004511 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4512 if (TheDeclarator.isInvalidType())
4513 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004514
John McCalldd4a3b02009-09-16 22:47:08 +00004515 // This is definitely an error in C++98. It's probably meant to
4516 // be forbidden in C++0x, too, but the specification is just
4517 // poorly written.
4518 //
4519 // The problem is with declarations like the following:
4520 // template <T> friend A<T>::foo;
4521 // where deciding whether a class C is a friend or not now hinges
4522 // on whether there exists an instantiation of A that causes
4523 // 'foo' to equal C. There are restrictions on class-heads
4524 // (which we declare (by fiat) elaborated friend declarations to
4525 // be) that makes this tractable.
4526 //
4527 // FIXME: handle "template <> friend class A<T>;", which
4528 // is possibly well-formed? Who even knows?
4529 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4530 Diag(Loc, diag::err_tagless_friend_type_template)
4531 << DS.getSourceRange();
4532 return DeclPtrTy();
4533 }
4534
John McCall02cace72009-08-28 07:59:38 +00004535 // C++ [class.friend]p2:
4536 // An elaborated-type-specifier shall be used in a friend declaration
4537 // for a class.*
4538 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004539 // This is one of the rare places in Clang where it's legitimate to
4540 // ask about the "spelling" of the type.
4541 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4542 // If we evaluated the type to a record type, suggest putting
4543 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004544 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004545 RecordDecl *RD = RT->getDecl();
4546
4547 std::string InsertionText = std::string(" ") + RD->getKindName();
4548
John McCalle3af0232009-10-07 23:34:25 +00004549 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4550 << (unsigned) RD->getTagKind()
4551 << T
4552 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004553 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4554 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004555 return DeclPtrTy();
4556 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004557 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4558 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004559 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004560 }
4561 }
4562
John McCalle3af0232009-10-07 23:34:25 +00004563 // Enum types cannot be friends.
4564 if (T->getAs<EnumType>()) {
4565 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4566 << SourceRange(DS.getFriendSpecLoc());
4567 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004568 }
John McCall02cace72009-08-28 07:59:38 +00004569
John McCall02cace72009-08-28 07:59:38 +00004570 // C++98 [class.friend]p1: A friend of a class is a function
4571 // or class that is not a member of the class . . .
4572 // But that's a silly restriction which nobody implements for
4573 // inner classes, and C++0x removes it anyway, so we only report
4574 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004575 if (!getLangOptions().CPlusPlus0x)
4576 if (const RecordType *RT = T->getAs<RecordType>())
4577 if (RT->getDecl()->getDeclContext() == CurContext)
4578 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004579
John McCalldd4a3b02009-09-16 22:47:08 +00004580 Decl *D;
4581 if (TempParams.size())
4582 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4583 TempParams.size(),
4584 (TemplateParameterList**) TempParams.release(),
4585 T.getTypePtr(),
4586 DS.getFriendSpecLoc());
4587 else
4588 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4589 DS.getFriendSpecLoc());
4590 D->setAccess(AS_public);
4591 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004592
John McCalldd4a3b02009-09-16 22:47:08 +00004593 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004594}
4595
John McCallbbbcdd92009-09-11 21:02:39 +00004596Sema::DeclPtrTy
4597Sema::ActOnFriendFunctionDecl(Scope *S,
4598 Declarator &D,
4599 bool IsDefinition,
4600 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004601 const DeclSpec &DS = D.getDeclSpec();
4602
4603 assert(DS.isFriendSpecified());
4604 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4605
4606 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004607 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004608 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004609
4610 // C++ [class.friend]p1
4611 // A friend of a class is a function or class....
4612 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004613 // It *doesn't* see through dependent types, which is correct
4614 // according to [temp.arg.type]p3:
4615 // If a declaration acquires a function type through a
4616 // type dependent on a template-parameter and this causes
4617 // a declaration that does not use the syntactic form of a
4618 // function declarator to have a function type, the program
4619 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004620 if (!T->isFunctionType()) {
4621 Diag(Loc, diag::err_unexpected_friend);
4622
4623 // It might be worthwhile to try to recover by creating an
4624 // appropriate declaration.
4625 return DeclPtrTy();
4626 }
4627
4628 // C++ [namespace.memdef]p3
4629 // - If a friend declaration in a non-local class first declares a
4630 // class or function, the friend class or function is a member
4631 // of the innermost enclosing namespace.
4632 // - The name of the friend is not found by simple name lookup
4633 // until a matching declaration is provided in that namespace
4634 // scope (either before or after the class declaration granting
4635 // friendship).
4636 // - If a friend function is called, its name may be found by the
4637 // name lookup that considers functions from namespaces and
4638 // classes associated with the types of the function arguments.
4639 // - When looking for a prior declaration of a class or a function
4640 // declared as a friend, scopes outside the innermost enclosing
4641 // namespace scope are not considered.
4642
John McCall02cace72009-08-28 07:59:38 +00004643 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4644 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004645 assert(Name);
4646
John McCall67d1a672009-08-06 02:15:43 +00004647 // The context we found the declaration in, or in which we should
4648 // create the declaration.
4649 DeclContext *DC;
4650
4651 // FIXME: handle local classes
4652
4653 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00004654 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4655 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00004656 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004657 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004658 DC = computeDeclContext(ScopeQual);
4659
4660 // FIXME: handle dependent contexts
4661 if (!DC) return DeclPtrTy();
4662
John McCall68263142009-11-18 22:49:29 +00004663 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00004664
4665 // If searching in that context implicitly found a declaration in
4666 // a different context, treat it like it wasn't found at all.
4667 // TODO: better diagnostics for this case. Suggesting the right
4668 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00004669 // FIXME: getRepresentativeDecl() is not right here at all
4670 if (Previous.empty() ||
4671 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004672 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004673 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4674 return DeclPtrTy();
4675 }
4676
4677 // C++ [class.friend]p1: A friend of a class is a function or
4678 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004679 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004680 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4681
John McCall67d1a672009-08-06 02:15:43 +00004682 // Otherwise walk out to the nearest namespace scope looking for matches.
4683 } else {
4684 // TODO: handle local class contexts.
4685
4686 DC = CurContext;
4687 while (true) {
4688 // Skip class contexts. If someone can cite chapter and verse
4689 // for this behavior, that would be nice --- it's what GCC and
4690 // EDG do, and it seems like a reasonable intent, but the spec
4691 // really only says that checks for unqualified existing
4692 // declarations should stop at the nearest enclosing namespace,
4693 // not that they should only consider the nearest enclosing
4694 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004695 while (DC->isRecord())
4696 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004697
John McCall68263142009-11-18 22:49:29 +00004698 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00004699
4700 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00004701 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00004702 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004703
John McCall67d1a672009-08-06 02:15:43 +00004704 if (DC->isFileContext()) break;
4705 DC = DC->getParent();
4706 }
4707
4708 // C++ [class.friend]p1: A friend of a class is a function or
4709 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004710 // C++0x changes this for both friend types and functions.
4711 // Most C++ 98 compilers do seem to give an error here, so
4712 // we do, too.
John McCall68263142009-11-18 22:49:29 +00004713 if (!Previous.empty() && DC->Equals(CurContext)
4714 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004715 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4716 }
4717
Douglas Gregor182ddf02009-09-28 00:08:27 +00004718 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004719 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004720 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4721 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4722 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00004723 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004724 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4725 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004726 return DeclPtrTy();
4727 }
John McCall67d1a672009-08-06 02:15:43 +00004728 }
4729
Douglas Gregor182ddf02009-09-28 00:08:27 +00004730 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +00004731 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00004732 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004733 IsDefinition,
4734 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004735 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004736
Douglas Gregor182ddf02009-09-28 00:08:27 +00004737 assert(ND->getDeclContext() == DC);
4738 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004739
John McCallab88d972009-08-31 22:39:49 +00004740 // Add the function declaration to the appropriate lookup tables,
4741 // adjusting the redeclarations list as necessary. We don't
4742 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004743 //
John McCallab88d972009-08-31 22:39:49 +00004744 // Also update the scope-based lookup if the target context's
4745 // lookup context is in lexical scope.
4746 if (!CurContext->isDependentContext()) {
4747 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004748 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004749 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004750 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004751 }
John McCall02cace72009-08-28 07:59:38 +00004752
4753 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004754 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004755 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004756 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004757 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004758
Douglas Gregor182ddf02009-09-28 00:08:27 +00004759 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004760}
4761
Chris Lattnerb28317a2009-03-28 19:18:32 +00004762void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004763 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Chris Lattnerb28317a2009-03-28 19:18:32 +00004765 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004766 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4767 if (!Fn) {
4768 Diag(DelLoc, diag::err_deleted_non_function);
4769 return;
4770 }
4771 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4772 Diag(DelLoc, diag::err_deleted_decl_not_first);
4773 Diag(Prev->getLocation(), diag::note_previous_declaration);
4774 // If the declaration wasn't the first, we delete the function anyway for
4775 // recovery.
4776 }
4777 Fn->setDeleted();
4778}
Sebastian Redl13e88542009-04-27 21:33:24 +00004779
4780static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4781 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4782 ++CI) {
4783 Stmt *SubStmt = *CI;
4784 if (!SubStmt)
4785 continue;
4786 if (isa<ReturnStmt>(SubStmt))
4787 Self.Diag(SubStmt->getSourceRange().getBegin(),
4788 diag::err_return_in_constructor_handler);
4789 if (!isa<Expr>(SubStmt))
4790 SearchForReturnInStmt(Self, SubStmt);
4791 }
4792}
4793
4794void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4795 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4796 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4797 SearchForReturnInStmt(*this, Handler);
4798 }
4799}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004800
Mike Stump1eb44332009-09-09 15:08:12 +00004801bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004802 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004803 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4804 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004805
4806 QualType CNewTy = Context.getCanonicalType(NewTy);
4807 QualType COldTy = Context.getCanonicalType(OldTy);
4808
Mike Stump1eb44332009-09-09 15:08:12 +00004809 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00004810 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004811 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004812
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004813 // Check if the return types are covariant
4814 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004815
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004816 /// Both types must be pointers or references to classes.
4817 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4818 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4819 NewClassTy = NewPT->getPointeeType();
4820 OldClassTy = OldPT->getPointeeType();
4821 }
4822 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4823 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4824 NewClassTy = NewRT->getPointeeType();
4825 OldClassTy = OldRT->getPointeeType();
4826 }
4827 }
Mike Stump1eb44332009-09-09 15:08:12 +00004828
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004829 // The return types aren't either both pointers or references to a class type.
4830 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004831 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004832 diag::err_different_return_type_for_overriding_virtual_function)
4833 << New->getDeclName() << NewTy << OldTy;
4834 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004835
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004836 return true;
4837 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004838
Douglas Gregora4923eb2009-11-16 21:35:15 +00004839 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004840 // Check if the new class derives from the old class.
4841 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4842 Diag(New->getLocation(),
4843 diag::err_covariant_return_not_derived)
4844 << New->getDeclName() << NewTy << OldTy;
4845 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4846 return true;
4847 }
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004849 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004850 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004851 diag::err_covariant_return_inaccessible_base,
4852 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4853 // FIXME: Should this point to the return type?
4854 New->getLocation(), SourceRange(), New->getDeclName())) {
4855 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4856 return true;
4857 }
4858 }
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004860 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004861 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004862 Diag(New->getLocation(),
4863 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004864 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004865 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4866 return true;
4867 };
Mike Stump1eb44332009-09-09 15:08:12 +00004868
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004869
4870 // The new class type must have the same or less qualifiers as the old type.
4871 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4872 Diag(New->getLocation(),
4873 diag::err_covariant_return_type_class_type_more_qualified)
4874 << New->getDeclName() << NewTy << OldTy;
4875 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4876 return true;
4877 };
Mike Stump1eb44332009-09-09 15:08:12 +00004878
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004879 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004880}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004881
Sean Huntbbd37c62009-11-21 08:43:09 +00004882bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4883 const CXXMethodDecl *Old)
4884{
4885 if (Old->hasAttr<FinalAttr>()) {
4886 Diag(New->getLocation(), diag::err_final_function_overridden)
4887 << New->getDeclName();
4888 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4889 return true;
4890 }
4891
4892 return false;
4893}
4894
Douglas Gregor4ba31362009-12-01 17:24:26 +00004895/// \brief Mark the given method pure.
4896///
4897/// \param Method the method to be marked pure.
4898///
4899/// \param InitRange the source range that covers the "0" initializer.
4900bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
4901 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
4902 Method->setPure();
4903
4904 // A class is abstract if at least one function is pure virtual.
4905 Method->getParent()->setAbstract(true);
4906 return false;
4907 }
4908
4909 if (!Method->isInvalidDecl())
4910 Diag(Method->getLocation(), diag::err_non_virtual_pure)
4911 << Method->getDeclName() << InitRange;
4912 return true;
4913}
4914
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004915/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4916/// initializer for the declaration 'Dcl'.
4917/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4918/// static data member of class X, names should be looked up in the scope of
4919/// class X.
4920void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004921 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004923 Decl *D = Dcl.getAs<Decl>();
4924 // If there is no declaration, there was an error parsing it.
4925 if (D == 0)
4926 return;
4927
4928 // Check whether it is a declaration with a nested name specifier like
4929 // int foo::bar;
4930 if (!D->isOutOfLine())
4931 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004933 // C++ [basic.lookup.unqual]p13
4934 //
4935 // A name used in the definition of a static data member of class X
4936 // (after the qualified-id of the static member) is looked up as if the name
4937 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004938
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004939 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004940 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004941}
4942
4943/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4944/// initializer for the declaration 'Dcl'.
4945void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004946 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004948 Decl *D = Dcl.getAs<Decl>();
4949 // If there is no declaration, there was an error parsing it.
4950 if (D == 0)
4951 return;
4952
4953 // Check whether it is a declaration with a nested name specifier like
4954 // int foo::bar;
4955 if (!D->isOutOfLine())
4956 return;
4957
4958 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004959 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004960}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00004961
4962/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
4963/// C++ if/switch/while/for statement.
4964/// e.g: "if (int x = f()) {...}"
4965Action::DeclResult
4966Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
4967 // C++ 6.4p2:
4968 // The declarator shall not specify a function or an array.
4969 // The type-specifier-seq shall not contain typedef and shall not declare a
4970 // new class or enumeration.
4971 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4972 "Parser allowed 'typedef' as storage class of condition decl.");
4973
4974 DeclaratorInfo *DInfo = 0;
4975 TagDecl *OwnedTag = 0;
4976 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
4977
4978 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
4979 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
4980 // would be created and CXXConditionDeclExpr wants a VarDecl.
4981 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
4982 << D.getSourceRange();
4983 return DeclResult();
4984 } else if (OwnedTag && OwnedTag->isDefinition()) {
4985 // The type-specifier-seq shall not declare a new class or enumeration.
4986 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
4987 }
4988
4989 DeclPtrTy Dcl = ActOnDeclarator(S, D);
4990 if (!Dcl)
4991 return DeclResult();
4992
4993 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
4994 VD->setDeclaredInCondition(true);
4995 return Dcl;
4996}