blob: e956ffec4929019c5de8ca9d6ad382514836c254 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000026#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000028#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000029#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000030
31using namespace clang;
32
Chris Lattner8123a952008-04-10 02:22:51 +000033//===----------------------------------------------------------------------===//
34// CheckDefaultArgumentVisitor
35//===----------------------------------------------------------------------===//
36
Chris Lattner9e979552008-04-12 23:52:44 +000037namespace {
38 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
39 /// the default argument of a parameter to determine whether it
40 /// contains any ill-formed subexpressions. For example, this will
41 /// diagnose the use of local variables or parameters within the
42 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000043 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000044 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000045 Expr *DefaultArg;
46 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000047
Chris Lattner9e979552008-04-12 23:52:44 +000048 public:
Mike Stump1eb44332009-09-09 15:08:12 +000049 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000050 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000051
Chris Lattner9e979552008-04-12 23:52:44 +000052 bool VisitExpr(Expr *Node);
53 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000054 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000055 };
Chris Lattner8123a952008-04-10 02:22:51 +000056
Chris Lattner9e979552008-04-12 23:52:44 +000057 /// VisitExpr - Visit all of the children of this expression.
58 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
59 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000060 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000061 E = Node->child_end(); I != E; ++I)
62 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000063 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000064 }
65
Chris Lattner9e979552008-04-12 23:52:44 +000066 /// VisitDeclRefExpr - Visit a reference to a declaration, to
67 /// determine whether this declaration can be used in the default
68 /// argument expression.
69 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000070 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000071 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
72 // C++ [dcl.fct.default]p9
73 // Default arguments are evaluated each time the function is
74 // called. The order of evaluation of function arguments is
75 // unspecified. Consequently, parameters of a function shall not
76 // be used in default argument expressions, even if they are not
77 // evaluated. Parameters of a function declared before a default
78 // argument expression are in scope and can hide namespace and
79 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000080 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000081 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000082 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000083 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000084 // C++ [dcl.fct.default]p7
85 // Local variables shall not be used in default argument
86 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000087 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000088 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000089 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000090 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000091 }
Chris Lattner8123a952008-04-10 02:22:51 +000092
Douglas Gregor3996f232008-11-04 13:41:56 +000093 return false;
94 }
Chris Lattner9e979552008-04-12 23:52:44 +000095
Douglas Gregor796da182008-11-04 14:32:21 +000096 /// VisitCXXThisExpr - Visit a C++ "this" expression.
97 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
98 // C++ [dcl.fct.default]p8:
99 // The keyword this shall not be used in a default argument of a
100 // member function.
101 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_this)
103 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105}
106
Anders Carlssoned961f92009-08-25 02:29:20 +0000107bool
108Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000109 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000110 QualType ParamType = Param->getType();
111
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000126 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000127 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000128 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000129
130 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Anders Carlssoned961f92009-08-25 02:29:20 +0000132 // Okay: add the default argument to the parameter
133 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Anders Carlssoned961f92009-08-25 02:29:20 +0000135 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Anders Carlsson9351c172009-08-25 03:18:48 +0000137 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000138}
139
Chris Lattner8123a952008-04-10 02:22:51 +0000140/// ActOnParamDefaultArgument - Check whether the default argument
141/// provided for a function parameter is well-formed. If so, attach it
142/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000143void
Mike Stump1eb44332009-09-09 15:08:12 +0000144Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000145 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000146 if (!param || !defarg.get())
147 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattnerb28317a2009-03-28 19:18:32 +0000149 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000150 UnparsedDefaultArgLocs.erase(Param);
151
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000152 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000153 QualType ParamType = Param->getType();
154
155 // Default arguments are only permitted in C++
156 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000157 Diag(EqualLoc, diag::err_param_default_argument)
158 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000159 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000160 return;
161 }
162
Anders Carlsson66e30672009-08-25 01:02:06 +0000163 // Check that the default argument is well-formed
164 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
165 if (DefaultArgChecker.Visit(DefaultArg.get())) {
166 Param->setInvalidDecl();
167 return;
168 }
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Anders Carlssoned961f92009-08-25 02:29:20 +0000170 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000171}
172
Douglas Gregor61366e92008-12-24 00:01:03 +0000173/// ActOnParamUnparsedDefaultArgument - We've seen a default
174/// argument for a function parameter, but we can't parse it yet
175/// because we're inside a class definition. Note that this default
176/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000177void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000178 SourceLocation EqualLoc,
179 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000180 if (!param)
181 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattnerb28317a2009-03-28 19:18:32 +0000183 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000184 if (Param)
185 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Anders Carlsson5e300d12009-06-12 16:51:40 +0000187 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000188}
189
Douglas Gregor72b505b2008-12-16 21:30:33 +0000190/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
191/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000192void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000193 if (!param)
194 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Anders Carlsson5e300d12009-06-12 16:51:40 +0000196 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Anders Carlsson5e300d12009-06-12 16:51:40 +0000198 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Anders Carlsson5e300d12009-06-12 16:51:40 +0000200 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000201}
202
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000203/// CheckExtraCXXDefaultArguments - Check for any extra default
204/// arguments in the declarator, which is not a function declaration
205/// or definition and therefore is not permitted to have default
206/// arguments. This routine should be invoked for every declarator
207/// that is not a function declaration or definition.
208void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
209 // C++ [dcl.fct.default]p3
210 // A default argument expression shall be specified only in the
211 // parameter-declaration-clause of a function declaration or in a
212 // template-parameter (14.1). It shall not be specified for a
213 // parameter pack. If it is specified in a
214 // parameter-declaration-clause, it shall not occur within a
215 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000216 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000217 DeclaratorChunk &chunk = D.getTypeObject(i);
218 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000219 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
220 ParmVarDecl *Param =
221 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000222 if (Param->hasUnparsedDefaultArg()) {
223 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000224 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
225 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
226 delete Toks;
227 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000228 } else if (Param->getDefaultArg()) {
229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << Param->getDefaultArg()->getSourceRange();
231 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000232 }
233 }
234 }
235 }
236}
237
Chris Lattner3d1cee32008-04-08 05:04:30 +0000238// MergeCXXFunctionDecl - Merge two declarations of the same C++
239// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000240// type. Subroutine of MergeFunctionDecl. Returns true if there was an
241// error, false otherwise.
242bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
243 bool Invalid = false;
244
Chris Lattner3d1cee32008-04-08 05:04:30 +0000245 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000246 // For non-template functions, default arguments can be added in
247 // later declarations of a function in the same
248 // scope. Declarations in different scopes have completely
249 // distinct sets of default arguments. That is, declarations in
250 // inner scopes do not acquire default arguments from
251 // declarations in outer scopes, and vice versa. In a given
252 // function declaration, all parameters subsequent to a
253 // parameter with a default argument shall have default
254 // arguments supplied in this or previous declarations. A
255 // default argument shall not be redefined by a later
256 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000257 //
258 // C++ [dcl.fct.default]p6:
259 // Except for member functions of class templates, the default arguments
260 // in a member function definition that appears outside of the class
261 // definition are added to the set of default arguments provided by the
262 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000263 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
264 ParmVarDecl *OldParam = Old->getParamDecl(p);
265 ParmVarDecl *NewParam = New->getParamDecl(p);
266
Douglas Gregor6cc15182009-09-11 18:44:32 +0000267 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000268 // FIXME: If the parameter doesn't have an identifier then the location
269 // points to the '=' which means that the fixit hint won't remove any
270 // extra spaces between the type and the '='.
271 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000272 if (NewParam->getIdentifier())
273 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000274
Mike Stump1eb44332009-09-09 15:08:12 +0000275 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000276 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000277 << NewParam->getDefaultArgRange()
278 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
279 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000280
281 // Look for the function declaration where the default argument was
282 // actually written, which may be a declaration prior to Old.
283 for (FunctionDecl *Older = Old->getPreviousDeclaration();
284 Older; Older = Older->getPreviousDeclaration()) {
285 if (!Older->getParamDecl(p)->hasDefaultArg())
286 break;
287
288 OldParam = Older->getParamDecl(p);
289 }
290
291 Diag(OldParam->getLocation(), diag::note_previous_definition)
292 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000293 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000294 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000295 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000296 if (OldParam->hasUninstantiatedDefaultArg())
297 NewParam->setUninstantiatedDefaultArg(
298 OldParam->getUninstantiatedDefaultArg());
299 else
300 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000301 } else if (NewParam->hasDefaultArg()) {
302 if (New->getDescribedFunctionTemplate()) {
303 // Paragraph 4, quoted above, only applies to non-template functions.
304 Diag(NewParam->getLocation(),
305 diag::err_param_default_argument_template_redecl)
306 << NewParam->getDefaultArgRange();
307 Diag(Old->getLocation(), diag::note_template_prev_declaration)
308 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000309 } else if (New->getTemplateSpecializationKind()
310 != TSK_ImplicitInstantiation &&
311 New->getTemplateSpecializationKind() != TSK_Undeclared) {
312 // C++ [temp.expr.spec]p21:
313 // Default function arguments shall not be specified in a declaration
314 // or a definition for one of the following explicit specializations:
315 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000316 // - the explicit specialization of a member function template;
317 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000318 // template where the class template specialization to which the
319 // member function specialization belongs is implicitly
320 // instantiated.
321 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
322 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
323 << New->getDeclName()
324 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000325 } else if (New->getDeclContext()->isDependentContext()) {
326 // C++ [dcl.fct.default]p6 (DR217):
327 // Default arguments for a member function of a class template shall
328 // be specified on the initial declaration of the member function
329 // within the class template.
330 //
331 // Reading the tea leaves a bit in DR217 and its reference to DR205
332 // leads me to the conclusion that one cannot add default function
333 // arguments for an out-of-line definition of a member function of a
334 // dependent type.
335 int WhichKind = 2;
336 if (CXXRecordDecl *Record
337 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
338 if (Record->getDescribedClassTemplate())
339 WhichKind = 0;
340 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
341 WhichKind = 1;
342 else
343 WhichKind = 2;
344 }
345
346 Diag(NewParam->getLocation(),
347 diag::err_param_default_argument_member_template_redecl)
348 << WhichKind
349 << NewParam->getDefaultArgRange();
350 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000351 }
352 }
353
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000354 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000355 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
356 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000357 Invalid = true;
358 }
359
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000361}
362
363/// CheckCXXDefaultArguments - Verify that the default arguments for a
364/// function declaration are well-formed according to C++
365/// [dcl.fct.default].
366void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
367 unsigned NumParams = FD->getNumParams();
368 unsigned p;
369
370 // Find first parameter with a default argument
371 for (p = 0; p < NumParams; ++p) {
372 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000373 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000374 break;
375 }
376
377 // C++ [dcl.fct.default]p4:
378 // In a given function declaration, all parameters
379 // subsequent to a parameter with a default argument shall
380 // have default arguments supplied in this or previous
381 // declarations. A default argument shall not be redefined
382 // by a later declaration (not even to the same value).
383 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000384 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000386 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000387 if (Param->isInvalidDecl())
388 /* We already complained about this parameter. */;
389 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000390 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000391 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000392 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000393 else
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000395 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 LastMissingDefaultArg = p;
398 }
399 }
400
401 if (LastMissingDefaultArg > 0) {
402 // Some default arguments were missing. Clear out all of the
403 // default arguments up to (and including) the last missing
404 // default argument, so that we leave the function parameters
405 // in a semantically valid state.
406 for (p = 0; p <= LastMissingDefaultArg; ++p) {
407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000408 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000409 if (!Param->hasUnparsedDefaultArg())
410 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000411 Param->setDefaultArg(0);
412 }
413 }
414 }
415}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000416
Douglas Gregorb48fe382008-10-31 09:07:45 +0000417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000423 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000424 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000425 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
427 } else
428 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
429
430 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000431 return &II == CurDecl->getIdentifier();
432 else
433 return false;
434}
435
Mike Stump1eb44332009-09-09 15:08:12 +0000436/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000437///
438/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
439/// and returns NULL otherwise.
440CXXBaseSpecifier *
441Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
442 SourceRange SpecifierRange,
443 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000444 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000445 SourceLocation BaseLoc) {
446 // C++ [class.union]p1:
447 // A union shall not have base classes.
448 if (Class->isUnion()) {
449 Diag(Class->getLocation(), diag::err_base_clause_on_union)
450 << SpecifierRange;
451 return 0;
452 }
453
454 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000455 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000456 Class->getTagKind() == RecordDecl::TK_class,
457 Access, BaseType);
458
459 // Base specifiers must be record types.
460 if (!BaseType->isRecordType()) {
461 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
462 return 0;
463 }
464
465 // C++ [class.union]p1:
466 // A union shall not be used as a base class.
467 if (BaseType->isUnionType()) {
468 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.derived]p2:
473 // The class-name in a base-specifier shall not be an incompletely
474 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000475 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000476 PDiag(diag::err_incomplete_base_class)
477 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000478 return 0;
479
Eli Friedman1d954f62009-08-15 21:55:26 +0000480 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000481 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 assert(BaseDecl && "Record type has no declaration");
483 BaseDecl = BaseDecl->getDefinition(Context);
484 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000485 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
486 assert(CXXBaseDecl && "Base type is not a C++ type");
487 if (!CXXBaseDecl->isEmpty())
488 Class->setEmpty(false);
489 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490 Class->setPolymorphic(true);
491
492 // C++ [dcl.init.aggr]p1:
493 // An aggregate is [...] a class with [...] no base classes [...].
494 Class->setAggregate(false);
495 Class->setPOD(false);
496
Anders Carlsson347ba892009-04-16 00:08:20 +0000497 if (Virtual) {
498 // C++ [class.ctor]p5:
499 // A constructor is trivial if its class has no virtual base classes.
500 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000501
502 // C++ [class.copy]p6:
503 // A copy constructor is trivial if its class has no virtual base classes.
504 Class->setHasTrivialCopyConstructor(false);
505
506 // C++ [class.copy]p11:
507 // A copy assignment operator is trivial if its class has no virtual
508 // base classes.
509 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000510
511 // C++0x [meta.unary.prop] is_empty:
512 // T is a class type, but not a union type, with ... no virtual base
513 // classes
514 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000515 } else {
516 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000517 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000518 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000519 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
520 Class->setHasTrivialConstructor(false);
521
522 // C++ [class.copy]p6:
523 // A copy constructor is trivial if all the direct base classes of its
524 // class have trivial copy constructors.
525 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
526 Class->setHasTrivialCopyConstructor(false);
527
528 // C++ [class.copy]p11:
529 // A copy assignment operator is trivial if all the direct base classes
530 // of its class have trivial copy assignment operators.
531 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
532 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000533 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000534
535 // C++ [class.ctor]p3:
536 // A destructor is trivial if all the direct base classes of its class
537 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000538 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
539 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor2943aed2009-03-03 04:44:36 +0000541 // Create the base specifier.
542 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000543 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
544 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000545 Access, BaseType);
546}
547
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000548/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
549/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000550/// example:
551/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000552/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000553Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000554Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000555 bool Virtual, AccessSpecifier Access,
556 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000557 if (!classdecl)
558 return true;
559
Douglas Gregor40808ce2009-03-09 23:48:35 +0000560 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000561 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000562 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000563 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
564 Virtual, Access,
565 BaseType, BaseLoc))
566 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Douglas Gregor2943aed2009-03-03 04:44:36 +0000568 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000569}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000570
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571/// \brief Performs the actual work of attaching the given base class
572/// specifiers to a C++ class.
573bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
574 unsigned NumBases) {
575 if (NumBases == 0)
576 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000577
578 // Used to keep track of which base types we have already seen, so
579 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000580 // that the key is always the unqualified canonical type of the base
581 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000582 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
583
584 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000585 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000587 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000588 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000590 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000591
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000592 if (KnownBaseTypes[NewBaseType]) {
593 // C++ [class.mi]p3:
594 // A class shall not be specified as a direct base class of a
595 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000597 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000598 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000600
601 // Delete the duplicate base class specifier; we're going to
602 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000603 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000604
605 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000606 } else {
607 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608 KnownBaseTypes[NewBaseType] = Bases[idx];
609 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610 }
611 }
612
613 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000614 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615
616 // Delete the remaining (good) base class specifiers, since their
617 // data has been copied into the CXXRecordDecl.
618 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000619 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620
621 return Invalid;
622}
623
624/// ActOnBaseSpecifiers - Attach the given base specifiers to the
625/// class, after checking whether there are any duplicate base
626/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000627void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000628 unsigned NumBases) {
629 if (!ClassDecl || !Bases || !NumBases)
630 return;
631
632 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000633 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000634 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000635}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000636
Douglas Gregora8f32e02009-10-06 17:59:45 +0000637/// \brief Determine whether the type \p Derived is a C++ class that is
638/// derived from the type \p Base.
639bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
640 if (!getLangOptions().CPlusPlus)
641 return false;
642
643 const RecordType *DerivedRT = Derived->getAs<RecordType>();
644 if (!DerivedRT)
645 return false;
646
647 const RecordType *BaseRT = Base->getAs<RecordType>();
648 if (!BaseRT)
649 return false;
650
651 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
652 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
653 return DerivedRD->isDerivedFrom(BaseRD);
654}
655
656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
661
662 const RecordType *DerivedRT = Derived->getAs<RecordType>();
663 if (!DerivedRT)
664 return false;
665
666 const RecordType *BaseRT = Base->getAs<RecordType>();
667 if (!BaseRT)
668 return false;
669
670 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
671 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
672 return DerivedRD->isDerivedFrom(BaseRD, Paths);
673}
674
675/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
676/// conversion (where Derived and Base are class types) is
677/// well-formed, meaning that the conversion is unambiguous (and
678/// that all of the base classes are accessible). Returns true
679/// and emits a diagnostic if the code is ill-formed, returns false
680/// otherwise. Loc is the location where this routine should point to
681/// if there is an error, and Range is the source range to highlight
682/// if there is an error.
683bool
684Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
685 unsigned InaccessibleBaseID,
686 unsigned AmbigiousBaseConvID,
687 SourceLocation Loc, SourceRange Range,
688 DeclarationName Name) {
689 // First, determine whether the path from Derived to Base is
690 // ambiguous. This is slightly more expensive than checking whether
691 // the Derived to Base conversion exists, because here we need to
692 // explore multiple paths to determine if there is an ambiguity.
693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
694 /*DetectVirtual=*/false);
695 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
696 assert(DerivationOkay &&
697 "Can only be used with a derived-to-base conversion");
698 (void)DerivationOkay;
699
700 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000701 if (InaccessibleBaseID == 0)
702 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000703 // Check that the base class can be accessed.
704 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
705 Name);
706 }
707
708 // We know that the derived-to-base conversion is ambiguous, and
709 // we're going to produce a diagnostic. Perform the derived-to-base
710 // search just one more time to compute all of the possible paths so
711 // that we can print them out. This is more expensive than any of
712 // the previous derived-to-base checks we've done, but at this point
713 // performance isn't as much of an issue.
714 Paths.clear();
715 Paths.setRecordingPaths(true);
716 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
717 assert(StillOkay && "Can only be used with a derived-to-base conversion");
718 (void)StillOkay;
719
720 // Build up a textual representation of the ambiguous paths, e.g.,
721 // D -> B -> A, that will be used to illustrate the ambiguous
722 // conversions in the diagnostic. We only print one of the paths
723 // to each base class subobject.
724 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
725
726 Diag(Loc, AmbigiousBaseConvID)
727 << Derived << Base << PathDisplayStr << Range << Name;
728 return true;
729}
730
731bool
732Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000733 SourceLocation Loc, SourceRange Range,
734 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000735 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000736 IgnoreAccess ? 0 :
737 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000738 diag::err_ambiguous_derived_to_base_conv,
739 Loc, Range, DeclarationName());
740}
741
742
743/// @brief Builds a string representing ambiguous paths from a
744/// specific derived class to different subobjects of the same base
745/// class.
746///
747/// This function builds a string that can be used in error messages
748/// to show the different paths that one can take through the
749/// inheritance hierarchy to go from the derived class to different
750/// subobjects of a base class. The result looks something like this:
751/// @code
752/// struct D -> struct B -> struct A
753/// struct D -> struct C -> struct A
754/// @endcode
755std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
756 std::string PathDisplayStr;
757 std::set<unsigned> DisplayedPaths;
758 for (CXXBasePaths::paths_iterator Path = Paths.begin();
759 Path != Paths.end(); ++Path) {
760 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
761 // We haven't displayed a path to this particular base
762 // class subobject yet.
763 PathDisplayStr += "\n ";
764 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
765 for (CXXBasePath::const_iterator Element = Path->begin();
766 Element != Path->end(); ++Element)
767 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
768 }
769 }
770
771 return PathDisplayStr;
772}
773
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000774//===----------------------------------------------------------------------===//
775// C++ class member Handling
776//===----------------------------------------------------------------------===//
777
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000778/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
779/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
780/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000781/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000782Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000783Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000784 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000785 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000786 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000787 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000788 Expr *BitWidth = static_cast<Expr*>(BW);
789 Expr *Init = static_cast<Expr*>(InitExpr);
790 SourceLocation Loc = D.getIdentifierLoc();
791
Sebastian Redl669d5d72008-11-14 23:42:31 +0000792 bool isFunc = D.isFunctionDeclarator();
793
John McCall67d1a672009-08-06 02:15:43 +0000794 assert(!DS.isFriendSpecified());
795
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000796 // C++ 9.2p6: A member shall not be declared to have automatic storage
797 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000798 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
799 // data members and cannot be applied to names declared const or static,
800 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000801 switch (DS.getStorageClassSpec()) {
802 case DeclSpec::SCS_unspecified:
803 case DeclSpec::SCS_typedef:
804 case DeclSpec::SCS_static:
805 // FALL THROUGH.
806 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000807 case DeclSpec::SCS_mutable:
808 if (isFunc) {
809 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000810 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000811 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000812 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Sebastian Redla11f42f2008-11-17 23:24:37 +0000814 // FIXME: It would be nicer if the keyword was ignored only for this
815 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000816 D.getMutableDeclSpec().ClearStorageClassSpecs();
817 } else {
818 QualType T = GetTypeForDeclarator(D, S);
819 diag::kind err = static_cast<diag::kind>(0);
820 if (T->isReferenceType())
821 err = diag::err_mutable_reference;
822 else if (T.isConstQualified())
823 err = diag::err_mutable_const;
824 if (err != 0) {
825 if (DS.getStorageClassSpecLoc().isValid())
826 Diag(DS.getStorageClassSpecLoc(), err);
827 else
828 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000829 // FIXME: It would be nicer if the keyword was ignored only for this
830 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000831 D.getMutableDeclSpec().ClearStorageClassSpecs();
832 }
833 }
834 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000835 default:
836 if (DS.getStorageClassSpecLoc().isValid())
837 Diag(DS.getStorageClassSpecLoc(),
838 diag::err_storageclass_invalid_for_member);
839 else
840 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
841 D.getMutableDeclSpec().ClearStorageClassSpecs();
842 }
843
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000844 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000845 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000846 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000847 // Check also for this case:
848 //
849 // typedef int f();
850 // f a;
851 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000852 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000853 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000854 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000855
Sebastian Redl669d5d72008-11-14 23:42:31 +0000856 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
857 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000858 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000859
860 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000861 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000862 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000863 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
864 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000865 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000866 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000867 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
868 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000869 if (!Member) {
870 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000871 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000872 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000873
874 // Non-instance-fields can't have a bitfield.
875 if (BitWidth) {
876 if (Member->isInvalidDecl()) {
877 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000878 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000879 // C++ 9.6p3: A bit-field shall not be a static member.
880 // "static member 'A' cannot be a bit-field"
881 Diag(Loc, diag::err_static_not_bitfield)
882 << Name << BitWidth->getSourceRange();
883 } else if (isa<TypedefDecl>(Member)) {
884 // "typedef member 'x' cannot be a bit-field"
885 Diag(Loc, diag::err_typedef_not_bitfield)
886 << Name << BitWidth->getSourceRange();
887 } else {
888 // A function typedef ("typedef int f(); f a;").
889 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
890 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000891 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000892 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000893 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner8b963ef2009-03-05 23:01:03 +0000895 DeleteExpr(BitWidth);
896 BitWidth = 0;
897 Member->setInvalidDecl();
898 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000899
900 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Douglas Gregor37b372b2009-08-20 22:52:58 +0000902 // If we have declared a member function template, set the access of the
903 // templated declaration as well.
904 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
905 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000906 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000907
Douglas Gregor10bd3682008-11-17 22:58:34 +0000908 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000909
Douglas Gregor021c3b32009-03-11 23:00:04 +0000910 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000911 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000912 if (Deleted) // FIXME: Source location is not very good.
913 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000914
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000915 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000916 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000917 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000918 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000919 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000920}
921
Douglas Gregor7ad83902008-11-05 04:29:56 +0000922/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000923Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000924Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000925 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000926 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000927 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000928 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000929 SourceLocation IdLoc,
930 SourceLocation LParenLoc,
931 ExprTy **Args, unsigned NumArgs,
932 SourceLocation *CommaLocs,
933 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000934 if (!ConstructorD)
935 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000937 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
939 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000940 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000941 if (!Constructor) {
942 // The user wrote a constructor initializer on a function that is
943 // not a C++ constructor. Ignore the error for now, because we may
944 // have more member initializers coming; we'll diagnose it just
945 // once in ActOnMemInitializers.
946 return true;
947 }
948
949 CXXRecordDecl *ClassDecl = Constructor->getParent();
950
951 // C++ [class.base.init]p2:
952 // Names in a mem-initializer-id are looked up in the scope of the
953 // constructor’s class and, if not found in that scope, are looked
954 // up in the scope containing the constructor’s
955 // definition. [Note: if the constructor’s class contains a member
956 // with the same name as a direct or virtual base class of the
957 // class, a mem-initializer-id naming the member or base class and
958 // composed of a single identifier refers to the class member. A
959 // mem-initializer-id for the hidden base class may be specified
960 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000961 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000962 // Look for a member, first.
963 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000964 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000965 = ClassDecl->lookup(MemberOrBase);
966 if (Result.first != Result.second)
967 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000968
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000969 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000970
Eli Friedman59c04372009-07-29 19:44:27 +0000971 if (Member)
972 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
973 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000974 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000975 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000976 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000977 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000978 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000979 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
980 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000982 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000983
Eli Friedman59c04372009-07-29 19:44:27 +0000984 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
985 RParenLoc, ClassDecl);
986}
987
John McCallb4190042009-11-04 23:02:40 +0000988/// Checks an initializer expression for use of uninitialized fields, such as
989/// containing the field that is being initialized. Returns true if there is an
990/// uninitialized field was used an updates the SourceLocation parameter; false
991/// otherwise.
992static bool InitExprContainsUninitializedFields(const Stmt* S,
993 const FieldDecl* LhsField,
994 SourceLocation* L) {
995 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
996 if (ME) {
997 const NamedDecl* RhsField = ME->getMemberDecl();
998 if (RhsField == LhsField) {
999 // Initializing a field with itself. Throw a warning.
1000 // But wait; there are exceptions!
1001 // Exception #1: The field may not belong to this record.
1002 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1003 const Expr* base = ME->getBase();
1004 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1005 // Even though the field matches, it does not belong to this record.
1006 return false;
1007 }
1008 // None of the exceptions triggered; return true to indicate an
1009 // uninitialized field was used.
1010 *L = ME->getMemberLoc();
1011 return true;
1012 }
1013 }
1014 bool found = false;
1015 for (Stmt::const_child_iterator it = S->child_begin();
1016 it != S->child_end() && found == false;
1017 ++it) {
1018 if (isa<CallExpr>(S)) {
1019 // Do not descend into function calls or constructors, as the use
1020 // of an uninitialized field may be valid. One would have to inspect
1021 // the contents of the function/ctor to determine if it is safe or not.
1022 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1023 // may be safe, depending on what the function/ctor does.
1024 continue;
1025 }
1026 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1027 }
1028 return found;
1029}
1030
Eli Friedman59c04372009-07-29 19:44:27 +00001031Sema::MemInitResult
1032Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1033 unsigned NumArgs, SourceLocation IdLoc,
1034 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001035 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1036 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1037 ExprTemporaries.clear();
1038
John McCallb4190042009-11-04 23:02:40 +00001039 // Diagnose value-uses of fields to initialize themselves, e.g.
1040 // foo(foo)
1041 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001042 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001043 for (unsigned i = 0; i < NumArgs; ++i) {
1044 SourceLocation L;
1045 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1046 // FIXME: Return true in the case when other fields are used before being
1047 // uninitialized. For example, let this field be the i'th field. When
1048 // initializing the i'th field, throw a warning if any of the >= i'th
1049 // fields are used, as they are not yet initialized.
1050 // Right now we are only handling the case where the i'th field uses
1051 // itself in its initializer.
1052 Diag(L, diag::warn_field_is_uninit);
1053 }
1054 }
1055
Eli Friedman59c04372009-07-29 19:44:27 +00001056 bool HasDependentArg = false;
1057 for (unsigned i = 0; i < NumArgs; i++)
1058 HasDependentArg |= Args[i]->isTypeDependent();
1059
1060 CXXConstructorDecl *C = 0;
1061 QualType FieldType = Member->getType();
1062 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1063 FieldType = Array->getElementType();
1064 if (FieldType->isDependentType()) {
1065 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001066 } else if (FieldType->isRecordType()) {
1067 // Member is a record (struct/union/class), so pass the initializer
1068 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001069 if (!HasDependentArg) {
1070 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1071
1072 C = PerformInitializationByConstructor(FieldType,
1073 MultiExprArg(*this,
1074 (void**)Args,
1075 NumArgs),
1076 IdLoc,
1077 SourceRange(IdLoc, RParenLoc),
1078 Member->getDeclName(), IK_Direct,
1079 ConstructorArgs);
1080
1081 if (C) {
1082 // Take over the constructor arguments as our own.
1083 NumArgs = ConstructorArgs.size();
1084 Args = (Expr **)ConstructorArgs.take();
1085 }
1086 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001087 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001088 // The member type is not a record type (or an array of record
1089 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001090 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001091 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1092 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001093 Expr *NewExp;
1094 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001095 if (FieldType->isReferenceType()) {
1096 Diag(IdLoc, diag::err_null_intialized_reference_member)
1097 << Member->getDeclName();
1098 return Diag(Member->getLocation(), diag::note_declared_at);
1099 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001100 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1101 NumArgs = 1;
1102 }
1103 else
1104 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001105 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1106 return true;
1107 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001108 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001109
1110 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1111 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1112 ExprTemporaries.clear();
1113
Eli Friedman59c04372009-07-29 19:44:27 +00001114 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001115 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001116 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001117}
1118
1119Sema::MemInitResult
1120Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1121 unsigned NumArgs, SourceLocation IdLoc,
1122 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1123 bool HasDependentArg = false;
1124 for (unsigned i = 0; i < NumArgs; i++)
1125 HasDependentArg |= Args[i]->isTypeDependent();
1126
1127 if (!BaseType->isDependentType()) {
1128 if (!BaseType->isRecordType())
1129 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1130 << BaseType << SourceRange(IdLoc, RParenLoc);
1131
1132 // C++ [class.base.init]p2:
1133 // [...] Unless the mem-initializer-id names a nonstatic data
1134 // member of the constructor’s class or a direct or virtual base
1135 // of that class, the mem-initializer is ill-formed. A
1136 // mem-initializer-list can initialize a base class using any
1137 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Eli Friedman59c04372009-07-29 19:44:27 +00001139 // First, check for a direct base class.
1140 const CXXBaseSpecifier *DirectBaseSpec = 0;
1141 for (CXXRecordDecl::base_class_const_iterator Base =
1142 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001143 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001144 // We found a direct base of this type. That's what we're
1145 // initializing.
1146 DirectBaseSpec = &*Base;
1147 break;
1148 }
1149 }
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Eli Friedman59c04372009-07-29 19:44:27 +00001151 // Check for a virtual base class.
1152 // FIXME: We might be able to short-circuit this if we know in advance that
1153 // there are no virtual bases.
1154 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1155 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1156 // We haven't found a base yet; search the class hierarchy for a
1157 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001158 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1159 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001160 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001161 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001162 Path != Paths.end(); ++Path) {
1163 if (Path->back().Base->isVirtual()) {
1164 VirtualBaseSpec = Path->back().Base;
1165 break;
1166 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001167 }
1168 }
1169 }
Eli Friedman59c04372009-07-29 19:44:27 +00001170
1171 // C++ [base.class.init]p2:
1172 // If a mem-initializer-id is ambiguous because it designates both
1173 // a direct non-virtual base class and an inherited virtual base
1174 // class, the mem-initializer is ill-formed.
1175 if (DirectBaseSpec && VirtualBaseSpec)
1176 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1177 << BaseType << SourceRange(IdLoc, RParenLoc);
1178 // C++ [base.class.init]p2:
1179 // Unless the mem-initializer-id names a nonstatic data membeer of the
1180 // constructor's class ot a direst or virtual base of that class, the
1181 // mem-initializer is ill-formed.
1182 if (!DirectBaseSpec && !VirtualBaseSpec)
1183 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1184 << BaseType << ClassDecl->getNameAsCString()
1185 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001186 }
1187
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001188 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001189 if (!BaseType->isDependentType() && !HasDependentArg) {
1190 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001191 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001192 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1193
1194 C = PerformInitializationByConstructor(BaseType,
1195 MultiExprArg(*this,
1196 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001197 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001198 Name, IK_Direct,
1199 ConstructorArgs);
1200 if (C) {
1201 // Take over the constructor arguments as our own.
1202 NumArgs = ConstructorArgs.size();
1203 Args = (Expr **)ConstructorArgs.take();
1204 }
Eli Friedman59c04372009-07-29 19:44:27 +00001205 }
1206
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001207 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1208 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1209 ExprTemporaries.clear();
1210
Mike Stump1eb44332009-09-09 15:08:12 +00001211 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001212 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001213}
1214
Eli Friedman80c30da2009-11-09 19:20:36 +00001215bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001216Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001217 CXXBaseOrMemberInitializer **Initializers,
1218 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001219 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001220 // We need to build the initializer AST according to order of construction
1221 // and not what user specified in the Initializers list.
1222 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1223 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1224 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1225 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001226 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001228 for (unsigned i = 0; i < NumInitializers; i++) {
1229 CXXBaseOrMemberInitializer *Member = Initializers[i];
1230 if (Member->isBaseInitializer()) {
1231 if (Member->getBaseClass()->isDependentType())
1232 HasDependentBaseInit = true;
1233 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1234 } else {
1235 AllBaseFields[Member->getMember()] = Member;
1236 }
1237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001239 if (HasDependentBaseInit) {
1240 // FIXME. This does not preserve the ordering of the initializers.
1241 // Try (with -Wreorder)
1242 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001243 // template<class X> struct B : A<X> {
1244 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001245 // int x1;
1246 // };
1247 // B<int> x;
1248 // On seeing one dependent type, we should essentially exit this routine
1249 // while preserving user-declared initializer list. When this routine is
1250 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001251 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001253 // If we have a dependent base initialization, we can't determine the
1254 // association between initializers and bases; just dump the known
1255 // initializers into the list, and don't try to deal with other bases.
1256 for (unsigned i = 0; i < NumInitializers; i++) {
1257 CXXBaseOrMemberInitializer *Member = Initializers[i];
1258 if (Member->isBaseInitializer())
1259 AllToInit.push_back(Member);
1260 }
1261 } else {
1262 // Push virtual bases before others.
1263 for (CXXRecordDecl::base_class_iterator VBase =
1264 ClassDecl->vbases_begin(),
1265 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1266 if (VBase->getType()->isDependentType())
1267 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001268 if (CXXBaseOrMemberInitializer *Value
1269 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001270 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001271 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001272 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001273 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001274 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001275 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001276 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001277 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001278 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1279 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1280 << 0 << VBase->getType();
1281 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1282 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001283 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001284 continue;
1285 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001286
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001287 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1288 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1289 Constructor->getLocation(), CtorArgs))
1290 continue;
1291
1292 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1293
Anders Carlsson8db68da2009-11-13 20:11:49 +00001294 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1295 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1296 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001297 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001298 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1299 CtorArgs.takeAs<Expr>(),
1300 CtorArgs.size(), Ctor,
1301 SourceLocation(),
1302 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001303 AllToInit.push_back(Member);
1304 }
1305 }
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001307 for (CXXRecordDecl::base_class_iterator Base =
1308 ClassDecl->bases_begin(),
1309 E = ClassDecl->bases_end(); Base != E; ++Base) {
1310 // Virtuals are in the virtual base list and already constructed.
1311 if (Base->isVirtual())
1312 continue;
1313 // Skip dependent types.
1314 if (Base->getType()->isDependentType())
1315 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001316 if (CXXBaseOrMemberInitializer *Value
1317 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001318 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001319 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001320 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001321 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001322 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001323 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001324 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001325 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001326 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1327 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1328 << 0 << Base->getType();
1329 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1330 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001331 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001332 continue;
1333 }
1334
1335 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1336 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1337 Constructor->getLocation(), CtorArgs))
1338 continue;
1339
1340 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001341
Anders Carlsson8db68da2009-11-13 20:11:49 +00001342 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1343 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1344 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001345 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001346 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1347 CtorArgs.takeAs<Expr>(),
1348 CtorArgs.size(), Ctor,
1349 SourceLocation(),
1350 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001351 AllToInit.push_back(Member);
1352 }
1353 }
1354 }
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001356 // non-static data members.
1357 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1358 E = ClassDecl->field_end(); Field != E; ++Field) {
1359 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001360 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001361 Field->getType()->getAs<RecordType>()) {
1362 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001363 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001364 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001365 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1366 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1367 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1368 // set to the anonymous union data member used in the initializer
1369 // list.
1370 Value->setMember(*Field);
1371 Value->setAnonUnionMember(*FA);
1372 AllToInit.push_back(Value);
1373 break;
1374 }
1375 }
1376 }
1377 continue;
1378 }
1379 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1380 AllToInit.push_back(Value);
1381 continue;
1382 }
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Eli Friedman49c16da2009-11-09 01:05:47 +00001384 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001385 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001386
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001387 QualType FT = Context.getBaseElementType((*Field)->getType());
1388 if (const RecordType* RT = FT->getAs<RecordType>()) {
1389 CXXConstructorDecl *Ctor =
1390 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001391 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001392 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1393 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1394 << 1 << (*Field)->getDeclName();
1395 Diag(Field->getLocation(), diag::note_field_decl);
1396 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1397 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001398 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001399 continue;
1400 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001401
1402 if (FT.isConstQualified() && Ctor->isTrivial()) {
1403 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1404 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1405 << 1 << (*Field)->getDeclName();
1406 Diag((*Field)->getLocation(), diag::note_declared_at);
1407 HadError = true;
1408 }
1409
1410 // Don't create initializers for trivial constructors, since they don't
1411 // actually need to be run.
1412 if (Ctor->isTrivial())
1413 continue;
1414
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001415 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1416 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1417 Constructor->getLocation(), CtorArgs))
1418 continue;
1419
Anders Carlsson8db68da2009-11-13 20:11:49 +00001420 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1421 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1422 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001423 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001424 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1425 CtorArgs.size(), Ctor,
1426 SourceLocation(),
1427 SourceLocation());
1428
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001429 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001430 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001431 }
1432 else if (FT->isReferenceType()) {
1433 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001434 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1435 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001436 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001437 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001438 }
1439 else if (FT.isConstQualified()) {
1440 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001441 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1442 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001443 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001444 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001445 }
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001448 NumInitializers = AllToInit.size();
1449 if (NumInitializers > 0) {
1450 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1451 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1452 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001454 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1455 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1456 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1457 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001458
1459 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001460}
1461
Eli Friedman6347f422009-07-21 19:28:10 +00001462static void *GetKeyForTopLevelField(FieldDecl *Field) {
1463 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001464 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001465 if (RT->getDecl()->isAnonymousStructOrUnion())
1466 return static_cast<void *>(RT->getDecl());
1467 }
1468 return static_cast<void *>(Field);
1469}
1470
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001471static void *GetKeyForBase(QualType BaseType) {
1472 if (const RecordType *RT = BaseType->getAs<RecordType>())
1473 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001475 assert(0 && "Unexpected base type!");
1476 return 0;
1477}
1478
Mike Stump1eb44332009-09-09 15:08:12 +00001479static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001480 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001481 // For fields injected into the class via declaration of an anonymous union,
1482 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001483 if (Member->isMemberInitializer()) {
1484 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Eli Friedman49c16da2009-11-09 01:05:47 +00001486 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001488 // in AnonUnionMember field.
1489 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1490 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001491 if (Field->getDeclContext()->isRecord()) {
1492 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1493 if (RD->isAnonymousStructOrUnion())
1494 return static_cast<void *>(RD);
1495 }
1496 return static_cast<void *>(Field);
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001499 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001500}
1501
John McCall6aee6212009-11-04 23:13:52 +00001502/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001503void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001504 SourceLocation ColonLoc,
1505 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001506 if (!ConstructorDecl)
1507 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001508
1509 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001510
1511 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001512 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Anders Carlssona7b35212009-03-25 02:58:17 +00001514 if (!Constructor) {
1515 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1516 return;
1517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001519 if (!Constructor->isDependentContext()) {
1520 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1521 bool err = false;
1522 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001523 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001524 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1525 void *KeyToMember = GetKeyForMember(Member);
1526 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1527 if (!PrevMember) {
1528 PrevMember = Member;
1529 continue;
1530 }
1531 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001532 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001533 diag::error_multiple_mem_initialization)
1534 << Field->getNameAsString();
1535 else {
1536 Type *BaseClass = Member->getBaseClass();
1537 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001538 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001539 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001540 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001541 }
1542 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1543 << 0;
1544 err = true;
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001547 if (err)
1548 return;
1549 }
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Eli Friedman49c16da2009-11-09 01:05:47 +00001551 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001552 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001553 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001555 if (Constructor->isDependentContext())
1556 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
1558 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001559 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001560 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001561 Diagnostic::Ignored)
1562 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001564 // Also issue warning if order of ctor-initializer list does not match order
1565 // of 1) base class declarations and 2) order of non-static data members.
1566 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001568 CXXRecordDecl *ClassDecl
1569 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1570 // Push virtual bases before others.
1571 for (CXXRecordDecl::base_class_iterator VBase =
1572 ClassDecl->vbases_begin(),
1573 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001574 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001576 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1577 E = ClassDecl->bases_end(); Base != E; ++Base) {
1578 // Virtuals are alread in the virtual base list and are constructed
1579 // first.
1580 if (Base->isVirtual())
1581 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001582 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001583 }
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001585 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1586 E = ClassDecl->field_end(); Field != E; ++Field)
1587 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001589 int Last = AllBaseOrMembers.size();
1590 int curIndex = 0;
1591 CXXBaseOrMemberInitializer *PrevMember = 0;
1592 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001593 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001594 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1595 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001596
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001597 for (; curIndex < Last; curIndex++)
1598 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1599 break;
1600 if (curIndex == Last) {
1601 assert(PrevMember && "Member not in member list?!");
1602 // Initializer as specified in ctor-initializer list is out of order.
1603 // Issue a warning diagnostic.
1604 if (PrevMember->isBaseInitializer()) {
1605 // Diagnostics is for an initialized base class.
1606 Type *BaseClass = PrevMember->getBaseClass();
1607 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001608 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001609 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001610 } else {
1611 FieldDecl *Field = PrevMember->getMember();
1612 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001613 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001614 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001615 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001616 // Also the note!
1617 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001618 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001619 diag::note_fieldorbase_initialized_here) << 0
1620 << Field->getNameAsString();
1621 else {
1622 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001623 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001624 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001625 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001626 }
1627 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001628 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001629 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001630 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001631 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001632 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001633}
1634
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001635void
1636Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1637 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1638 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001640 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1641 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1642 if (VBase->getType()->isDependentType())
1643 continue;
1644 // Skip over virtual bases which have trivial destructors.
1645 CXXRecordDecl *BaseClassDecl
1646 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1647 if (BaseClassDecl->hasTrivialDestructor())
1648 continue;
1649 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001650 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001651 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001652
1653 uintptr_t Member =
1654 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001655 | CXXDestructorDecl::VBASE;
1656 AllToDestruct.push_back(Member);
1657 }
1658 for (CXXRecordDecl::base_class_iterator Base =
1659 ClassDecl->bases_begin(),
1660 E = ClassDecl->bases_end(); Base != E; ++Base) {
1661 if (Base->isVirtual())
1662 continue;
1663 if (Base->getType()->isDependentType())
1664 continue;
1665 // Skip over virtual bases which have trivial destructors.
1666 CXXRecordDecl *BaseClassDecl
1667 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1668 if (BaseClassDecl->hasTrivialDestructor())
1669 continue;
1670 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001671 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001672 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001673 uintptr_t Member =
1674 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001675 | CXXDestructorDecl::DRCTNONVBASE;
1676 AllToDestruct.push_back(Member);
1677 }
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001679 // non-static data members.
1680 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1681 E = ClassDecl->field_end(); Field != E; ++Field) {
1682 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001684 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1685 // Skip over virtual bases which have trivial destructors.
1686 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1687 if (FieldClassDecl->hasTrivialDestructor())
1688 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001689 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001690 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001691 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001692 const_cast<CXXDestructorDecl*>(Dtor));
1693 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1694 AllToDestruct.push_back(Member);
1695 }
1696 }
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001698 unsigned NumDestructions = AllToDestruct.size();
1699 if (NumDestructions > 0) {
1700 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001701 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001702 new (Context) uintptr_t [NumDestructions];
1703 // Insert in reverse order.
1704 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1705 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1706 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1707 }
1708}
1709
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001710void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001711 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001712 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001714 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001715
1716 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001717 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001718 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001719}
1720
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001721namespace {
1722 /// PureVirtualMethodCollector - traverses a class and its superclasses
1723 /// and determines if it has any pure virtual methods.
1724 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1725 ASTContext &Context;
1726
Sebastian Redldfe292d2009-03-22 21:28:55 +00001727 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001728 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001729
1730 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001731 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001733 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001735 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001736 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001737 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001739 MethodList List;
1740 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001742 // Copy the temporary list to methods, and make sure to ignore any
1743 // null entries.
1744 for (size_t i = 0, e = List.size(); i != e; ++i) {
1745 if (List[i])
1746 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001747 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001748 }
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001750 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001752 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1753 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001754 };
Mike Stump1eb44332009-09-09 15:08:12 +00001755
1756 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001757 MethodList& Methods) {
1758 // First, collect the pure virtual methods for the base classes.
1759 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1760 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001761 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001762 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001763 if (BaseDecl && BaseDecl->isAbstract())
1764 Collect(BaseDecl, Methods);
1765 }
1766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001768 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001769 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001771 MethodSetTy OverriddenMethods;
1772 size_t MethodsSize = Methods.size();
1773
Mike Stump1eb44332009-09-09 15:08:12 +00001774 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001775 i != e; ++i) {
1776 // Traverse the record, looking for methods.
1777 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001778 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001779 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001780 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Anders Carlsson27823022009-10-18 19:34:08 +00001782 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001783 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1784 E = MD->end_overridden_methods(); I != E; ++I) {
1785 // Keep track of the overridden methods.
1786 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001787 }
1788 }
1789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790
1791 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001792 // overridden.
1793 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1794 if (OverriddenMethods.count(Methods[i]))
1795 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001796 }
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001798 }
1799}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001800
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001801
Mike Stump1eb44332009-09-09 15:08:12 +00001802bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001803 unsigned DiagID, AbstractDiagSelID SelID,
1804 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001805 if (SelID == -1)
1806 return RequireNonAbstractType(Loc, T,
1807 PDiag(DiagID), CurrentRD);
1808 else
1809 return RequireNonAbstractType(Loc, T,
1810 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001811}
1812
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001813bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1814 const PartialDiagnostic &PD,
1815 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001816 if (!getLangOptions().CPlusPlus)
1817 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Anders Carlsson11f21a02009-03-23 19:10:31 +00001819 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001820 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001821 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Ted Kremenek6217b802009-07-29 21:53:49 +00001823 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001824 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001825 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001826 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001828 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001829 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Ted Kremenek6217b802009-07-29 21:53:49 +00001832 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001833 if (!RT)
1834 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001836 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1837 if (!RD)
1838 return false;
1839
Anders Carlssone65a3c82009-03-24 17:23:42 +00001840 if (CurrentRD && CurrentRD != RD)
1841 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001843 if (!RD->isAbstract())
1844 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001846 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001848 // Check if we've already emitted the list of pure virtual functions for this
1849 // class.
1850 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1851 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001853 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001854
1855 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001856 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1857 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001858
1859 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001860 MD->getDeclName();
1861 }
1862
1863 if (!PureVirtualClassDiagSet)
1864 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1865 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001867 return true;
1868}
1869
Anders Carlsson8211eff2009-03-24 01:19:16 +00001870namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001871 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001872 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1873 Sema &SemaRef;
1874 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Anders Carlssone65a3c82009-03-24 17:23:42 +00001876 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001877 bool Invalid = false;
1878
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001879 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1880 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001881 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001882
Anders Carlsson8211eff2009-03-24 01:19:16 +00001883 return Invalid;
1884 }
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Anders Carlssone65a3c82009-03-24 17:23:42 +00001886 public:
1887 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1888 : SemaRef(SemaRef), AbstractClass(ac) {
1889 Visit(SemaRef.Context.getTranslationUnitDecl());
1890 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001891
Anders Carlssone65a3c82009-03-24 17:23:42 +00001892 bool VisitFunctionDecl(const FunctionDecl *FD) {
1893 if (FD->isThisDeclarationADefinition()) {
1894 // No need to do the check if we're in a definition, because it requires
1895 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001896 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001897 return VisitDeclContext(FD);
1898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Anders Carlssone65a3c82009-03-24 17:23:42 +00001900 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001901 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001902 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001903 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1904 diag::err_abstract_type_in_decl,
1905 Sema::AbstractReturnType,
1906 AbstractClass);
1907
Mike Stump1eb44332009-09-09 15:08:12 +00001908 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001909 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001910 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001911 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001912 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001913 VD->getOriginalType(),
1914 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001915 Sema::AbstractParamType,
1916 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001917 }
1918
1919 return Invalid;
1920 }
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Anders Carlssone65a3c82009-03-24 17:23:42 +00001922 bool VisitDecl(const Decl* D) {
1923 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1924 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Anders Carlssone65a3c82009-03-24 17:23:42 +00001926 return false;
1927 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001928 };
1929}
1930
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001931void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001932 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001933 SourceLocation LBrac,
1934 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001935 if (!TagDecl)
1936 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Douglas Gregor42af25f2009-05-11 19:58:34 +00001938 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001939 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001940 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001941 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001942
Chris Lattnerb28317a2009-03-28 19:18:32 +00001943 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001944 if (!RD->isAbstract()) {
1945 // Collect all the pure virtual methods and see if this is an abstract
1946 // class after all.
1947 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001948 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001949 RD->setAbstract(true);
1950 }
Mike Stump1eb44332009-09-09 15:08:12 +00001951
1952 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001953 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Douglas Gregor663b5a02009-10-14 20:14:33 +00001955 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001956 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001957}
1958
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001959/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1960/// special functions, such as the default constructor, copy
1961/// constructor, or destructor, to the given C++ class (C++
1962/// [special]p1). This routine can only be executed just before the
1963/// definition of the class is complete.
1964void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001965 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001966 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001967
Sebastian Redl465226e2009-05-27 22:11:52 +00001968 // FIXME: Implicit declarations have exception specifications, which are
1969 // the union of the specifications of the implicitly called functions.
1970
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001971 if (!ClassDecl->hasUserDeclaredConstructor()) {
1972 // C++ [class.ctor]p5:
1973 // A default constructor for a class X is a constructor of class X
1974 // that can be called without an argument. If there is no
1975 // user-declared constructor for class X, a default constructor is
1976 // implicitly declared. An implicitly-declared default constructor
1977 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001978 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001979 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001980 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001981 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001982 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001983 Context.getFunctionType(Context.VoidTy,
1984 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001985 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001986 /*isExplicit=*/false,
1987 /*isInline=*/true,
1988 /*isImplicitlyDeclared=*/true);
1989 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001990 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001991 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001992 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001993 }
1994
1995 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1996 // C++ [class.copy]p4:
1997 // If the class definition does not explicitly declare a copy
1998 // constructor, one is declared implicitly.
1999
2000 // C++ [class.copy]p5:
2001 // The implicitly-declared copy constructor for a class X will
2002 // have the form
2003 //
2004 // X::X(const X&)
2005 //
2006 // if
2007 bool HasConstCopyConstructor = true;
2008
2009 // -- each direct or virtual base class B of X has a copy
2010 // constructor whose first parameter is of type const B& or
2011 // const volatile B&, and
2012 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2013 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2014 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002015 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002016 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002017 = BaseClassDecl->hasConstCopyConstructor(Context);
2018 }
2019
2020 // -- for all the nonstatic data members of X that are of a
2021 // class type M (or array thereof), each such class type
2022 // has a copy constructor whose first parameter is of type
2023 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002024 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2025 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002026 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002027 QualType FieldType = (*Field)->getType();
2028 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2029 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002030 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002031 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002032 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002033 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002034 = FieldClassDecl->hasConstCopyConstructor(Context);
2035 }
2036 }
2037
Sebastian Redl64b45f72009-01-05 20:52:13 +00002038 // Otherwise, the implicitly declared copy constructor will have
2039 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002040 //
2041 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002042 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002043 if (HasConstCopyConstructor)
2044 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002045 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002046
Sebastian Redl64b45f72009-01-05 20:52:13 +00002047 // An implicitly-declared copy constructor is an inline public
2048 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002049 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002050 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002051 CXXConstructorDecl *CopyConstructor
2052 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002053 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002054 Context.getFunctionType(Context.VoidTy,
2055 &ArgType, 1,
2056 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002057 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002058 /*isExplicit=*/false,
2059 /*isInline=*/true,
2060 /*isImplicitlyDeclared=*/true);
2061 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002062 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002063 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002064
2065 // Add the parameter to the constructor.
2066 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2067 ClassDecl->getLocation(),
2068 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002069 ArgType, /*DInfo=*/0,
2070 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002071 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002072 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002073 }
2074
Sebastian Redl64b45f72009-01-05 20:52:13 +00002075 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2076 // Note: The following rules are largely analoguous to the copy
2077 // constructor rules. Note that virtual bases are not taken into account
2078 // for determining the argument type of the operator. Note also that
2079 // operators taking an object instead of a reference are allowed.
2080 //
2081 // C++ [class.copy]p10:
2082 // If the class definition does not explicitly declare a copy
2083 // assignment operator, one is declared implicitly.
2084 // The implicitly-defined copy assignment operator for a class X
2085 // will have the form
2086 //
2087 // X& X::operator=(const X&)
2088 //
2089 // if
2090 bool HasConstCopyAssignment = true;
2091
2092 // -- each direct base class B of X has a copy assignment operator
2093 // whose parameter is of type const B&, const volatile B& or B,
2094 // and
2095 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2096 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002097 assert(!Base->getType()->isDependentType() &&
2098 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002099 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002100 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002101 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002102 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002103 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002104 }
2105
2106 // -- for all the nonstatic data members of X that are of a class
2107 // type M (or array thereof), each such class type has a copy
2108 // assignment operator whose parameter is of type const M&,
2109 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002110 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2111 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002112 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002113 QualType FieldType = (*Field)->getType();
2114 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2115 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002116 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002117 const CXXRecordDecl *FieldClassDecl
2118 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002119 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002120 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002121 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002122 }
2123 }
2124
2125 // Otherwise, the implicitly declared copy assignment operator will
2126 // have the form
2127 //
2128 // X& X::operator=(X&)
2129 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002130 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002131 if (HasConstCopyAssignment)
2132 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002133 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002134
2135 // An implicitly-declared copy assignment operator is an inline public
2136 // member of its class.
2137 DeclarationName Name =
2138 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2139 CXXMethodDecl *CopyAssignment =
2140 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2141 Context.getFunctionType(RetType, &ArgType, 1,
2142 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002143 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002144 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002145 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002146 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002147 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002148
2149 // Add the parameter to the operator.
2150 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2151 ClassDecl->getLocation(),
2152 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002153 ArgType, /*DInfo=*/0,
2154 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002155 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002156
2157 // Don't call addedAssignmentOperator. There is no way to distinguish an
2158 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002159 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002160 }
2161
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002162 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002163 // C++ [class.dtor]p2:
2164 // If a class has no user-declared destructor, a destructor is
2165 // declared implicitly. An implicitly-declared destructor is an
2166 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002167 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002168 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002169 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002170 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002171 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002172 Context.getFunctionType(Context.VoidTy,
2173 0, 0, false, 0),
2174 /*isInline=*/true,
2175 /*isImplicitlyDeclared=*/true);
2176 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002177 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002178 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002179 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002180 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002181}
2182
Douglas Gregor6569d682009-05-27 23:11:45 +00002183void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002184 Decl *D = TemplateD.getAs<Decl>();
2185 if (!D)
2186 return;
2187
2188 TemplateParameterList *Params = 0;
2189 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2190 Params = Template->getTemplateParameters();
2191 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2192 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2193 Params = PartialSpec->getTemplateParameters();
2194 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002195 return;
2196
Douglas Gregor6569d682009-05-27 23:11:45 +00002197 for (TemplateParameterList::iterator Param = Params->begin(),
2198 ParamEnd = Params->end();
2199 Param != ParamEnd; ++Param) {
2200 NamedDecl *Named = cast<NamedDecl>(*Param);
2201 if (Named->getDeclName()) {
2202 S->AddDecl(DeclPtrTy::make(Named));
2203 IdResolver.AddDecl(Named);
2204 }
2205 }
2206}
2207
Douglas Gregor72b505b2008-12-16 21:30:33 +00002208/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2209/// parsing a top-level (non-nested) C++ class, and we are now
2210/// parsing those parts of the given Method declaration that could
2211/// not be parsed earlier (C++ [class.mem]p2), such as default
2212/// arguments. This action should enter the scope of the given
2213/// Method declaration as if we had just parsed the qualified method
2214/// name. However, it should not bring the parameters into scope;
2215/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002216void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002217 if (!MethodD)
2218 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002220 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Douglas Gregor72b505b2008-12-16 21:30:33 +00002222 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002223 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002224 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002225 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2226 SS.setScopeRep(
2227 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002228 ActOnCXXEnterDeclaratorScope(S, SS);
2229}
2230
2231/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2232/// C++ method declaration. We're (re-)introducing the given
2233/// function parameter into scope for use in parsing later parts of
2234/// the method declaration. For example, we could see an
2235/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002236void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002237 if (!ParamD)
2238 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Chris Lattnerb28317a2009-03-28 19:18:32 +00002240 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002241
2242 // If this parameter has an unparsed default argument, clear it out
2243 // to make way for the parsed default argument.
2244 if (Param->hasUnparsedDefaultArg())
2245 Param->setDefaultArg(0);
2246
Chris Lattnerb28317a2009-03-28 19:18:32 +00002247 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002248 if (Param->getDeclName())
2249 IdResolver.AddDecl(Param);
2250}
2251
2252/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2253/// processing the delayed method declaration for Method. The method
2254/// declaration is now considered finished. There may be a separate
2255/// ActOnStartOfFunctionDef action later (not necessarily
2256/// immediately!) for this method, if it was also defined inside the
2257/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002258void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002259 if (!MethodD)
2260 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002262 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Chris Lattnerb28317a2009-03-28 19:18:32 +00002264 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002265 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002266 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002267 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2268 SS.setScopeRep(
2269 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002270 ActOnCXXExitDeclaratorScope(S, SS);
2271
2272 // Now that we have our default arguments, check the constructor
2273 // again. It could produce additional diagnostics or affect whether
2274 // the class has implicitly-declared destructors, among other
2275 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002276 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2277 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002278
2279 // Check the default arguments, which we may have added.
2280 if (!Method->isInvalidDecl())
2281 CheckCXXDefaultArguments(Method);
2282}
2283
Douglas Gregor42a552f2008-11-05 20:51:48 +00002284/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002285/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002286/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002287/// emit diagnostics and set the invalid bit to true. In any case, the type
2288/// will be updated to reflect a well-formed type for the constructor and
2289/// returned.
2290QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2291 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002292 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002293
2294 // C++ [class.ctor]p3:
2295 // A constructor shall not be virtual (10.3) or static (9.4). A
2296 // constructor can be invoked for a const, volatile or const
2297 // volatile object. A constructor shall not be declared const,
2298 // volatile, or const volatile (9.3.2).
2299 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002300 if (!D.isInvalidType())
2301 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2302 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2303 << SourceRange(D.getIdentifierLoc());
2304 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002305 }
2306 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002307 if (!D.isInvalidType())
2308 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2309 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2310 << SourceRange(D.getIdentifierLoc());
2311 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002312 SC = FunctionDecl::None;
2313 }
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Chris Lattner65401802009-04-25 08:28:21 +00002315 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2316 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002317 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002318 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2319 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002320 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002321 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2322 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002323 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002324 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2325 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002326 }
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Douglas Gregor42a552f2008-11-05 20:51:48 +00002328 // Rebuild the function type "R" without any type qualifiers (in
2329 // case any of the errors above fired) and with "void" as the
2330 // return type, since constructors don't have return types. We
2331 // *always* have to do this, because GetTypeForDeclarator will
2332 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002333 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002334 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2335 Proto->getNumArgs(),
2336 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002337}
2338
Douglas Gregor72b505b2008-12-16 21:30:33 +00002339/// CheckConstructor - Checks a fully-formed constructor for
2340/// well-formedness, issuing any diagnostics required. Returns true if
2341/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002342void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002343 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002344 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2345 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002346 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002347
2348 // C++ [class.copy]p3:
2349 // A declaration of a constructor for a class X is ill-formed if
2350 // its first parameter is of type (optionally cv-qualified) X and
2351 // either there are no other parameters or else all other
2352 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002353 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002354 ((Constructor->getNumParams() == 1) ||
2355 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002356 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2357 Constructor->getTemplateSpecializationKind()
2358 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002359 QualType ParamType = Constructor->getParamDecl(0)->getType();
2360 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2361 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002362 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2363 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002364 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002365
2366 // FIXME: Rather that making the constructor invalid, we should endeavor
2367 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002368 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002369 }
2370 }
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Douglas Gregor72b505b2008-12-16 21:30:33 +00002372 // Notify the class that we've added a constructor.
2373 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002374}
2375
Anders Carlsson6d701392009-11-15 22:49:34 +00002376/// CheckDestructor - Checks a fully-formed destructor for
2377/// well-formedness, issuing any diagnostics required.
2378void Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2379 CXXRecordDecl *RD = Destructor->getParent();
2380
2381 if (Destructor->isVirtual()) {
2382 SourceLocation Loc;
2383
2384 if (!Destructor->isImplicit())
2385 Loc = Destructor->getLocation();
2386 else
2387 Loc = RD->getLocation();
2388
2389 // If we have a virtual destructor, look up the deallocation function
2390 FunctionDecl *OperatorDelete = 0;
2391 DeclarationName Name =
2392 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2393 if (!FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2394 Destructor->setOperatorDelete(OperatorDelete);
2395 }
2396}
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();
Douglas Gregor70316a02008-12-26 15:00:45 +00002610 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002611 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002612 Conv = Conversions->function_begin(),
2613 ConvEnd = Conversions->function_end();
2614 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002615 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002616 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002617 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002618 }
2619 }
2620 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002621 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002622 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002623 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002624 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002625 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002626
Chris Lattnerb28317a2009-03-28 19:18:32 +00002627 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002628}
2629
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002630//===----------------------------------------------------------------------===//
2631// Namespace Handling
2632//===----------------------------------------------------------------------===//
2633
2634/// ActOnStartNamespaceDef - This is called at the start of a namespace
2635/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002636Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2637 SourceLocation IdentLoc,
2638 IdentifierInfo *II,
2639 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002640 NamespaceDecl *Namespc =
2641 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2642 Namespc->setLBracLoc(LBrace);
2643
2644 Scope *DeclRegionScope = NamespcScope->getParent();
2645
2646 if (II) {
2647 // C++ [namespace.def]p2:
2648 // The identifier in an original-namespace-definition shall not have been
2649 // previously defined in the declarative region in which the
2650 // original-namespace-definition appears. The identifier in an
2651 // original-namespace-definition is the name of the namespace. Subsequently
2652 // in that declarative region, it is treated as an original-namespace-name.
2653
John McCallf36e02d2009-10-09 21:13:30 +00002654 NamedDecl *PrevDecl
2655 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump1eb44332009-09-09 15:08:12 +00002656
Douglas Gregor44b43212008-12-11 16:49:14 +00002657 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2658 // This is an extended namespace definition.
2659 // Attach this namespace decl to the chain of extended namespace
2660 // definitions.
2661 OrigNS->setNextNamespace(Namespc);
2662 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002663
Mike Stump1eb44332009-09-09 15:08:12 +00002664 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002665 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002666 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002667 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002668 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002669 } else if (PrevDecl) {
2670 // This is an invalid name redefinition.
2671 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2672 << Namespc->getDeclName();
2673 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2674 Namespc->setInvalidDecl();
2675 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002676 } else if (II->isStr("std") &&
2677 CurContext->getLookupContext()->isTranslationUnit()) {
2678 // This is the first "real" definition of the namespace "std", so update
2679 // our cache of the "std" namespace to point at this definition.
2680 if (StdNamespace) {
2681 // We had already defined a dummy namespace "std". Link this new
2682 // namespace definition to the dummy namespace "std".
2683 StdNamespace->setNextNamespace(Namespc);
2684 StdNamespace->setLocation(IdentLoc);
2685 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2686 }
2687
2688 // Make our StdNamespace cache point at the first real definition of the
2689 // "std" namespace.
2690 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002691 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002692
2693 PushOnScopeChains(Namespc, DeclRegionScope);
2694 } else {
John McCall9aeed322009-10-01 00:25:31 +00002695 // Anonymous namespaces.
2696
2697 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2698 // behaves as if it were replaced by
2699 // namespace unique { /* empty body */ }
2700 // using namespace unique;
2701 // namespace unique { namespace-body }
2702 // where all occurrences of 'unique' in a translation unit are
2703 // replaced by the same identifier and this identifier differs
2704 // from all other identifiers in the entire program.
2705
2706 // We just create the namespace with an empty name and then add an
2707 // implicit using declaration, just like the standard suggests.
2708 //
2709 // CodeGen enforces the "universally unique" aspect by giving all
2710 // declarations semantically contained within an anonymous
2711 // namespace internal linkage.
2712
2713 assert(Namespc->isAnonymousNamespace());
2714 CurContext->addDecl(Namespc);
2715
2716 UsingDirectiveDecl* UD
2717 = UsingDirectiveDecl::Create(Context, CurContext,
2718 /* 'using' */ LBrace,
2719 /* 'namespace' */ SourceLocation(),
2720 /* qualifier */ SourceRange(),
2721 /* NNS */ NULL,
2722 /* identifier */ SourceLocation(),
2723 Namespc,
2724 /* Ancestor */ CurContext);
2725 UD->setImplicit();
2726 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002727 }
2728
2729 // Although we could have an invalid decl (i.e. the namespace name is a
2730 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002731 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2732 // for the namespace has the declarations that showed up in that particular
2733 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002734 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002735 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002736}
2737
2738/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2739/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002740void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2741 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002742 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2743 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2744 Namespc->setRBracLoc(RBrace);
2745 PopDeclContext();
2746}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002747
Chris Lattnerb28317a2009-03-28 19:18:32 +00002748Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2749 SourceLocation UsingLoc,
2750 SourceLocation NamespcLoc,
2751 const CXXScopeSpec &SS,
2752 SourceLocation IdentLoc,
2753 IdentifierInfo *NamespcName,
2754 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002755 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2756 assert(NamespcName && "Invalid NamespcName.");
2757 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002758 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002759
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002760 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002761
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002762 // Lookup namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002763 LookupResult R;
2764 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002765 if (R.isAmbiguous()) {
2766 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002767 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002768 }
John McCallf36e02d2009-10-09 21:13:30 +00002769 if (!R.empty()) {
2770 NamedDecl *NS = R.getFoundDecl();
Douglas Gregor19aeac62009-11-14 03:27:21 +00002771 // FIXME: Namespace aliases!
Douglas Gregorf780abc2008-12-30 03:27:21 +00002772 assert(isa<NamespaceDecl>(NS) && "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.
2785 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2786 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2787 CommonAncestor = CommonAncestor->getParent();
2788
Mike Stump1eb44332009-09-09 15:08:12 +00002789 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002790 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002791 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002792 SS.getRange(),
2793 (NestedNameSpecifier *)SS.getScopeRep(),
2794 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002795 cast<NamespaceDecl>(NS),
2796 CommonAncestor);
2797 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002798 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002799 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002800 }
2801
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002802 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002803 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002804 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002805}
2806
2807void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2808 // If scope has associated entity, then using directive is at namespace
2809 // or translation unit scope. We add UsingDirectiveDecls, into
2810 // it's lookup structure.
2811 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002812 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002813 else
2814 // Otherwise it is block-sope. using-directives will affect lookup
2815 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002816 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002817}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002818
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002819
2820Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002821 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002822 SourceLocation UsingLoc,
2823 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002824 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002825 AttributeList *AttrList,
2826 bool IsTypeName) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002827 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Douglas Gregor12c118a2009-11-04 16:30:06 +00002829 switch (Name.getKind()) {
2830 case UnqualifiedId::IK_Identifier:
2831 case UnqualifiedId::IK_OperatorFunctionId:
2832 case UnqualifiedId::IK_ConversionFunctionId:
2833 break;
2834
2835 case UnqualifiedId::IK_ConstructorName:
2836 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2837 << SS.getRange();
2838 return DeclPtrTy();
2839
2840 case UnqualifiedId::IK_DestructorName:
2841 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2842 << SS.getRange();
2843 return DeclPtrTy();
2844
2845 case UnqualifiedId::IK_TemplateId:
2846 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2847 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2848 return DeclPtrTy();
2849 }
2850
2851 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2852 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2853 Name.getSourceRange().getBegin(),
2854 TargetName, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002855 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002856 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002857 UD->setAccess(AS);
2858 }
Mike Stump1eb44332009-09-09 15:08:12 +00002859
Anders Carlssonc72160b2009-08-28 05:40:36 +00002860 return DeclPtrTy::make(UD);
2861}
2862
2863NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2864 const CXXScopeSpec &SS,
2865 SourceLocation IdentLoc,
2866 DeclarationName Name,
2867 AttributeList *AttrList,
2868 bool IsTypeName) {
2869 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2870 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002871
Anders Carlsson550b14b2009-08-28 05:49:21 +00002872 // FIXME: We ignore attributes for now.
2873 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002875 if (SS.isEmpty()) {
2876 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002877 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002878 }
Mike Stump1eb44332009-09-09 15:08:12 +00002879
2880 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002881 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2882
John McCallaf8e6ed2009-11-12 03:15:40 +00002883 DeclContext *LookupContext = computeDeclContext(SS);
2884 if (!LookupContext) {
Anders Carlsson550b14b2009-08-28 05:49:21 +00002885 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2886 SS.getRange(), NNS,
2887 IdentLoc, Name, IsTypeName);
2888 }
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002890 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2891 // C++0x N2914 [namespace.udecl]p3:
2892 // A using-declaration used as a member-declaration shall refer to a member
2893 // of a base class of the class being defined, shall refer to a member of an
2894 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002895 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002896 // a member of a base class of the class being defined.
John McCallaf8e6ed2009-11-12 03:15:40 +00002897
2898 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2899 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002900 Diag(SS.getRange().getBegin(),
2901 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2902 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002903 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002904 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002905 } else {
2906 // C++0x N2914 [namespace.udecl]p8:
2907 // A using-declaration for a class member shall be a member-declaration.
John McCallaf8e6ed2009-11-12 03:15:40 +00002908 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002909 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002910 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002911 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002912 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002913 }
2914
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002915 // Lookup target name.
John McCallf36e02d2009-10-09 21:13:30 +00002916 LookupResult R;
2917 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002918
John McCallf36e02d2009-10-09 21:13:30 +00002919 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002920 Diag(IdentLoc, diag::err_no_member)
2921 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002922 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002923 }
2924
John McCallf36e02d2009-10-09 21:13:30 +00002925 // FIXME: handle ambiguity?
2926 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002928 if (IsTypeName && !isa<TypeDecl>(ND)) {
2929 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002930 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002931 }
2932
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002933 // C++0x N2914 [namespace.udecl]p6:
2934 // A using-declaration shall not name a namespace.
2935 if (isa<NamespaceDecl>(ND)) {
2936 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2937 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002938 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002939 }
Mike Stump1eb44332009-09-09 15:08:12 +00002940
Anders Carlssonc72160b2009-08-28 05:40:36 +00002941 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2942 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002943}
2944
Anders Carlsson81c85c42009-03-28 23:53:49 +00002945/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2946/// is a namespace alias, returns the namespace it points to.
2947static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2948 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2949 return AD->getNamespace();
2950 return dyn_cast_or_null<NamespaceDecl>(D);
2951}
2952
Mike Stump1eb44332009-09-09 15:08:12 +00002953Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002954 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002955 SourceLocation AliasLoc,
2956 IdentifierInfo *Alias,
2957 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002958 SourceLocation IdentLoc,
2959 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002960
Anders Carlsson81c85c42009-03-28 23:53:49 +00002961 // Lookup the namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002962 LookupResult R;
2963 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlsson81c85c42009-03-28 23:53:49 +00002964
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002965 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00002966 if (NamedDecl *PrevDecl
2967 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002968 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002969 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002970 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00002971 if (!R.isAmbiguous() && !R.empty() &&
2972 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00002973 return DeclPtrTy();
2974 }
Mike Stump1eb44332009-09-09 15:08:12 +00002975
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002976 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2977 diag::err_redefinition_different_kind;
2978 Diag(AliasLoc, DiagID) << Alias;
2979 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002980 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002981 }
2982
Anders Carlsson5721c682009-03-28 06:42:02 +00002983 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002984 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002985 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002986 }
Mike Stump1eb44332009-09-09 15:08:12 +00002987
John McCallf36e02d2009-10-09 21:13:30 +00002988 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00002989 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002990 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002991 }
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002993 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002994 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2995 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002996 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00002997 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002999 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003000 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003001}
3002
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003003void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3004 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003005 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3006 !Constructor->isUsed()) &&
3007 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Eli Friedman80c30da2009-11-09 19:20:36 +00003009 CXXRecordDecl *ClassDecl
3010 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3011 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003012
Eli Friedman80c30da2009-11-09 19:20:36 +00003013 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
3014 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
3015 << Context.getTagDeclType(ClassDecl);
3016 Constructor->setInvalidDecl();
3017 } else {
3018 Constructor->setUsed();
3019 }
Eli Friedman49c16da2009-11-09 01:05:47 +00003020 return;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003021}
3022
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003023void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003024 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003025 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3026 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003027 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003028 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3029 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003030 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003031 // implicitly defined, all the implicitly-declared default destructors
3032 // for its base class and its non-static data members shall have been
3033 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003034 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3035 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003036 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003037 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003038 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003039 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003040 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3041 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3042 else
Mike Stump1eb44332009-09-09 15:08:12 +00003043 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003044 "DefineImplicitDestructor - missing dtor in a base class");
3045 }
3046 }
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003048 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3049 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003050 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3051 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3052 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003053 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003054 CXXRecordDecl *FieldClassDecl
3055 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3056 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003057 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003058 const_cast<CXXDestructorDecl*>(
3059 FieldClassDecl->getDestructor(Context)))
3060 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3061 else
Mike Stump1eb44332009-09-09 15:08:12 +00003062 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003063 "DefineImplicitDestructor - missing dtor in class of a data member");
3064 }
3065 }
3066 }
3067 Destructor->setUsed();
3068}
3069
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003070void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3071 CXXMethodDecl *MethodDecl) {
3072 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3073 MethodDecl->getOverloadedOperator() == OO_Equal &&
3074 !MethodDecl->isUsed()) &&
3075 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003077 CXXRecordDecl *ClassDecl
3078 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003080 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003081 // Before the implicitly-declared copy assignment operator for a class is
3082 // implicitly defined, all implicitly-declared copy assignment operators
3083 // for its direct base classes and its nonstatic data members shall have
3084 // been implicitly defined.
3085 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3087 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003088 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003089 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003090 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003091 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3092 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3093 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003094 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3095 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003096 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3097 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3098 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003099 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003100 CXXRecordDecl *FieldClassDecl
3101 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003102 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003103 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3104 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003105 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003106 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003107 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3108 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003109 Diag(CurrentLocation, diag::note_first_required_here);
3110 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003111 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003112 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003113 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3114 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003115 Diag(CurrentLocation, diag::note_first_required_here);
3116 err = true;
3117 }
3118 }
3119 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003120 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003121}
3122
3123CXXMethodDecl *
3124Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3125 CXXRecordDecl *ClassDecl) {
3126 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3127 QualType RHSType(LHSType);
3128 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003129 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003130 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003131 RHSType = Context.getCVRQualifiedType(RHSType,
3132 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003133 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3134 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003135 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003136 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3137 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003138 SourceLocation()));
3139 Expr *Args[2] = { &*LHS, &*RHS };
3140 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003141 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003142 CandidateSet);
3143 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003144 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003145 ClassDecl->getLocation(), Best) == OR_Success)
3146 return cast<CXXMethodDecl>(Best->Function);
3147 assert(false &&
3148 "getAssignOperatorMethod - copy assignment operator method not found");
3149 return 0;
3150}
3151
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003152void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3153 CXXConstructorDecl *CopyConstructor,
3154 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003155 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003156 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3157 !CopyConstructor->isUsed()) &&
3158 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003160 CXXRecordDecl *ClassDecl
3161 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3162 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003163 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003164 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003165 // implicitly defined, all the implicitly-declared copy constructors
3166 // for its base class and its non-static data members shall have been
3167 // implicitly defined.
3168 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3169 Base != ClassDecl->bases_end(); ++Base) {
3170 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003171 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003172 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003173 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003174 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003175 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003176 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3177 FieldEnd = ClassDecl->field_end();
3178 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003179 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3180 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3181 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003182 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003183 CXXRecordDecl *FieldClassDecl
3184 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003185 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003186 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003187 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003188 }
3189 }
3190 CopyConstructor->setUsed();
3191}
3192
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003193Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003194Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003195 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003196 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003197 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Douglas Gregor39da0b82009-09-09 23:08:42 +00003199 // C++ [class.copy]p15:
3200 // Whenever a temporary class object is copied using a copy constructor, and
3201 // this object and the copy have the same cv-unqualified type, an
3202 // implementation is permitted to treat the original and the copy as two
3203 // different ways of referring to the same object and not perform a copy at
3204 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003206 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003207 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003208 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003209 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3210 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003211 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3212 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3213 E = ICE->getSubExpr();
3214
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003215 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3216 Elidable = true;
3217 }
Mike Stump1eb44332009-09-09 15:08:12 +00003218
3219 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003220 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003221}
3222
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003223/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3224/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003225Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003226Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3227 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003228 MultiExprArg ExprArgs) {
3229 unsigned NumExprs = ExprArgs.size();
3230 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Douglas Gregor39da0b82009-09-09 23:08:42 +00003232 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3233 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003234}
3235
Anders Carlssone7624a72009-08-27 05:08:22 +00003236Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003237Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3238 QualType Ty,
3239 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003240 MultiExprArg Args,
3241 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003242 unsigned NumExprs = Args.size();
3243 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003244
Douglas Gregor39da0b82009-09-09 23:08:42 +00003245 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3246 TyBeginLoc, Exprs,
3247 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003248}
3249
3250
Mike Stump1eb44332009-09-09 15:08:12 +00003251bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003252 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003253 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003254 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003255 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003256 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003257 if (TempResult.isInvalid())
3258 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003259
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003260 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003261 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003262 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003263 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Anders Carlssonfe2de492009-08-25 05:18:00 +00003265 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003266}
3267
Mike Stump1eb44332009-09-09 15:08:12 +00003268void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003269 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003270 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003271 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003272 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003273 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003274 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003275}
3276
Mike Stump1eb44332009-09-09 15:08:12 +00003277/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003278/// ActOnDeclarator, when a C++ direct initializer is present.
3279/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003280void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3281 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003282 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003283 SourceLocation *CommaLocs,
3284 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003285 unsigned NumExprs = Exprs.size();
3286 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003287 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003288
3289 // If there is no declaration, there was an error parsing it. Just ignore
3290 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003291 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003294 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3295 if (!VDecl) {
3296 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3297 RealDecl->setInvalidDecl();
3298 return;
3299 }
3300
Douglas Gregor83ddad32009-08-26 21:14:46 +00003301 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003302 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003303 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3304 //
3305 // Clients that want to distinguish between the two forms, can check for
3306 // direct initializer using VarDecl::hasCXXDirectInitializer().
3307 // A major benefit is that clients that don't particularly care about which
3308 // exactly form was it (like the CodeGen) can handle both cases without
3309 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003310
Douglas Gregor83ddad32009-08-26 21:14:46 +00003311 // If either the declaration has a dependent type or if any of the expressions
3312 // is type-dependent, we represent the initialization via a ParenListExpr for
3313 // later use during template instantiation.
3314 if (VDecl->getType()->isDependentType() ||
3315 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3316 // Let clients know that initialization was done with a direct initializer.
3317 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003318
Douglas Gregor83ddad32009-08-26 21:14:46 +00003319 // Store the initialization expressions as a ParenListExpr.
3320 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003321 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003322 new (Context) ParenListExpr(Context, LParenLoc,
3323 (Expr **)Exprs.release(),
3324 NumExprs, RParenLoc));
3325 return;
3326 }
Mike Stump1eb44332009-09-09 15:08:12 +00003327
Douglas Gregor83ddad32009-08-26 21:14:46 +00003328
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003329 // C++ 8.5p11:
3330 // The form of initialization (using parentheses or '=') is generally
3331 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003332 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003333 QualType DeclInitType = VDecl->getType();
3334 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003335 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003336
Douglas Gregor615c5d42009-03-24 16:43:20 +00003337 // FIXME: This isn't the right place to complete the type.
3338 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3339 diag::err_typecheck_decl_incomplete_type)) {
3340 VDecl->setInvalidDecl();
3341 return;
3342 }
3343
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003344 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003345 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3346
Douglas Gregor18fe5682008-11-03 20:45:27 +00003347 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003348 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003349 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003350 VDecl->getLocation(),
3351 SourceRange(VDecl->getLocation(),
3352 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003353 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003354 IK_Direct,
3355 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003356 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003357 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003358 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003359 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003360 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003361 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003362 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003363 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003364 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003365 return;
3366 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003367
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003368 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003369 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3370 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003371 RealDecl->setInvalidDecl();
3372 return;
3373 }
3374
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003375 // Let clients know that initialization was done with a direct initializer.
3376 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003377
3378 assert(NumExprs == 1 && "Expected 1 expression");
3379 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003380 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3381 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003382}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003383
Douglas Gregor19aeac62009-11-14 03:27:21 +00003384/// \brief Add the applicable constructor candidates for an initialization
3385/// by constructor.
3386static void AddConstructorInitializationCandidates(Sema &SemaRef,
3387 QualType ClassType,
3388 Expr **Args,
3389 unsigned NumArgs,
3390 Sema::InitializationKind Kind,
3391 OverloadCandidateSet &CandidateSet) {
3392 // C++ [dcl.init]p14:
3393 // If the initialization is direct-initialization, or if it is
3394 // copy-initialization where the cv-unqualified version of the
3395 // source type is the same class as, or a derived class of, the
3396 // class of the destination, constructors are considered. The
3397 // applicable constructors are enumerated (13.3.1.3), and the
3398 // best one is chosen through overload resolution (13.3). The
3399 // constructor so selected is called to initialize the object,
3400 // with the initializer expression(s) as its argument(s). If no
3401 // constructor applies, or the overload resolution is ambiguous,
3402 // the initialization is ill-formed.
3403 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3404 assert(ClassRec && "Can only initialize a class type here");
3405
3406 // FIXME: When we decide not to synthesize the implicitly-declared
3407 // constructors, we'll need to make them appear here.
3408
3409 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3410 DeclarationName ConstructorName
3411 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3412 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3413 DeclContext::lookup_const_iterator Con, ConEnd;
3414 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3415 Con != ConEnd; ++Con) {
3416 // Find the constructor (which may be a template).
3417 CXXConstructorDecl *Constructor = 0;
3418 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3419 if (ConstructorTmpl)
3420 Constructor
3421 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3422 else
3423 Constructor = cast<CXXConstructorDecl>(*Con);
3424
3425 if ((Kind == Sema::IK_Direct) ||
3426 (Kind == Sema::IK_Copy &&
3427 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3428 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3429 if (ConstructorTmpl)
3430 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
3431 Args, NumArgs, CandidateSet);
3432 else
3433 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3434 }
3435 }
3436}
3437
3438/// \brief Attempt to perform initialization by constructor
3439/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3440/// copy-initialization.
3441///
3442/// This routine determines whether initialization by constructor is possible,
3443/// but it does not emit any diagnostics in the case where the initialization
3444/// is ill-formed.
3445///
3446/// \param ClassType the type of the object being initialized, which must have
3447/// class type.
3448///
3449/// \param Args the arguments provided to initialize the object
3450///
3451/// \param NumArgs the number of arguments provided to initialize the object
3452///
3453/// \param Kind the type of initialization being performed
3454///
3455/// \returns the constructor used to initialize the object, if successful.
3456/// Otherwise, emits a diagnostic and returns NULL.
3457CXXConstructorDecl *
3458Sema::TryInitializationByConstructor(QualType ClassType,
3459 Expr **Args, unsigned NumArgs,
3460 SourceLocation Loc,
3461 InitializationKind Kind) {
3462 // Build the overload candidate set
3463 OverloadCandidateSet CandidateSet;
3464 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3465 CandidateSet);
3466
3467 // Determine whether we found a constructor we can use.
3468 OverloadCandidateSet::iterator Best;
3469 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3470 case OR_Success:
3471 case OR_Deleted:
3472 // We found a constructor. Return it.
3473 return cast<CXXConstructorDecl>(Best->Function);
3474
3475 case OR_No_Viable_Function:
3476 case OR_Ambiguous:
3477 // Overload resolution failed. Return nothing.
3478 return 0;
3479 }
3480
3481 // Silence GCC warning
3482 return 0;
3483}
3484
Douglas Gregor39da0b82009-09-09 23:08:42 +00003485/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3486/// may occur as part of direct-initialization or copy-initialization.
3487///
3488/// \param ClassType the type of the object being initialized, which must have
3489/// class type.
3490///
3491/// \param ArgsPtr the arguments provided to initialize the object
3492///
3493/// \param Loc the source location where the initialization occurs
3494///
3495/// \param Range the source range that covers the entire initialization
3496///
3497/// \param InitEntity the name of the entity being initialized, if known
3498///
3499/// \param Kind the type of initialization being performed
3500///
3501/// \param ConvertedArgs a vector that will be filled in with the
3502/// appropriately-converted arguments to the constructor (if initialization
3503/// succeeded).
3504///
3505/// \returns the constructor used to initialize the object, if successful.
3506/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003507CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003508Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003509 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003510 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003511 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003512 InitializationKind Kind,
3513 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00003514
3515 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00003516 Expr **Args = (Expr **)ArgsPtr.get();
3517 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003518 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00003519 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3520 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003521
Douglas Gregor18fe5682008-11-03 20:45:27 +00003522 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003523 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003524 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003525 // We found a constructor. Break out so that we can convert the arguments
3526 // appropriately.
3527 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003528
Douglas Gregor18fe5682008-11-03 20:45:27 +00003529 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003530 if (InitEntity)
3531 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003532 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003533 else
3534 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003535 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003536 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003537 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Douglas Gregor18fe5682008-11-03 20:45:27 +00003539 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003540 if (InitEntity)
3541 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3542 else
3543 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003544 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3545 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003546
3547 case OR_Deleted:
3548 if (InitEntity)
3549 Diag(Loc, diag::err_ovl_deleted_init)
3550 << Best->Function->isDeleted()
3551 << InitEntity << Range;
3552 else
3553 Diag(Loc, diag::err_ovl_deleted_init)
3554 << Best->Function->isDeleted()
3555 << InitEntity << Range;
3556 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3557 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003558 }
Mike Stump1eb44332009-09-09 15:08:12 +00003559
Douglas Gregor39da0b82009-09-09 23:08:42 +00003560 // Convert the arguments, fill in default arguments, etc.
3561 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3562 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3563 return 0;
3564
3565 return Constructor;
3566}
3567
3568/// \brief Given a constructor and the set of arguments provided for the
3569/// constructor, convert the arguments and add any required default arguments
3570/// to form a proper call to this constructor.
3571///
3572/// \returns true if an error occurred, false otherwise.
3573bool
3574Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3575 MultiExprArg ArgsPtr,
3576 SourceLocation Loc,
3577 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3578 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3579 unsigned NumArgs = ArgsPtr.size();
3580 Expr **Args = (Expr **)ArgsPtr.get();
3581
3582 const FunctionProtoType *Proto
3583 = Constructor->getType()->getAs<FunctionProtoType>();
3584 assert(Proto && "Constructor without a prototype?");
3585 unsigned NumArgsInProto = Proto->getNumArgs();
3586 unsigned NumArgsToCheck = NumArgs;
3587
3588 // If too few arguments are available, we'll fill in the rest with defaults.
3589 if (NumArgs < NumArgsInProto) {
3590 NumArgsToCheck = NumArgsInProto;
3591 ConvertedArgs.reserve(NumArgsInProto);
3592 } else {
3593 ConvertedArgs.reserve(NumArgs);
3594 if (NumArgs > NumArgsInProto)
3595 NumArgsToCheck = NumArgsInProto;
3596 }
3597
3598 // Convert arguments
3599 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3600 QualType ProtoArgType = Proto->getArgType(i);
3601
3602 Expr *Arg;
3603 if (i < NumArgs) {
3604 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003605
3606 // Pass the argument.
3607 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3608 return true;
3609
3610 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003611 } else {
3612 ParmVarDecl *Param = Constructor->getParamDecl(i);
3613
3614 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3615 if (DefArg.isInvalid())
3616 return true;
3617
3618 Arg = DefArg.takeAs<Expr>();
3619 }
3620
3621 ConvertedArgs.push_back(Arg);
3622 }
3623
3624 // If this is a variadic call, handle args passed through "...".
3625 if (Proto->isVariadic()) {
3626 // Promote the arguments (C99 6.5.2.2p7).
3627 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3628 Expr *Arg = Args[i];
3629 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3630 return true;
3631
3632 ConvertedArgs.push_back(Arg);
3633 Args[i] = 0;
3634 }
3635 }
3636
3637 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003638}
3639
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003640/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3641/// determine whether they are reference-related,
3642/// reference-compatible, reference-compatible with added
3643/// qualification, or incompatible, for use in C++ initialization by
3644/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3645/// type, and the first type (T1) is the pointee type of the reference
3646/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003647Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00003648Sema::CompareReferenceRelationship(SourceLocation Loc,
3649 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003650 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003651 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003652 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00003653 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003654
Douglas Gregor393896f2009-11-05 13:06:35 +00003655 QualType T1 = Context.getCanonicalType(OrigT1);
3656 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003657 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3658 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003659
3660 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003661 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003662 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003663 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003664 if (UnqualT1 == UnqualT2)
3665 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00003666 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3667 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3668 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00003669 DerivedToBase = true;
3670 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003671 return Ref_Incompatible;
3672
3673 // At this point, we know that T1 and T2 are reference-related (at
3674 // least).
3675
3676 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003677 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003678 // reference-related to T2 and cv1 is the same cv-qualification
3679 // as, or greater cv-qualification than, cv2. For purposes of
3680 // overload resolution, cases for which cv1 is greater
3681 // cv-qualification than cv2 are identified as
3682 // reference-compatible with added qualification (see 13.3.3.2).
3683 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3684 return Ref_Compatible;
3685 else if (T1.isMoreQualifiedThan(T2))
3686 return Ref_Compatible_With_Added_Qualification;
3687 else
3688 return Ref_Related;
3689}
3690
3691/// CheckReferenceInit - Check the initialization of a reference
3692/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3693/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003694/// list), and DeclType is the type of the declaration. When ICS is
3695/// non-null, this routine will compute the implicit conversion
3696/// sequence according to C++ [over.ics.ref] and will not produce any
3697/// diagnostics; when ICS is null, it will emit diagnostics when any
3698/// errors are found. Either way, a return value of true indicates
3699/// that there was a failure, a return value of false indicates that
3700/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003701///
3702/// When @p SuppressUserConversions, user-defined conversions are
3703/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003704/// When @p AllowExplicit, we also permit explicit user-defined
3705/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003706/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003707/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3708/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003709bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003710Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003711 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003712 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003713 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003714 ImplicitConversionSequence *ICS,
3715 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003716 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3717
Ted Kremenek6217b802009-07-29 21:53:49 +00003718 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003719 QualType T2 = Init->getType();
3720
Douglas Gregor904eed32008-11-10 20:40:00 +00003721 // If the initializer is the address of an overloaded function, try
3722 // to resolve the overloaded function. If all goes well, T2 is the
3723 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003724 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003725 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003726 ICS != 0);
3727 if (Fn) {
3728 // Since we're performing this reference-initialization for
3729 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003730 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003731 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003732 return true;
3733
Anders Carlsson96ad5332009-10-21 17:16:23 +00003734 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003735 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003736
3737 T2 = Fn->getType();
3738 }
3739 }
3740
Douglas Gregor15da57e2008-10-29 02:00:59 +00003741 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003742 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003743 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003744 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3745 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003746 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00003747 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003748
3749 // Most paths end in a failed conversion.
3750 if (ICS)
3751 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003752
3753 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003754 // A reference to type "cv1 T1" is initialized by an expression
3755 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003756
3757 // -- If the initializer expression
3758
Sebastian Redla9845802009-03-29 15:27:50 +00003759 // Rvalue references cannot bind to lvalues (N2812).
3760 // There is absolutely no situation where they can. In particular, note that
3761 // this is ill-formed, even if B has a user-defined conversion to A&&:
3762 // B b;
3763 // A&& r = b;
3764 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3765 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003766 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003767 << Init->getSourceRange();
3768 return true;
3769 }
3770
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003771 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003772 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3773 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003774 //
3775 // Note that the bit-field check is skipped if we are just computing
3776 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003777 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003778 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003779 BindsDirectly = true;
3780
Douglas Gregor15da57e2008-10-29 02:00:59 +00003781 if (ICS) {
3782 // C++ [over.ics.ref]p1:
3783 // When a parameter of reference type binds directly (8.5.3)
3784 // to an argument expression, the implicit conversion sequence
3785 // is the identity conversion, unless the argument expression
3786 // has a type that is a derived class of the parameter type,
3787 // in which case the implicit conversion sequence is a
3788 // derived-to-base Conversion (13.3.3.1).
3789 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3790 ICS->Standard.First = ICK_Identity;
3791 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3792 ICS->Standard.Third = ICK_Identity;
3793 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3794 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003795 ICS->Standard.ReferenceBinding = true;
3796 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003797 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003798 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003799
3800 // Nothing more to do: the inaccessibility/ambiguity check for
3801 // derived-to-base conversions is suppressed when we're
3802 // computing the implicit conversion sequence (C++
3803 // [over.best.ics]p2).
3804 return false;
3805 } else {
3806 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003807 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3808 if (DerivedToBase)
3809 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003810 else if(CheckExceptionSpecCompatibility(Init, T1))
3811 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003812 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003813 }
3814 }
3815
3816 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003817 // implicitly converted to an lvalue of type "cv3 T3,"
3818 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003819 // 92) (this conversion is selected by enumerating the
3820 // applicable conversion functions (13.3.1.6) and choosing
3821 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003822 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003823 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003824 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003825 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003826
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003827 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003828 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003829 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003830 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003831 = Conversions->function_begin();
3832 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003833 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003834 = dyn_cast<FunctionTemplateDecl>(*Func);
3835 CXXConversionDecl *Conv;
3836 if (ConvTemplate)
3837 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3838 else
3839 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003840
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003841 // If the conversion function doesn't return a reference type,
3842 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003843 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003844 (AllowExplicit || !Conv->isExplicit())) {
3845 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003846 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003847 CandidateSet);
3848 else
3849 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3850 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003851 }
3852
3853 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003854 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003855 case OR_Success:
3856 // This is a direct binding.
3857 BindsDirectly = true;
3858
3859 if (ICS) {
3860 // C++ [over.ics.ref]p1:
3861 //
3862 // [...] If the parameter binds directly to the result of
3863 // applying a conversion function to the argument
3864 // expression, the implicit conversion sequence is a
3865 // user-defined conversion sequence (13.3.3.1.2), with the
3866 // second standard conversion sequence either an identity
3867 // conversion or, if the conversion function returns an
3868 // entity of a type that is a derived class of the parameter
3869 // type, a derived-to-base Conversion.
3870 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3871 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3872 ICS->UserDefined.After = Best->FinalConversion;
3873 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003874 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003875 assert(ICS->UserDefined.After.ReferenceBinding &&
3876 ICS->UserDefined.After.DirectBinding &&
3877 "Expected a direct reference binding!");
3878 return false;
3879 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003880 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003881 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003882 CastExpr::CK_UserDefinedConversion,
3883 cast<CXXMethodDecl>(Best->Function),
3884 Owned(Init));
3885 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003886
3887 if (CheckExceptionSpecCompatibility(Init, T1))
3888 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003889 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3890 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003891 }
3892 break;
3893
3894 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003895 if (ICS) {
3896 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3897 Cand != CandidateSet.end(); ++Cand)
3898 if (Cand->Viable)
3899 ICS->ConversionFunctionSet.push_back(Cand->Function);
3900 break;
3901 }
3902 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3903 << Init->getSourceRange();
3904 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003905 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003907 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003908 case OR_Deleted:
3909 // There was no suitable conversion, or we found a deleted
3910 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003911 break;
3912 }
3913 }
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003915 if (BindsDirectly) {
3916 // C++ [dcl.init.ref]p4:
3917 // [...] In all cases where the reference-related or
3918 // reference-compatible relationship of two types is used to
3919 // establish the validity of a reference binding, and T1 is a
3920 // base class of T2, a program that necessitates such a binding
3921 // is ill-formed if T1 is an inaccessible (clause 11) or
3922 // ambiguous (10.2) base class of T2.
3923 //
3924 // Note that we only check this condition when we're allowed to
3925 // complain about errors, because we should not be checking for
3926 // ambiguity (or inaccessibility) unless the reference binding
3927 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003928 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003929 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003930 Init->getSourceRange(),
3931 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003932 else
3933 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003934 }
3935
3936 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003937 // type (i.e., cv1 shall be const), or the reference shall be an
3938 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003939 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003940 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003941 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003942 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3943 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003944 return true;
3945 }
3946
3947 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003948 // class type, and "cv1 T1" is reference-compatible with
3949 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003950 // following ways (the choice is implementation-defined):
3951 //
3952 // -- The reference is bound to the object represented by
3953 // the rvalue (see 3.10) or to a sub-object within that
3954 // object.
3955 //
Eli Friedman33a31382009-08-05 19:21:58 +00003956 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003957 // a constructor is called to copy the entire rvalue
3958 // object into the temporary. The reference is bound to
3959 // the temporary or to a sub-object within the
3960 // temporary.
3961 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003962 // The constructor that would be used to make the copy
3963 // shall be callable whether or not the copy is actually
3964 // done.
3965 //
Sebastian Redla9845802009-03-29 15:27:50 +00003966 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003967 // freedom, so we will always take the first option and never build
3968 // a temporary in this case. FIXME: We will, however, have to check
3969 // for the presence of a copy constructor in C++98/03 mode.
3970 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003971 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3972 if (ICS) {
3973 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3974 ICS->Standard.First = ICK_Identity;
3975 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3976 ICS->Standard.Third = ICK_Identity;
3977 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3978 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003979 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003980 ICS->Standard.DirectBinding = false;
3981 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003982 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003983 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003984 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3985 if (DerivedToBase)
3986 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003987 else if(CheckExceptionSpecCompatibility(Init, T1))
3988 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003989 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003990 }
3991 return false;
3992 }
3993
Eli Friedman33a31382009-08-05 19:21:58 +00003994 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003995 // initialized from the initializer expression using the
3996 // rules for a non-reference copy initialization (8.5). The
3997 // reference is then bound to the temporary. If T1 is
3998 // reference-related to T2, cv1 must be the same
3999 // cv-qualification as, or greater cv-qualification than,
4000 // cv2; otherwise, the program is ill-formed.
4001 if (RefRelationship == Ref_Related) {
4002 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4003 // we would be reference-compatible or reference-compatible with
4004 // added qualification. But that wasn't the case, so the reference
4005 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004006 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004007 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00004008 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4009 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004010 return true;
4011 }
4012
Douglas Gregor734d9862009-01-30 23:27:23 +00004013 // If at least one of the types is a class type, the types are not
4014 // related, and we aren't allowed any user conversions, the
4015 // reference binding fails. This case is important for breaking
4016 // recursion, since TryImplicitConversion below will attempt to
4017 // create a temporary through the use of a copy constructor.
4018 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4019 (T1->isRecordType() || T2->isRecordType())) {
4020 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004021 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00004022 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4023 return true;
4024 }
4025
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004026 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004027 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004028 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004029 //
Sebastian Redla9845802009-03-29 15:27:50 +00004030 // When a parameter of reference type is not bound directly to
4031 // an argument expression, the conversion sequence is the one
4032 // required to convert the argument expression to the
4033 // underlying type of the reference according to
4034 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4035 // to copy-initializing a temporary of the underlying type with
4036 // the argument expression. Any difference in top-level
4037 // cv-qualification is subsumed by the initialization itself
4038 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004039 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4040 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004041 /*ForceRValue=*/false,
4042 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Sebastian Redla9845802009-03-29 15:27:50 +00004044 // Of course, that's still a reference binding.
4045 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4046 ICS->Standard.ReferenceBinding = true;
4047 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004048 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004049 ImplicitConversionSequence::UserDefinedConversion) {
4050 ICS->UserDefined.After.ReferenceBinding = true;
4051 ICS->UserDefined.After.RRefBinding = isRValRef;
4052 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004053 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4054 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004055 ImplicitConversionSequence Conversions;
4056 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4057 false, false,
4058 Conversions);
4059 if (badConversion) {
4060 if ((Conversions.ConversionKind ==
4061 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004062 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004063 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004064 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4065 for (int j = Conversions.ConversionFunctionSet.size()-1;
4066 j >= 0; j--) {
4067 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4068 Diag(Func->getLocation(), diag::err_ovl_candidate);
4069 }
4070 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004071 else {
4072 if (isRValRef)
4073 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4074 << Init->getSourceRange();
4075 else
4076 Diag(DeclLoc, diag::err_invalid_initialization)
4077 << DeclType << Init->getType() << Init->getSourceRange();
4078 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004079 }
4080 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004081 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004082}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004083
4084/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4085/// of this overloaded operator is well-formed. If so, returns false;
4086/// otherwise, emits appropriate diagnostics and returns true.
4087bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004088 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004089 "Expected an overloaded operator declaration");
4090
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004091 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4092
Mike Stump1eb44332009-09-09 15:08:12 +00004093 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004094 // The allocation and deallocation functions, operator new,
4095 // operator new[], operator delete and operator delete[], are
4096 // described completely in 3.7.3. The attributes and restrictions
4097 // found in the rest of this subclause do not apply to them unless
4098 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00004099 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004100 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004101 return false;
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004102
4103 if (Op == OO_New || Op == OO_Array_New) {
4104 bool ret = false;
4105 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4106 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4107 QualType T = Context.getCanonicalType((*Param)->getType());
4108 if (!T->isDependentType() && SizeTy != T) {
4109 Diag(FnDecl->getLocation(),
4110 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4111 << SizeTy;
4112 ret = true;
4113 }
4114 }
4115 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4116 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4117 return Diag(FnDecl->getLocation(),
4118 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregorcffecd02009-11-12 16:49:45 +00004119 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004120 return ret;
4121 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004122
4123 // C++ [over.oper]p6:
4124 // An operator function shall either be a non-static member
4125 // function or be a non-member function and have at least one
4126 // parameter whose type is a class, a reference to a class, an
4127 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004128 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4129 if (MethodDecl->isStatic())
4130 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004131 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004132 } else {
4133 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004134 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4135 ParamEnd = FnDecl->param_end();
4136 Param != ParamEnd; ++Param) {
4137 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004138 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4139 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004140 ClassOrEnumParam = true;
4141 break;
4142 }
4143 }
4144
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004145 if (!ClassOrEnumParam)
4146 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004147 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004148 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004149 }
4150
4151 // C++ [over.oper]p8:
4152 // An operator function cannot have default arguments (8.3.6),
4153 // except where explicitly stated below.
4154 //
Mike Stump1eb44332009-09-09 15:08:12 +00004155 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004156 // (C++ [over.call]p1).
4157 if (Op != OO_Call) {
4158 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4159 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004160 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004161 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004162 diag::err_operator_overload_default_arg)
4163 << FnDecl->getDeclName();
4164 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004165 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004166 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004167 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004168 }
4169 }
4170
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004171 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4172 { false, false, false }
4173#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4174 , { Unary, Binary, MemberOnly }
4175#include "clang/Basic/OperatorKinds.def"
4176 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004177
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004178 bool CanBeUnaryOperator = OperatorUses[Op][0];
4179 bool CanBeBinaryOperator = OperatorUses[Op][1];
4180 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004181
4182 // C++ [over.oper]p8:
4183 // [...] Operator functions cannot have more or fewer parameters
4184 // than the number required for the corresponding operator, as
4185 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004186 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004187 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004188 if (Op != OO_Call &&
4189 ((NumParams == 1 && !CanBeUnaryOperator) ||
4190 (NumParams == 2 && !CanBeBinaryOperator) ||
4191 (NumParams < 1) || (NumParams > 2))) {
4192 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004193 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004194 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004195 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004196 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004197 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004198 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004199 assert(CanBeBinaryOperator &&
4200 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004201 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004202 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004203
Chris Lattner416e46f2008-11-21 07:57:12 +00004204 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004205 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004206 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004207
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004208 // Overloaded operators other than operator() cannot be variadic.
4209 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004210 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004211 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004212 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004213 }
4214
4215 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004216 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4217 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004218 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004219 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004220 }
4221
4222 // C++ [over.inc]p1:
4223 // The user-defined function called operator++ implements the
4224 // prefix and postfix ++ operator. If this function is a member
4225 // function with no parameters, or a non-member function with one
4226 // parameter of class or enumeration type, it defines the prefix
4227 // increment operator ++ for objects of that type. If the function
4228 // is a member function with one parameter (which shall be of type
4229 // int) or a non-member function with two parameters (the second
4230 // of which shall be of type int), it defines the postfix
4231 // increment operator ++ for objects of that type.
4232 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4233 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4234 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004235 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004236 ParamIsInt = BT->getKind() == BuiltinType::Int;
4237
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004238 if (!ParamIsInt)
4239 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004240 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004241 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004242 }
4243
Sebastian Redl64b45f72009-01-05 20:52:13 +00004244 // Notify the class if it got an assignment operator.
4245 if (Op == OO_Equal) {
4246 // Would have returned earlier otherwise.
4247 assert(isa<CXXMethodDecl>(FnDecl) &&
4248 "Overloaded = not member, but not filtered.");
4249 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4250 Method->getParent()->addedAssignmentOperator(Context, Method);
4251 }
4252
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004253 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004254}
Chris Lattner5a003a42008-12-17 07:09:26 +00004255
Douglas Gregor074149e2009-01-05 19:45:36 +00004256/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4257/// linkage specification, including the language and (if present)
4258/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4259/// the location of the language string literal, which is provided
4260/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4261/// the '{' brace. Otherwise, this linkage specification does not
4262/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004263Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4264 SourceLocation ExternLoc,
4265 SourceLocation LangLoc,
4266 const char *Lang,
4267 unsigned StrSize,
4268 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004269 LinkageSpecDecl::LanguageIDs Language;
4270 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4271 Language = LinkageSpecDecl::lang_c;
4272 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4273 Language = LinkageSpecDecl::lang_cxx;
4274 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004275 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004276 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004277 }
Mike Stump1eb44332009-09-09 15:08:12 +00004278
Chris Lattnercc98eac2008-12-17 07:13:27 +00004279 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004280
Douglas Gregor074149e2009-01-05 19:45:36 +00004281 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004282 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004283 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004284 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004285 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004286 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004287}
4288
Douglas Gregor074149e2009-01-05 19:45:36 +00004289/// ActOnFinishLinkageSpecification - Completely the definition of
4290/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4291/// valid, it's the position of the closing '}' brace in a linkage
4292/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004293Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4294 DeclPtrTy LinkageSpec,
4295 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004296 if (LinkageSpec)
4297 PopDeclContext();
4298 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004299}
4300
Douglas Gregord308e622009-05-18 20:51:54 +00004301/// \brief Perform semantic analysis for the variable declaration that
4302/// occurs within a C++ catch clause, returning the newly-created
4303/// variable.
4304VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004305 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004306 IdentifierInfo *Name,
4307 SourceLocation Loc,
4308 SourceRange Range) {
4309 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004310
4311 // Arrays and functions decay.
4312 if (ExDeclType->isArrayType())
4313 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4314 else if (ExDeclType->isFunctionType())
4315 ExDeclType = Context.getPointerType(ExDeclType);
4316
4317 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4318 // The exception-declaration shall not denote a pointer or reference to an
4319 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004320 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004321 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004322 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004323 Invalid = true;
4324 }
Douglas Gregord308e622009-05-18 20:51:54 +00004325
Sebastian Redl4b07b292008-12-22 19:15:10 +00004326 QualType BaseType = ExDeclType;
4327 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004328 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004329 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004330 BaseType = Ptr->getPointeeType();
4331 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004332 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004333 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004334 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004335 BaseType = Ref->getPointeeType();
4336 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004337 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004338 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004339 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004340 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004341 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004342
Mike Stump1eb44332009-09-09 15:08:12 +00004343 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004344 RequireNonAbstractType(Loc, ExDeclType,
4345 diag::err_abstract_type_in_decl,
4346 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004347 Invalid = true;
4348
Douglas Gregord308e622009-05-18 20:51:54 +00004349 // FIXME: Need to test for ability to copy-construct and destroy the
4350 // exception variable.
4351
Sebastian Redl8351da02008-12-22 21:35:02 +00004352 // FIXME: Need to check for abstract classes.
4353
Mike Stump1eb44332009-09-09 15:08:12 +00004354 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004355 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004356
4357 if (Invalid)
4358 ExDecl->setInvalidDecl();
4359
4360 return ExDecl;
4361}
4362
4363/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4364/// handler.
4365Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004366 DeclaratorInfo *DInfo = 0;
4367 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004368
4369 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004370 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004371 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004372 // The scope should be freshly made just for us. There is just no way
4373 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004374 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004375 if (PrevDecl->isTemplateParameter()) {
4376 // Maybe we will complain about the shadowed template parameter.
4377 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004378 }
4379 }
4380
Chris Lattnereaaebc72009-04-25 08:06:05 +00004381 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004382 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4383 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004384 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004385 }
4386
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004387 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004388 D.getIdentifier(),
4389 D.getIdentifierLoc(),
4390 D.getDeclSpec().getSourceRange());
4391
Chris Lattnereaaebc72009-04-25 08:06:05 +00004392 if (Invalid)
4393 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Sebastian Redl4b07b292008-12-22 19:15:10 +00004395 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004396 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004397 PushOnScopeChains(ExDecl, S);
4398 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004399 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004400
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004401 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004402 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004403}
Anders Carlssonfb311762009-03-14 00:25:26 +00004404
Mike Stump1eb44332009-09-09 15:08:12 +00004405Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004406 ExprArg assertexpr,
4407 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004408 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004409 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004410 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4411
Anders Carlssonc3082412009-03-14 00:33:21 +00004412 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4413 llvm::APSInt Value(32);
4414 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4415 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4416 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004417 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004418 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004419
Anders Carlssonc3082412009-03-14 00:33:21 +00004420 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004421 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004422 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004423 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004424 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004425 }
4426 }
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Anders Carlsson77d81422009-03-15 17:35:16 +00004428 assertexpr.release();
4429 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004430 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004431 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004432
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004433 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004434 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004435}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004436
John McCalldd4a3b02009-09-16 22:47:08 +00004437/// Handle a friend type declaration. This works in tandem with
4438/// ActOnTag.
4439///
4440/// Notes on friend class templates:
4441///
4442/// We generally treat friend class declarations as if they were
4443/// declaring a class. So, for example, the elaborated type specifier
4444/// in a friend declaration is required to obey the restrictions of a
4445/// class-head (i.e. no typedefs in the scope chain), template
4446/// parameters are required to match up with simple template-ids, &c.
4447/// However, unlike when declaring a template specialization, it's
4448/// okay to refer to a template specialization without an empty
4449/// template parameter declaration, e.g.
4450/// friend class A<T>::B<unsigned>;
4451/// We permit this as a special case; if there are any template
4452/// parameters present at all, require proper matching, i.e.
4453/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004454Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004455 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004456 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004457
4458 assert(DS.isFriendSpecified());
4459 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4460
John McCalldd4a3b02009-09-16 22:47:08 +00004461 // Try to convert the decl specifier to a type. This works for
4462 // friend templates because ActOnTag never produces a ClassTemplateDecl
4463 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004464 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004465 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4466 if (TheDeclarator.isInvalidType())
4467 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004468
John McCalldd4a3b02009-09-16 22:47:08 +00004469 // This is definitely an error in C++98. It's probably meant to
4470 // be forbidden in C++0x, too, but the specification is just
4471 // poorly written.
4472 //
4473 // The problem is with declarations like the following:
4474 // template <T> friend A<T>::foo;
4475 // where deciding whether a class C is a friend or not now hinges
4476 // on whether there exists an instantiation of A that causes
4477 // 'foo' to equal C. There are restrictions on class-heads
4478 // (which we declare (by fiat) elaborated friend declarations to
4479 // be) that makes this tractable.
4480 //
4481 // FIXME: handle "template <> friend class A<T>;", which
4482 // is possibly well-formed? Who even knows?
4483 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4484 Diag(Loc, diag::err_tagless_friend_type_template)
4485 << DS.getSourceRange();
4486 return DeclPtrTy();
4487 }
4488
John McCall02cace72009-08-28 07:59:38 +00004489 // C++ [class.friend]p2:
4490 // An elaborated-type-specifier shall be used in a friend declaration
4491 // for a class.*
4492 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004493 // This is one of the rare places in Clang where it's legitimate to
4494 // ask about the "spelling" of the type.
4495 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4496 // If we evaluated the type to a record type, suggest putting
4497 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004498 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004499 RecordDecl *RD = RT->getDecl();
4500
4501 std::string InsertionText = std::string(" ") + RD->getKindName();
4502
John McCalle3af0232009-10-07 23:34:25 +00004503 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4504 << (unsigned) RD->getTagKind()
4505 << T
4506 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004507 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4508 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004509 return DeclPtrTy();
4510 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004511 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4512 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004513 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004514 }
4515 }
4516
John McCalle3af0232009-10-07 23:34:25 +00004517 // Enum types cannot be friends.
4518 if (T->getAs<EnumType>()) {
4519 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4520 << SourceRange(DS.getFriendSpecLoc());
4521 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004522 }
John McCall02cace72009-08-28 07:59:38 +00004523
John McCall02cace72009-08-28 07:59:38 +00004524 // C++98 [class.friend]p1: A friend of a class is a function
4525 // or class that is not a member of the class . . .
4526 // But that's a silly restriction which nobody implements for
4527 // inner classes, and C++0x removes it anyway, so we only report
4528 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004529 if (!getLangOptions().CPlusPlus0x)
4530 if (const RecordType *RT = T->getAs<RecordType>())
4531 if (RT->getDecl()->getDeclContext() == CurContext)
4532 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004533
John McCalldd4a3b02009-09-16 22:47:08 +00004534 Decl *D;
4535 if (TempParams.size())
4536 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4537 TempParams.size(),
4538 (TemplateParameterList**) TempParams.release(),
4539 T.getTypePtr(),
4540 DS.getFriendSpecLoc());
4541 else
4542 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4543 DS.getFriendSpecLoc());
4544 D->setAccess(AS_public);
4545 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004546
John McCalldd4a3b02009-09-16 22:47:08 +00004547 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004548}
4549
John McCallbbbcdd92009-09-11 21:02:39 +00004550Sema::DeclPtrTy
4551Sema::ActOnFriendFunctionDecl(Scope *S,
4552 Declarator &D,
4553 bool IsDefinition,
4554 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004555 const DeclSpec &DS = D.getDeclSpec();
4556
4557 assert(DS.isFriendSpecified());
4558 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4559
4560 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004561 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004562 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004563
4564 // C++ [class.friend]p1
4565 // A friend of a class is a function or class....
4566 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004567 // It *doesn't* see through dependent types, which is correct
4568 // according to [temp.arg.type]p3:
4569 // If a declaration acquires a function type through a
4570 // type dependent on a template-parameter and this causes
4571 // a declaration that does not use the syntactic form of a
4572 // function declarator to have a function type, the program
4573 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004574 if (!T->isFunctionType()) {
4575 Diag(Loc, diag::err_unexpected_friend);
4576
4577 // It might be worthwhile to try to recover by creating an
4578 // appropriate declaration.
4579 return DeclPtrTy();
4580 }
4581
4582 // C++ [namespace.memdef]p3
4583 // - If a friend declaration in a non-local class first declares a
4584 // class or function, the friend class or function is a member
4585 // of the innermost enclosing namespace.
4586 // - The name of the friend is not found by simple name lookup
4587 // until a matching declaration is provided in that namespace
4588 // scope (either before or after the class declaration granting
4589 // friendship).
4590 // - If a friend function is called, its name may be found by the
4591 // name lookup that considers functions from namespaces and
4592 // classes associated with the types of the function arguments.
4593 // - When looking for a prior declaration of a class or a function
4594 // declared as a friend, scopes outside the innermost enclosing
4595 // namespace scope are not considered.
4596
John McCall02cace72009-08-28 07:59:38 +00004597 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4598 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004599 assert(Name);
4600
John McCall67d1a672009-08-06 02:15:43 +00004601 // The context we found the declaration in, or in which we should
4602 // create the declaration.
4603 DeclContext *DC;
4604
4605 // FIXME: handle local classes
4606
4607 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004608 NamedDecl *PrevDecl = 0;
John McCall67d1a672009-08-06 02:15:43 +00004609 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004610 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004611 DC = computeDeclContext(ScopeQual);
4612
4613 // FIXME: handle dependent contexts
4614 if (!DC) return DeclPtrTy();
4615
John McCallf36e02d2009-10-09 21:13:30 +00004616 LookupResult R;
4617 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4618 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004619
4620 // If searching in that context implicitly found a declaration in
4621 // a different context, treat it like it wasn't found at all.
4622 // TODO: better diagnostics for this case. Suggesting the right
4623 // qualified scope would be nice...
Douglas Gregor182ddf02009-09-28 00:08:27 +00004624 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004625 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004626 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4627 return DeclPtrTy();
4628 }
4629
4630 // C++ [class.friend]p1: A friend of a class is a function or
4631 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004632 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004633 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4634
John McCall67d1a672009-08-06 02:15:43 +00004635 // Otherwise walk out to the nearest namespace scope looking for matches.
4636 } else {
4637 // TODO: handle local class contexts.
4638
4639 DC = CurContext;
4640 while (true) {
4641 // Skip class contexts. If someone can cite chapter and verse
4642 // for this behavior, that would be nice --- it's what GCC and
4643 // EDG do, and it seems like a reasonable intent, but the spec
4644 // really only says that checks for unqualified existing
4645 // declarations should stop at the nearest enclosing namespace,
4646 // not that they should only consider the nearest enclosing
4647 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004648 while (DC->isRecord())
4649 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004650
John McCallf36e02d2009-10-09 21:13:30 +00004651 LookupResult R;
4652 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4653 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004654
4655 // TODO: decide what we think about using declarations.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004656 if (PrevDecl)
John McCall67d1a672009-08-06 02:15:43 +00004657 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004658
John McCall67d1a672009-08-06 02:15:43 +00004659 if (DC->isFileContext()) break;
4660 DC = DC->getParent();
4661 }
4662
4663 // C++ [class.friend]p1: A friend of a class is a function or
4664 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004665 // C++0x changes this for both friend types and functions.
4666 // Most C++ 98 compilers do seem to give an error here, so
4667 // we do, too.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004668 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004669 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4670 }
4671
Douglas Gregor182ddf02009-09-28 00:08:27 +00004672 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004673 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004674 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4675 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4676 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00004677 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004678 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4679 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004680 return DeclPtrTy();
4681 }
John McCall67d1a672009-08-06 02:15:43 +00004682 }
4683
Douglas Gregor182ddf02009-09-28 00:08:27 +00004684 bool Redeclaration = false;
4685 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregora735b202009-10-13 14:39:41 +00004686 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004687 IsDefinition,
4688 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004689 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004690
Douglas Gregor182ddf02009-09-28 00:08:27 +00004691 assert(ND->getDeclContext() == DC);
4692 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004693
John McCallab88d972009-08-31 22:39:49 +00004694 // Add the function declaration to the appropriate lookup tables,
4695 // adjusting the redeclarations list as necessary. We don't
4696 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004697 //
John McCallab88d972009-08-31 22:39:49 +00004698 // Also update the scope-based lookup if the target context's
4699 // lookup context is in lexical scope.
4700 if (!CurContext->isDependentContext()) {
4701 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004702 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004703 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004704 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004705 }
John McCall02cace72009-08-28 07:59:38 +00004706
4707 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004708 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004709 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004710 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004711 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004712
Douglas Gregor182ddf02009-09-28 00:08:27 +00004713 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004714}
4715
Chris Lattnerb28317a2009-03-28 19:18:32 +00004716void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004717 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Chris Lattnerb28317a2009-03-28 19:18:32 +00004719 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004720 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4721 if (!Fn) {
4722 Diag(DelLoc, diag::err_deleted_non_function);
4723 return;
4724 }
4725 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4726 Diag(DelLoc, diag::err_deleted_decl_not_first);
4727 Diag(Prev->getLocation(), diag::note_previous_declaration);
4728 // If the declaration wasn't the first, we delete the function anyway for
4729 // recovery.
4730 }
4731 Fn->setDeleted();
4732}
Sebastian Redl13e88542009-04-27 21:33:24 +00004733
4734static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4735 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4736 ++CI) {
4737 Stmt *SubStmt = *CI;
4738 if (!SubStmt)
4739 continue;
4740 if (isa<ReturnStmt>(SubStmt))
4741 Self.Diag(SubStmt->getSourceRange().getBegin(),
4742 diag::err_return_in_constructor_handler);
4743 if (!isa<Expr>(SubStmt))
4744 SearchForReturnInStmt(Self, SubStmt);
4745 }
4746}
4747
4748void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4749 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4750 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4751 SearchForReturnInStmt(*this, Handler);
4752 }
4753}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004754
Mike Stump1eb44332009-09-09 15:08:12 +00004755bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004756 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004757 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4758 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004759
4760 QualType CNewTy = Context.getCanonicalType(NewTy);
4761 QualType COldTy = Context.getCanonicalType(OldTy);
4762
Mike Stump1eb44332009-09-09 15:08:12 +00004763 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00004764 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004765 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004766
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004767 // Check if the return types are covariant
4768 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004769
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004770 /// Both types must be pointers or references to classes.
4771 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4772 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4773 NewClassTy = NewPT->getPointeeType();
4774 OldClassTy = OldPT->getPointeeType();
4775 }
4776 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4777 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4778 NewClassTy = NewRT->getPointeeType();
4779 OldClassTy = OldRT->getPointeeType();
4780 }
4781 }
Mike Stump1eb44332009-09-09 15:08:12 +00004782
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004783 // The return types aren't either both pointers or references to a class type.
4784 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004785 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004786 diag::err_different_return_type_for_overriding_virtual_function)
4787 << New->getDeclName() << NewTy << OldTy;
4788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004789
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004790 return true;
4791 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004792
Douglas Gregora4923eb2009-11-16 21:35:15 +00004793 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004794 // Check if the new class derives from the old class.
4795 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4796 Diag(New->getLocation(),
4797 diag::err_covariant_return_not_derived)
4798 << New->getDeclName() << NewTy << OldTy;
4799 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4800 return true;
4801 }
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004803 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004804 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004805 diag::err_covariant_return_inaccessible_base,
4806 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4807 // FIXME: Should this point to the return type?
4808 New->getLocation(), SourceRange(), New->getDeclName())) {
4809 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4810 return true;
4811 }
4812 }
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004814 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004815 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004816 Diag(New->getLocation(),
4817 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004818 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004819 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4820 return true;
4821 };
Mike Stump1eb44332009-09-09 15:08:12 +00004822
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004823
4824 // The new class type must have the same or less qualifiers as the old type.
4825 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4826 Diag(New->getLocation(),
4827 diag::err_covariant_return_type_class_type_more_qualified)
4828 << New->getDeclName() << NewTy << OldTy;
4829 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4830 return true;
4831 };
Mike Stump1eb44332009-09-09 15:08:12 +00004832
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004833 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004834}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004835
4836/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4837/// initializer for the declaration 'Dcl'.
4838/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4839/// static data member of class X, names should be looked up in the scope of
4840/// class X.
4841void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004842 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004844 Decl *D = Dcl.getAs<Decl>();
4845 // If there is no declaration, there was an error parsing it.
4846 if (D == 0)
4847 return;
4848
4849 // Check whether it is a declaration with a nested name specifier like
4850 // int foo::bar;
4851 if (!D->isOutOfLine())
4852 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004854 // C++ [basic.lookup.unqual]p13
4855 //
4856 // A name used in the definition of a static data member of class X
4857 // (after the qualified-id of the static member) is looked up as if the name
4858 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004860 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004861 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004862}
4863
4864/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4865/// initializer for the declaration 'Dcl'.
4866void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004867 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004868
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004869 Decl *D = Dcl.getAs<Decl>();
4870 // If there is no declaration, there was an error parsing it.
4871 if (D == 0)
4872 return;
4873
4874 // Check whether it is a declaration with a nested name specifier like
4875 // int foo::bar;
4876 if (!D->isOutOfLine())
4877 return;
4878
4879 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004880 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004881}