blob: 90aef21637319904e4187957aa277c9bfadf2568 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000027#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000028#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000029
30using namespace clang;
31
Chris Lattner8123a952008-04-10 02:22:51 +000032//===----------------------------------------------------------------------===//
33// CheckDefaultArgumentVisitor
34//===----------------------------------------------------------------------===//
35
Chris Lattner9e979552008-04-12 23:52:44 +000036namespace {
37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
38 /// the default argument of a parameter to determine whether it
39 /// contains any ill-formed subexpressions. For example, this will
40 /// diagnose the use of local variables or parameters within the
41 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000042 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000043 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000044 Expr *DefaultArg;
45 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000046
Chris Lattner9e979552008-04-12 23:52:44 +000047 public:
Mike Stump1eb44332009-09-09 15:08:12 +000048 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000049 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-04-12 23:52:44 +000051 bool VisitExpr(Expr *Node);
52 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000053 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000054 };
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 /// VisitExpr - Visit all of the children of this expression.
57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
58 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000059 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000060 E = Node->child_end(); I != E; ++I)
61 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000062 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000063 }
64
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitDeclRefExpr - Visit a reference to a declaration, to
66 /// determine whether this declaration can be used in the default
67 /// argument expression.
68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000069 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000070 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
71 // C++ [dcl.fct.default]p9
72 // Default arguments are evaluated each time the function is
73 // called. The order of evaluation of function arguments is
74 // unspecified. Consequently, parameters of a function shall not
75 // be used in default argument expressions, even if they are not
76 // evaluated. Parameters of a function declared before a default
77 // argument expression are in scope and can hide namespace and
78 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000079 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000080 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000081 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000082 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000083 // C++ [dcl.fct.default]p7
84 // Local variables shall not be used in default argument
85 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000086 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000090 }
Chris Lattner8123a952008-04-10 02:22:51 +000091
Douglas Gregor3996f232008-11-04 13:41:56 +000092 return false;
93 }
Chris Lattner9e979552008-04-12 23:52:44 +000094
Douglas Gregor796da182008-11-04 14:32:21 +000095 /// VisitCXXThisExpr - Visit a C++ "this" expression.
96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
97 // C++ [dcl.fct.default]p8:
98 // The keyword this shall not be used in a default argument of a
99 // member function.
100 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_this)
102 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104}
105
Anders Carlssoned961f92009-08-25 02:29:20 +0000106bool
107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000108 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000109 QualType ParamType = Param->getType();
110
Anders Carlsson5653ca52009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlssoned961f92009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000127 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Anders Carlssoned961f92009-08-25 02:29:20 +0000131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Anders Carlssoned961f92009-08-25 02:29:20 +0000134 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000137}
138
Chris Lattner8123a952008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000142void
Mike Stump1eb44332009-09-09 15:08:12 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Chris Lattnerb28317a2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlsson66e30672009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Anders Carlssoned961f92009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000170}
171
Douglas Gregor61366e92008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000179 if (!param)
180 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Anders Carlsson5e300d12009-06-12 16:51:40 +0000186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000187}
188
Douglas Gregor72b505b2008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000192 if (!param)
193 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Anders Carlsson5e300d12009-06-12 16:51:40 +0000197 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Anders Carlsson5e300d12009-06-12 16:51:40 +0000199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000200}
201
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattner3d1cee32008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000256 //
257 // C++ [dcl.fct.default]p6:
258 // Except for member functions of class templates, the default arguments
259 // in a member function definition that appears outside of the class
260 // definition are added to the set of default arguments provided by the
261 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
263 ParmVarDecl *OldParam = Old->getParamDecl(p);
264 ParmVarDecl *NewParam = New->getParamDecl(p);
265
Douglas Gregor6cc15182009-09-11 18:44:32 +0000266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000267 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000268 diag::err_param_default_argument_redefinition)
Douglas Gregor6cc15182009-09-11 18:44:32 +0000269 << NewParam->getDefaultArgRange();
270
271 // Look for the function declaration where the default argument was
272 // actually written, which may be a declaration prior to Old.
273 for (FunctionDecl *Older = Old->getPreviousDeclaration();
274 Older; Older = Older->getPreviousDeclaration()) {
275 if (!Older->getParamDecl(p)->hasDefaultArg())
276 break;
277
278 OldParam = Older->getParamDecl(p);
279 }
280
281 Diag(OldParam->getLocation(), diag::note_previous_definition)
282 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000283 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000284 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000285 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000286 if (OldParam->hasUninstantiatedDefaultArg())
287 NewParam->setUninstantiatedDefaultArg(
288 OldParam->getUninstantiatedDefaultArg());
289 else
290 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000291 } else if (NewParam->hasDefaultArg()) {
292 if (New->getDescribedFunctionTemplate()) {
293 // Paragraph 4, quoted above, only applies to non-template functions.
294 Diag(NewParam->getLocation(),
295 diag::err_param_default_argument_template_redecl)
296 << NewParam->getDefaultArgRange();
297 Diag(Old->getLocation(), diag::note_template_prev_declaration)
298 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000299 } else if (New->getTemplateSpecializationKind()
300 != TSK_ImplicitInstantiation &&
301 New->getTemplateSpecializationKind() != TSK_Undeclared) {
302 // C++ [temp.expr.spec]p21:
303 // Default function arguments shall not be specified in a declaration
304 // or a definition for one of the following explicit specializations:
305 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000306 // - the explicit specialization of a member function template;
307 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000308 // template where the class template specialization to which the
309 // member function specialization belongs is implicitly
310 // instantiated.
311 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
312 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
313 << New->getDeclName()
314 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000315 } else if (New->getDeclContext()->isDependentContext()) {
316 // C++ [dcl.fct.default]p6 (DR217):
317 // Default arguments for a member function of a class template shall
318 // be specified on the initial declaration of the member function
319 // within the class template.
320 //
321 // Reading the tea leaves a bit in DR217 and its reference to DR205
322 // leads me to the conclusion that one cannot add default function
323 // arguments for an out-of-line definition of a member function of a
324 // dependent type.
325 int WhichKind = 2;
326 if (CXXRecordDecl *Record
327 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
328 if (Record->getDescribedClassTemplate())
329 WhichKind = 0;
330 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
331 WhichKind = 1;
332 else
333 WhichKind = 2;
334 }
335
336 Diag(NewParam->getLocation(),
337 diag::err_param_default_argument_member_template_redecl)
338 << WhichKind
339 << NewParam->getDefaultArgRange();
340 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000341 }
342 }
343
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000344 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000345 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
346 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000347 Invalid = true;
348 }
349
Douglas Gregorcda9c672009-02-16 17:45:42 +0000350 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000351}
352
353/// CheckCXXDefaultArguments - Verify that the default arguments for a
354/// function declaration are well-formed according to C++
355/// [dcl.fct.default].
356void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
357 unsigned NumParams = FD->getNumParams();
358 unsigned p;
359
360 // Find first parameter with a default argument
361 for (p = 0; p < NumParams; ++p) {
362 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000363 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364 break;
365 }
366
367 // C++ [dcl.fct.default]p4:
368 // In a given function declaration, all parameters
369 // subsequent to a parameter with a default argument shall
370 // have default arguments supplied in this or previous
371 // declarations. A default argument shall not be redefined
372 // by a later declaration (not even to the same value).
373 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000374 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000377 if (Param->isInvalidDecl())
378 /* We already complained about this parameter. */;
379 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000380 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000381 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000382 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 else
Mike Stump1eb44332009-09-09 15:08:12 +0000384 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chris Lattner3d1cee32008-04-08 05:04:30 +0000387 LastMissingDefaultArg = p;
388 }
389 }
390
391 if (LastMissingDefaultArg > 0) {
392 // Some default arguments were missing. Clear out all of the
393 // default arguments up to (and including) the last missing
394 // default argument, so that we leave the function parameters
395 // in a semantically valid state.
396 for (p = 0; p <= LastMissingDefaultArg; ++p) {
397 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000398 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000399 if (!Param->hasUnparsedDefaultArg())
400 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 Param->setDefaultArg(0);
402 }
403 }
404 }
405}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000406
Douglas Gregorb48fe382008-10-31 09:07:45 +0000407/// isCurrentClassName - Determine whether the identifier II is the
408/// name of the class type currently being defined. In the case of
409/// nested classes, this will only return true if II is the name of
410/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000411bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
412 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000413 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000414 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000415 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
417 } else
418 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
419
420 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421 return &II == CurDecl->getIdentifier();
422 else
423 return false;
424}
425
Mike Stump1eb44332009-09-09 15:08:12 +0000426/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000427///
428/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
429/// and returns NULL otherwise.
430CXXBaseSpecifier *
431Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
432 SourceRange SpecifierRange,
433 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000434 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000435 SourceLocation BaseLoc) {
436 // C++ [class.union]p1:
437 // A union shall not have base classes.
438 if (Class->isUnion()) {
439 Diag(Class->getLocation(), diag::err_base_clause_on_union)
440 << SpecifierRange;
441 return 0;
442 }
443
444 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000445 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000446 Class->getTagKind() == RecordDecl::TK_class,
447 Access, BaseType);
448
449 // Base specifiers must be record types.
450 if (!BaseType->isRecordType()) {
451 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
452 return 0;
453 }
454
455 // C++ [class.union]p1:
456 // A union shall not be used as a base class.
457 if (BaseType->isUnionType()) {
458 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
459 return 0;
460 }
461
462 // C++ [class.derived]p2:
463 // The class-name in a base-specifier shall not be an incompletely
464 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000465 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000466 PDiag(diag::err_incomplete_base_class)
467 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000468 return 0;
469
Eli Friedman1d954f62009-08-15 21:55:26 +0000470 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000471 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000472 assert(BaseDecl && "Record type has no declaration");
473 BaseDecl = BaseDecl->getDefinition(Context);
474 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000475 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
476 assert(CXXBaseDecl && "Base type is not a C++ type");
477 if (!CXXBaseDecl->isEmpty())
478 Class->setEmpty(false);
479 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000480 Class->setPolymorphic(true);
481
482 // C++ [dcl.init.aggr]p1:
483 // An aggregate is [...] a class with [...] no base classes [...].
484 Class->setAggregate(false);
485 Class->setPOD(false);
486
Anders Carlsson347ba892009-04-16 00:08:20 +0000487 if (Virtual) {
488 // C++ [class.ctor]p5:
489 // A constructor is trivial if its class has no virtual base classes.
490 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000491
492 // C++ [class.copy]p6:
493 // A copy constructor is trivial if its class has no virtual base classes.
494 Class->setHasTrivialCopyConstructor(false);
495
496 // C++ [class.copy]p11:
497 // A copy assignment operator is trivial if its class has no virtual
498 // base classes.
499 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000500
501 // C++0x [meta.unary.prop] is_empty:
502 // T is a class type, but not a union type, with ... no virtual base
503 // classes
504 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000505 } else {
506 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000507 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000508 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000509 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
510 Class->setHasTrivialConstructor(false);
511
512 // C++ [class.copy]p6:
513 // A copy constructor is trivial if all the direct base classes of its
514 // class have trivial copy constructors.
515 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
516 Class->setHasTrivialCopyConstructor(false);
517
518 // C++ [class.copy]p11:
519 // A copy assignment operator is trivial if all the direct base classes
520 // of its class have trivial copy assignment operators.
521 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
522 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000523 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000524
525 // C++ [class.ctor]p3:
526 // A destructor is trivial if all the direct base classes of its class
527 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000528 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
529 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531 // Create the base specifier.
532 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000533 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
534 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000535 Access, BaseType);
536}
537
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000538/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
539/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000540/// example:
541/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000542/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000543Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000544Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000545 bool Virtual, AccessSpecifier Access,
546 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000547 if (!classdecl)
548 return true;
549
Douglas Gregor40808ce2009-03-09 23:48:35 +0000550 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000551 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000552 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000553 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
554 Virtual, Access,
555 BaseType, BaseLoc))
556 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Douglas Gregor2943aed2009-03-03 04:44:36 +0000558 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000559}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000560
Douglas Gregor2943aed2009-03-03 04:44:36 +0000561/// \brief Performs the actual work of attaching the given base class
562/// specifiers to a C++ class.
563bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
564 unsigned NumBases) {
565 if (NumBases == 0)
566 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000567
568 // Used to keep track of which base types we have already seen, so
569 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000570 // that the key is always the unqualified canonical type of the base
571 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000572 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
573
574 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000575 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000577 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000578 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000579 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000580 NewBaseType = NewBaseType.getUnqualifiedType();
581
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000582 if (KnownBaseTypes[NewBaseType]) {
583 // C++ [class.mi]p3:
584 // A class shall not be specified as a direct base class of a
585 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000587 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000588 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000590
591 // Delete the duplicate base class specifier; we're going to
592 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000593 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594
595 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000596 } else {
597 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598 KnownBaseTypes[NewBaseType] = Bases[idx];
599 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000600 }
601 }
602
603 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000604 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000605
606 // Delete the remaining (good) base class specifiers, since their
607 // data has been copied into the CXXRecordDecl.
608 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000609 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000610
611 return Invalid;
612}
613
614/// ActOnBaseSpecifiers - Attach the given base specifiers to the
615/// class, after checking whether there are any duplicate base
616/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000617void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 unsigned NumBases) {
619 if (!ClassDecl || !Bases || !NumBases)
620 return;
621
622 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000623 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000625}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000626
Douglas Gregora8f32e02009-10-06 17:59:45 +0000627/// \brief Determine whether the type \p Derived is a C++ class that is
628/// derived from the type \p Base.
629bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
630 if (!getLangOptions().CPlusPlus)
631 return false;
632
633 const RecordType *DerivedRT = Derived->getAs<RecordType>();
634 if (!DerivedRT)
635 return false;
636
637 const RecordType *BaseRT = Base->getAs<RecordType>();
638 if (!BaseRT)
639 return false;
640
641 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
642 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
643 return DerivedRD->isDerivedFrom(BaseRD);
644}
645
646/// \brief Determine whether the type \p Derived is a C++ class that is
647/// derived from the type \p Base.
648bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
649 if (!getLangOptions().CPlusPlus)
650 return false;
651
652 const RecordType *DerivedRT = Derived->getAs<RecordType>();
653 if (!DerivedRT)
654 return false;
655
656 const RecordType *BaseRT = Base->getAs<RecordType>();
657 if (!BaseRT)
658 return false;
659
660 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
661 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
662 return DerivedRD->isDerivedFrom(BaseRD, Paths);
663}
664
665/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
666/// conversion (where Derived and Base are class types) is
667/// well-formed, meaning that the conversion is unambiguous (and
668/// that all of the base classes are accessible). Returns true
669/// and emits a diagnostic if the code is ill-formed, returns false
670/// otherwise. Loc is the location where this routine should point to
671/// if there is an error, and Range is the source range to highlight
672/// if there is an error.
673bool
674Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
675 unsigned InaccessibleBaseID,
676 unsigned AmbigiousBaseConvID,
677 SourceLocation Loc, SourceRange Range,
678 DeclarationName Name) {
679 // First, determine whether the path from Derived to Base is
680 // ambiguous. This is slightly more expensive than checking whether
681 // the Derived to Base conversion exists, because here we need to
682 // explore multiple paths to determine if there is an ambiguity.
683 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
684 /*DetectVirtual=*/false);
685 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
686 assert(DerivationOkay &&
687 "Can only be used with a derived-to-base conversion");
688 (void)DerivationOkay;
689
690 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
691 // Check that the base class can be accessed.
692 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
693 Name);
694 }
695
696 // We know that the derived-to-base conversion is ambiguous, and
697 // we're going to produce a diagnostic. Perform the derived-to-base
698 // search just one more time to compute all of the possible paths so
699 // that we can print them out. This is more expensive than any of
700 // the previous derived-to-base checks we've done, but at this point
701 // performance isn't as much of an issue.
702 Paths.clear();
703 Paths.setRecordingPaths(true);
704 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
705 assert(StillOkay && "Can only be used with a derived-to-base conversion");
706 (void)StillOkay;
707
708 // Build up a textual representation of the ambiguous paths, e.g.,
709 // D -> B -> A, that will be used to illustrate the ambiguous
710 // conversions in the diagnostic. We only print one of the paths
711 // to each base class subobject.
712 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
713
714 Diag(Loc, AmbigiousBaseConvID)
715 << Derived << Base << PathDisplayStr << Range << Name;
716 return true;
717}
718
719bool
720Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
721 SourceLocation Loc, SourceRange Range) {
722 return CheckDerivedToBaseConversion(Derived, Base,
723 diag::err_conv_to_inaccessible_base,
724 diag::err_ambiguous_derived_to_base_conv,
725 Loc, Range, DeclarationName());
726}
727
728
729/// @brief Builds a string representing ambiguous paths from a
730/// specific derived class to different subobjects of the same base
731/// class.
732///
733/// This function builds a string that can be used in error messages
734/// to show the different paths that one can take through the
735/// inheritance hierarchy to go from the derived class to different
736/// subobjects of a base class. The result looks something like this:
737/// @code
738/// struct D -> struct B -> struct A
739/// struct D -> struct C -> struct A
740/// @endcode
741std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
742 std::string PathDisplayStr;
743 std::set<unsigned> DisplayedPaths;
744 for (CXXBasePaths::paths_iterator Path = Paths.begin();
745 Path != Paths.end(); ++Path) {
746 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
747 // We haven't displayed a path to this particular base
748 // class subobject yet.
749 PathDisplayStr += "\n ";
750 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
751 for (CXXBasePath::const_iterator Element = Path->begin();
752 Element != Path->end(); ++Element)
753 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
754 }
755 }
756
757 return PathDisplayStr;
758}
759
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000760//===----------------------------------------------------------------------===//
761// C++ class member Handling
762//===----------------------------------------------------------------------===//
763
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000764/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
765/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
766/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000767/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000768Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000769Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000770 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000771 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000772 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000773 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000774 Expr *BitWidth = static_cast<Expr*>(BW);
775 Expr *Init = static_cast<Expr*>(InitExpr);
776 SourceLocation Loc = D.getIdentifierLoc();
777
Sebastian Redl669d5d72008-11-14 23:42:31 +0000778 bool isFunc = D.isFunctionDeclarator();
779
John McCall67d1a672009-08-06 02:15:43 +0000780 assert(!DS.isFriendSpecified());
781
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000782 // C++ 9.2p6: A member shall not be declared to have automatic storage
783 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000784 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
785 // data members and cannot be applied to names declared const or static,
786 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000787 switch (DS.getStorageClassSpec()) {
788 case DeclSpec::SCS_unspecified:
789 case DeclSpec::SCS_typedef:
790 case DeclSpec::SCS_static:
791 // FALL THROUGH.
792 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000793 case DeclSpec::SCS_mutable:
794 if (isFunc) {
795 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000796 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000797 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000798 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Sebastian Redla11f42f2008-11-17 23:24:37 +0000800 // FIXME: It would be nicer if the keyword was ignored only for this
801 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000802 D.getMutableDeclSpec().ClearStorageClassSpecs();
803 } else {
804 QualType T = GetTypeForDeclarator(D, S);
805 diag::kind err = static_cast<diag::kind>(0);
806 if (T->isReferenceType())
807 err = diag::err_mutable_reference;
808 else if (T.isConstQualified())
809 err = diag::err_mutable_const;
810 if (err != 0) {
811 if (DS.getStorageClassSpecLoc().isValid())
812 Diag(DS.getStorageClassSpecLoc(), err);
813 else
814 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000815 // FIXME: It would be nicer if the keyword was ignored only for this
816 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000817 D.getMutableDeclSpec().ClearStorageClassSpecs();
818 }
819 }
820 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000821 default:
822 if (DS.getStorageClassSpecLoc().isValid())
823 Diag(DS.getStorageClassSpecLoc(),
824 diag::err_storageclass_invalid_for_member);
825 else
826 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
827 D.getMutableDeclSpec().ClearStorageClassSpecs();
828 }
829
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000830 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000831 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000832 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000833 // Check also for this case:
834 //
835 // typedef int f();
836 // f a;
837 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000838 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000839 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000840 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000841
Sebastian Redl669d5d72008-11-14 23:42:31 +0000842 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
843 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000844 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000845
846 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000847 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000848 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000849 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
850 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000851 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000852 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000853 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
854 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000855 if (!Member) {
856 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000857 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000858 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000859
860 // Non-instance-fields can't have a bitfield.
861 if (BitWidth) {
862 if (Member->isInvalidDecl()) {
863 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000864 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000865 // C++ 9.6p3: A bit-field shall not be a static member.
866 // "static member 'A' cannot be a bit-field"
867 Diag(Loc, diag::err_static_not_bitfield)
868 << Name << BitWidth->getSourceRange();
869 } else if (isa<TypedefDecl>(Member)) {
870 // "typedef member 'x' cannot be a bit-field"
871 Diag(Loc, diag::err_typedef_not_bitfield)
872 << Name << BitWidth->getSourceRange();
873 } else {
874 // A function typedef ("typedef int f(); f a;").
875 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
876 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000877 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000878 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner8b963ef2009-03-05 23:01:03 +0000881 DeleteExpr(BitWidth);
882 BitWidth = 0;
883 Member->setInvalidDecl();
884 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000885
886 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Douglas Gregor37b372b2009-08-20 22:52:58 +0000888 // If we have declared a member function template, set the access of the
889 // templated declaration as well.
890 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
891 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000892 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893
Douglas Gregor10bd3682008-11-17 22:58:34 +0000894 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000895
Douglas Gregor021c3b32009-03-11 23:00:04 +0000896 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000897 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000898 if (Deleted) // FIXME: Source location is not very good.
899 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000900
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000901 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000902 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000903 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000904 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000905 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000906}
907
Douglas Gregor7ad83902008-11-05 04:29:56 +0000908/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000909Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000910Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000911 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000912 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000913 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000914 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000915 SourceLocation IdLoc,
916 SourceLocation LParenLoc,
917 ExprTy **Args, unsigned NumArgs,
918 SourceLocation *CommaLocs,
919 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000920 if (!ConstructorD)
921 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000923 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000924
925 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000926 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000927 if (!Constructor) {
928 // The user wrote a constructor initializer on a function that is
929 // not a C++ constructor. Ignore the error for now, because we may
930 // have more member initializers coming; we'll diagnose it just
931 // once in ActOnMemInitializers.
932 return true;
933 }
934
935 CXXRecordDecl *ClassDecl = Constructor->getParent();
936
937 // C++ [class.base.init]p2:
938 // Names in a mem-initializer-id are looked up in the scope of the
939 // constructor’s class and, if not found in that scope, are looked
940 // up in the scope containing the constructor’s
941 // definition. [Note: if the constructor’s class contains a member
942 // with the same name as a direct or virtual base class of the
943 // class, a mem-initializer-id naming the member or base class and
944 // composed of a single identifier refers to the class member. A
945 // mem-initializer-id for the hidden base class may be specified
946 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000947 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000948 // Look for a member, first.
949 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000950 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000951 = ClassDecl->lookup(MemberOrBase);
952 if (Result.first != Result.second)
953 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000954
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000955 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000956
Eli Friedman59c04372009-07-29 19:44:27 +0000957 if (Member)
958 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
959 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000960 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000961 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000962 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000963 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000964 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000965 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
966 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000968 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000969
Eli Friedman59c04372009-07-29 19:44:27 +0000970 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
971 RParenLoc, ClassDecl);
972}
973
974Sema::MemInitResult
975Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
976 unsigned NumArgs, SourceLocation IdLoc,
977 SourceLocation RParenLoc) {
978 bool HasDependentArg = false;
979 for (unsigned i = 0; i < NumArgs; i++)
980 HasDependentArg |= Args[i]->isTypeDependent();
981
982 CXXConstructorDecl *C = 0;
983 QualType FieldType = Member->getType();
984 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
985 FieldType = Array->getElementType();
986 if (FieldType->isDependentType()) {
987 // Can't check init for dependent type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000988 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000989 if (!HasDependentArg) {
990 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
991
992 C = PerformInitializationByConstructor(FieldType,
993 MultiExprArg(*this,
994 (void**)Args,
995 NumArgs),
996 IdLoc,
997 SourceRange(IdLoc, RParenLoc),
998 Member->getDeclName(), IK_Direct,
999 ConstructorArgs);
1000
1001 if (C) {
1002 // Take over the constructor arguments as our own.
1003 NumArgs = ConstructorArgs.size();
1004 Args = (Expr **)ConstructorArgs.take();
1005 }
1006 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001007 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001008 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001009 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1010 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001011 Expr *NewExp;
1012 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001013 if (FieldType->isReferenceType()) {
1014 Diag(IdLoc, diag::err_null_intialized_reference_member)
1015 << Member->getDeclName();
1016 return Diag(Member->getLocation(), diag::note_declared_at);
1017 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001018 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1019 NumArgs = 1;
1020 }
1021 else
1022 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001023 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1024 return true;
1025 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001026 }
Eli Friedman59c04372009-07-29 19:44:27 +00001027 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001028 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001029 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001030}
1031
1032Sema::MemInitResult
1033Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1034 unsigned NumArgs, SourceLocation IdLoc,
1035 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1036 bool HasDependentArg = false;
1037 for (unsigned i = 0; i < NumArgs; i++)
1038 HasDependentArg |= Args[i]->isTypeDependent();
1039
1040 if (!BaseType->isDependentType()) {
1041 if (!BaseType->isRecordType())
1042 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1043 << BaseType << SourceRange(IdLoc, RParenLoc);
1044
1045 // C++ [class.base.init]p2:
1046 // [...] Unless the mem-initializer-id names a nonstatic data
1047 // member of the constructor’s class or a direct or virtual base
1048 // of that class, the mem-initializer is ill-formed. A
1049 // mem-initializer-list can initialize a base class using any
1050 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Eli Friedman59c04372009-07-29 19:44:27 +00001052 // First, check for a direct base class.
1053 const CXXBaseSpecifier *DirectBaseSpec = 0;
1054 for (CXXRecordDecl::base_class_const_iterator Base =
1055 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001056 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +00001057 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1058 // We found a direct base of this type. That's what we're
1059 // initializing.
1060 DirectBaseSpec = &*Base;
1061 break;
1062 }
1063 }
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Eli Friedman59c04372009-07-29 19:44:27 +00001065 // Check for a virtual base class.
1066 // FIXME: We might be able to short-circuit this if we know in advance that
1067 // there are no virtual bases.
1068 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1069 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1070 // We haven't found a base yet; search the class hierarchy for a
1071 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001072 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1073 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001074 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001075 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001076 Path != Paths.end(); ++Path) {
1077 if (Path->back().Base->isVirtual()) {
1078 VirtualBaseSpec = Path->back().Base;
1079 break;
1080 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001081 }
1082 }
1083 }
Eli Friedman59c04372009-07-29 19:44:27 +00001084
1085 // C++ [base.class.init]p2:
1086 // If a mem-initializer-id is ambiguous because it designates both
1087 // a direct non-virtual base class and an inherited virtual base
1088 // class, the mem-initializer is ill-formed.
1089 if (DirectBaseSpec && VirtualBaseSpec)
1090 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1091 << BaseType << SourceRange(IdLoc, RParenLoc);
1092 // C++ [base.class.init]p2:
1093 // Unless the mem-initializer-id names a nonstatic data membeer of the
1094 // constructor's class ot a direst or virtual base of that class, the
1095 // mem-initializer is ill-formed.
1096 if (!DirectBaseSpec && !VirtualBaseSpec)
1097 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1098 << BaseType << ClassDecl->getNameAsCString()
1099 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001100 }
1101
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001102 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001103 if (!BaseType->isDependentType() && !HasDependentArg) {
1104 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
1105 Context.getCanonicalType(BaseType));
Douglas Gregor39da0b82009-09-09 23:08:42 +00001106 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1107
1108 C = PerformInitializationByConstructor(BaseType,
1109 MultiExprArg(*this,
1110 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001111 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001112 Name, IK_Direct,
1113 ConstructorArgs);
1114 if (C) {
1115 // Take over the constructor arguments as our own.
1116 NumArgs = ConstructorArgs.size();
1117 Args = (Expr **)ConstructorArgs.take();
1118 }
Eli Friedman59c04372009-07-29 19:44:27 +00001119 }
1120
Mike Stump1eb44332009-09-09 15:08:12 +00001121 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001122 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001123}
1124
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001125void
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001126Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001127 CXXBaseOrMemberInitializer **Initializers,
1128 unsigned NumInitializers,
Mike Stump1eb44332009-09-09 15:08:12 +00001129 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001130 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
1131 // We need to build the initializer AST according to order of construction
1132 // and not what user specified in the Initializers list.
1133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1134 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1135 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1136 bool HasDependentBaseInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001138 for (unsigned i = 0; i < NumInitializers; i++) {
1139 CXXBaseOrMemberInitializer *Member = Initializers[i];
1140 if (Member->isBaseInitializer()) {
1141 if (Member->getBaseClass()->isDependentType())
1142 HasDependentBaseInit = true;
1143 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1144 } else {
1145 AllBaseFields[Member->getMember()] = Member;
1146 }
1147 }
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001149 if (HasDependentBaseInit) {
1150 // FIXME. This does not preserve the ordering of the initializers.
1151 // Try (with -Wreorder)
1152 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001153 // template<class X> struct B : A<X> {
1154 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001155 // int x1;
1156 // };
1157 // B<int> x;
1158 // On seeing one dependent type, we should essentially exit this routine
1159 // while preserving user-declared initializer list. When this routine is
1160 // called during instantiatiation process, this routine will rebuild the
1161 // oderdered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001163 // If we have a dependent base initialization, we can't determine the
1164 // association between initializers and bases; just dump the known
1165 // initializers into the list, and don't try to deal with other bases.
1166 for (unsigned i = 0; i < NumInitializers; i++) {
1167 CXXBaseOrMemberInitializer *Member = Initializers[i];
1168 if (Member->isBaseInitializer())
1169 AllToInit.push_back(Member);
1170 }
1171 } else {
1172 // Push virtual bases before others.
1173 for (CXXRecordDecl::base_class_iterator VBase =
1174 ClassDecl->vbases_begin(),
1175 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1176 if (VBase->getType()->isDependentType())
1177 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001178 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001179 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001180 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001181 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001182 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001183 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1184 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001185 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001186 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001187 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001188 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001189 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001190 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001191 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001192 if (!Ctor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001193 Bases.push_back(VBase);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001194 continue;
1195 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001196
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001197 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1198 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1199 Constructor->getLocation(), CtorArgs))
1200 continue;
1201
1202 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1203
Mike Stump1eb44332009-09-09 15:08:12 +00001204 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001205 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1206 CtorArgs.takeAs<Expr>(),
1207 CtorArgs.size(), Ctor,
1208 SourceLocation(),
1209 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001210 AllToInit.push_back(Member);
1211 }
1212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001214 for (CXXRecordDecl::base_class_iterator Base =
1215 ClassDecl->bases_begin(),
1216 E = ClassDecl->bases_end(); Base != E; ++Base) {
1217 // Virtuals are in the virtual base list and already constructed.
1218 if (Base->isVirtual())
1219 continue;
1220 // Skip dependent types.
1221 if (Base->getType()->isDependentType())
1222 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001223 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001224 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001225 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001226 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001227 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001228 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1229 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001230 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001231 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001232 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001233 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001234 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001235 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001236 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001237 if (!Ctor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001238 Bases.push_back(Base);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001239 continue;
1240 }
1241
1242 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1243 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1244 Constructor->getLocation(), CtorArgs))
1245 continue;
1246
1247 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001248
Mike Stump1eb44332009-09-09 15:08:12 +00001249 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001250 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1251 CtorArgs.takeAs<Expr>(),
1252 CtorArgs.size(), Ctor,
1253 SourceLocation(),
1254 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001255 AllToInit.push_back(Member);
1256 }
1257 }
1258 }
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001260 // non-static data members.
1261 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1262 E = ClassDecl->field_end(); Field != E; ++Field) {
1263 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001264 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001265 Field->getType()->getAs<RecordType>()) {
1266 CXXRecordDecl *FieldClassDecl
1267 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001268 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001269 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1270 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1271 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1272 // set to the anonymous union data member used in the initializer
1273 // list.
1274 Value->setMember(*Field);
1275 Value->setAnonUnionMember(*FA);
1276 AllToInit.push_back(Value);
1277 break;
1278 }
1279 }
1280 }
1281 continue;
1282 }
1283 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001284 QualType FT = (*Field)->getType();
1285 if (const RecordType* RT = FT->getAs<RecordType>()) {
1286 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001287 assert(FieldRecDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001288 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001289 FieldRecDecl->getDefaultConstructor(Context))
1290 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1291 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001292 AllToInit.push_back(Value);
1293 continue;
1294 }
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001296 QualType FT = Context.getBaseElementType((*Field)->getType());
1297 if (const RecordType* RT = FT->getAs<RecordType>()) {
1298 CXXConstructorDecl *Ctor =
1299 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001300 if (!Ctor && !FT->isDependentType()) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001301 Fields.push_back(*Field);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001302 continue;
1303 }
1304
1305 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1306 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1307 Constructor->getLocation(), CtorArgs))
1308 continue;
1309
Mike Stump1eb44332009-09-09 15:08:12 +00001310 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001311 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1312 CtorArgs.size(), Ctor,
1313 SourceLocation(),
1314 SourceLocation());
1315
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001316 AllToInit.push_back(Member);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001317 if (Ctor)
1318 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001319 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1320 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1321 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1322 Diag((*Field)->getLocation(), diag::note_declared_at);
1323 }
1324 }
1325 else if (FT->isReferenceType()) {
1326 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1327 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1328 Diag((*Field)->getLocation(), diag::note_declared_at);
1329 }
1330 else if (FT.isConstQualified()) {
1331 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1332 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1333 Diag((*Field)->getLocation(), diag::note_declared_at);
1334 }
1335 }
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001337 NumInitializers = AllToInit.size();
1338 if (NumInitializers > 0) {
1339 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1340 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1341 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001343 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1344 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1345 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1346 }
1347}
1348
1349void
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001350Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1351 CXXConstructorDecl *Constructor,
1352 CXXBaseOrMemberInitializer **Initializers,
1353 unsigned NumInitializers
1354 ) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001355 llvm::SmallVector<CXXBaseSpecifier *, 4> Bases;
1356 llvm::SmallVector<FieldDecl *, 4> Members;
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001358 SetBaseOrMemberInitializers(Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001359 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001360 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001361 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001362 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1363 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001364 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001365 << 1 << Members[i]->getType();
1366}
1367
Eli Friedman6347f422009-07-21 19:28:10 +00001368static void *GetKeyForTopLevelField(FieldDecl *Field) {
1369 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001370 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001371 if (RT->getDecl()->isAnonymousStructOrUnion())
1372 return static_cast<void *>(RT->getDecl());
1373 }
1374 return static_cast<void *>(Field);
1375}
1376
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001377static void *GetKeyForBase(QualType BaseType) {
1378 if (const RecordType *RT = BaseType->getAs<RecordType>())
1379 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001381 assert(0 && "Unexpected base type!");
1382 return 0;
1383}
1384
Mike Stump1eb44332009-09-09 15:08:12 +00001385static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001386 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001387 // For fields injected into the class via declaration of an anonymous union,
1388 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001389 if (Member->isMemberInitializer()) {
1390 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001392 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001393 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001394 // in AnonUnionMember field.
1395 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1396 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001397 if (Field->getDeclContext()->isRecord()) {
1398 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1399 if (RD->isAnonymousStructOrUnion())
1400 return static_cast<void *>(RD);
1401 }
1402 return static_cast<void *>(Field);
1403 }
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001405 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001406}
1407
Mike Stump1eb44332009-09-09 15:08:12 +00001408void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001409 SourceLocation ColonLoc,
1410 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001411 if (!ConstructorDecl)
1412 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001413
1414 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001415
1416 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001417 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Anders Carlssona7b35212009-03-25 02:58:17 +00001419 if (!Constructor) {
1420 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1421 return;
1422 }
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001424 if (!Constructor->isDependentContext()) {
1425 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1426 bool err = false;
1427 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001428 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001429 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1430 void *KeyToMember = GetKeyForMember(Member);
1431 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1432 if (!PrevMember) {
1433 PrevMember = Member;
1434 continue;
1435 }
1436 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001437 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001438 diag::error_multiple_mem_initialization)
1439 << Field->getNameAsString();
1440 else {
1441 Type *BaseClass = Member->getBaseClass();
1442 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001443 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001444 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001445 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001446 }
1447 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1448 << 0;
1449 err = true;
1450 }
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001452 if (err)
1453 return;
1454 }
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001456 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001457 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001458 NumMemInits);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001460 if (Constructor->isDependentContext())
1461 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001462
1463 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001464 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001465 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001466 Diagnostic::Ignored)
1467 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001469 // Also issue warning if order of ctor-initializer list does not match order
1470 // of 1) base class declarations and 2) order of non-static data members.
1471 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001473 CXXRecordDecl *ClassDecl
1474 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1475 // Push virtual bases before others.
1476 for (CXXRecordDecl::base_class_iterator VBase =
1477 ClassDecl->vbases_begin(),
1478 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001479 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001481 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1482 E = ClassDecl->bases_end(); Base != E; ++Base) {
1483 // Virtuals are alread in the virtual base list and are constructed
1484 // first.
1485 if (Base->isVirtual())
1486 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001487 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001488 }
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001490 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1491 E = ClassDecl->field_end(); Field != E; ++Field)
1492 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001494 int Last = AllBaseOrMembers.size();
1495 int curIndex = 0;
1496 CXXBaseOrMemberInitializer *PrevMember = 0;
1497 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001498 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001499 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1500 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001501
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001502 for (; curIndex < Last; curIndex++)
1503 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1504 break;
1505 if (curIndex == Last) {
1506 assert(PrevMember && "Member not in member list?!");
1507 // Initializer as specified in ctor-initializer list is out of order.
1508 // Issue a warning diagnostic.
1509 if (PrevMember->isBaseInitializer()) {
1510 // Diagnostics is for an initialized base class.
1511 Type *BaseClass = PrevMember->getBaseClass();
1512 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001513 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001514 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001515 } else {
1516 FieldDecl *Field = PrevMember->getMember();
1517 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001518 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001519 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001520 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001521 // Also the note!
1522 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001523 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001524 diag::note_fieldorbase_initialized_here) << 0
1525 << Field->getNameAsString();
1526 else {
1527 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001528 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001529 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001530 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001531 }
1532 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001533 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001534 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001535 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001536 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001537 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001538}
1539
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001540void
1541Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1542 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1543 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001545 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1546 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1547 if (VBase->getType()->isDependentType())
1548 continue;
1549 // Skip over virtual bases which have trivial destructors.
1550 CXXRecordDecl *BaseClassDecl
1551 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1552 if (BaseClassDecl->hasTrivialDestructor())
1553 continue;
1554 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001555 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001556 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001557
1558 uintptr_t Member =
1559 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001560 | CXXDestructorDecl::VBASE;
1561 AllToDestruct.push_back(Member);
1562 }
1563 for (CXXRecordDecl::base_class_iterator Base =
1564 ClassDecl->bases_begin(),
1565 E = ClassDecl->bases_end(); Base != E; ++Base) {
1566 if (Base->isVirtual())
1567 continue;
1568 if (Base->getType()->isDependentType())
1569 continue;
1570 // Skip over virtual bases which have trivial destructors.
1571 CXXRecordDecl *BaseClassDecl
1572 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1573 if (BaseClassDecl->hasTrivialDestructor())
1574 continue;
1575 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001576 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001577 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001578 uintptr_t Member =
1579 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001580 | CXXDestructorDecl::DRCTNONVBASE;
1581 AllToDestruct.push_back(Member);
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001584 // non-static data members.
1585 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1586 E = ClassDecl->field_end(); Field != E; ++Field) {
1587 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001589 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1590 // Skip over virtual bases which have trivial destructors.
1591 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1592 if (FieldClassDecl->hasTrivialDestructor())
1593 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001594 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001595 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001596 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001597 const_cast<CXXDestructorDecl*>(Dtor));
1598 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1599 AllToDestruct.push_back(Member);
1600 }
1601 }
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001603 unsigned NumDestructions = AllToDestruct.size();
1604 if (NumDestructions > 0) {
1605 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001606 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001607 new (Context) uintptr_t [NumDestructions];
1608 // Insert in reverse order.
1609 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1610 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1611 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1612 }
1613}
1614
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001615void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001616 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001617 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001619 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001620
1621 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001622 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001623 BuildBaseOrMemberInitializers(Context,
1624 Constructor,
1625 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001626}
1627
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001628namespace {
1629 /// PureVirtualMethodCollector - traverses a class and its superclasses
1630 /// and determines if it has any pure virtual methods.
1631 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1632 ASTContext &Context;
1633
Sebastian Redldfe292d2009-03-22 21:28:55 +00001634 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001635 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001636
1637 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001638 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001640 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001642 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001643 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001644 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001646 MethodList List;
1647 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001649 // Copy the temporary list to methods, and make sure to ignore any
1650 // null entries.
1651 for (size_t i = 0, e = List.size(); i != e; ++i) {
1652 if (List[i])
1653 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001654 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001655 }
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001657 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001659 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1660 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001661 };
Mike Stump1eb44332009-09-09 15:08:12 +00001662
1663 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001664 MethodList& Methods) {
1665 // First, collect the pure virtual methods for the base classes.
1666 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1667 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001668 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001669 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001670 if (BaseDecl && BaseDecl->isAbstract())
1671 Collect(BaseDecl, Methods);
1672 }
1673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001675 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001676 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001678 MethodSetTy OverriddenMethods;
1679 size_t MethodsSize = Methods.size();
1680
Mike Stump1eb44332009-09-09 15:08:12 +00001681 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001682 i != e; ++i) {
1683 // Traverse the record, looking for methods.
1684 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001685 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001686 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001687 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Anders Carlsson27823022009-10-18 19:34:08 +00001689 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001690 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1691 E = MD->end_overridden_methods(); I != E; ++I) {
1692 // Keep track of the overridden methods.
1693 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001694 }
1695 }
1696 }
Mike Stump1eb44332009-09-09 15:08:12 +00001697
1698 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001699 // overridden.
1700 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1701 if (OverriddenMethods.count(Methods[i]))
1702 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001703 }
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001705 }
1706}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001707
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001708
Mike Stump1eb44332009-09-09 15:08:12 +00001709bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001710 unsigned DiagID, AbstractDiagSelID SelID,
1711 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001712 if (SelID == -1)
1713 return RequireNonAbstractType(Loc, T,
1714 PDiag(DiagID), CurrentRD);
1715 else
1716 return RequireNonAbstractType(Loc, T,
1717 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001718}
1719
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001720bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1721 const PartialDiagnostic &PD,
1722 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001723 if (!getLangOptions().CPlusPlus)
1724 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Anders Carlsson11f21a02009-03-23 19:10:31 +00001726 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001727 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001728 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Ted Kremenek6217b802009-07-29 21:53:49 +00001730 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001731 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001732 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001733 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001735 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001736 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001737 }
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Ted Kremenek6217b802009-07-29 21:53:49 +00001739 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001740 if (!RT)
1741 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001743 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1744 if (!RD)
1745 return false;
1746
Anders Carlssone65a3c82009-03-24 17:23:42 +00001747 if (CurrentRD && CurrentRD != RD)
1748 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001750 if (!RD->isAbstract())
1751 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001753 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001755 // Check if we've already emitted the list of pure virtual functions for this
1756 // class.
1757 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1758 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001760 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
1762 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001763 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1764 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001765
1766 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001767 MD->getDeclName();
1768 }
1769
1770 if (!PureVirtualClassDiagSet)
1771 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1772 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001774 return true;
1775}
1776
Anders Carlsson8211eff2009-03-24 01:19:16 +00001777namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001778 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001779 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1780 Sema &SemaRef;
1781 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Anders Carlssone65a3c82009-03-24 17:23:42 +00001783 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001784 bool Invalid = false;
1785
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001786 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1787 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001788 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001789
Anders Carlsson8211eff2009-03-24 01:19:16 +00001790 return Invalid;
1791 }
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Anders Carlssone65a3c82009-03-24 17:23:42 +00001793 public:
1794 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1795 : SemaRef(SemaRef), AbstractClass(ac) {
1796 Visit(SemaRef.Context.getTranslationUnitDecl());
1797 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001798
Anders Carlssone65a3c82009-03-24 17:23:42 +00001799 bool VisitFunctionDecl(const FunctionDecl *FD) {
1800 if (FD->isThisDeclarationADefinition()) {
1801 // No need to do the check if we're in a definition, because it requires
1802 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001803 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001804 return VisitDeclContext(FD);
1805 }
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Anders Carlssone65a3c82009-03-24 17:23:42 +00001807 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001808 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001809 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001810 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1811 diag::err_abstract_type_in_decl,
1812 Sema::AbstractReturnType,
1813 AbstractClass);
1814
Mike Stump1eb44332009-09-09 15:08:12 +00001815 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001816 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001817 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001818 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001819 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001820 VD->getOriginalType(),
1821 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001822 Sema::AbstractParamType,
1823 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001824 }
1825
1826 return Invalid;
1827 }
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlssone65a3c82009-03-24 17:23:42 +00001829 bool VisitDecl(const Decl* D) {
1830 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1831 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Anders Carlssone65a3c82009-03-24 17:23:42 +00001833 return false;
1834 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001835 };
1836}
1837
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001839 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001840 SourceLocation LBrac,
1841 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001842 if (!TagDecl)
1843 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregor42af25f2009-05-11 19:58:34 +00001845 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001847 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001848 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001849
Chris Lattnerb28317a2009-03-28 19:18:32 +00001850 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001851 if (!RD->isAbstract()) {
1852 // Collect all the pure virtual methods and see if this is an abstract
1853 // class after all.
1854 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001855 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001856 RD->setAbstract(true);
1857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858
1859 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001860 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Douglas Gregor663b5a02009-10-14 20:14:33 +00001862 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001863 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001864}
1865
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001866/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1867/// special functions, such as the default constructor, copy
1868/// constructor, or destructor, to the given C++ class (C++
1869/// [special]p1). This routine can only be executed just before the
1870/// definition of the class is complete.
1871void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001872 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001873 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001874
Sebastian Redl465226e2009-05-27 22:11:52 +00001875 // FIXME: Implicit declarations have exception specifications, which are
1876 // the union of the specifications of the implicitly called functions.
1877
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001878 if (!ClassDecl->hasUserDeclaredConstructor()) {
1879 // C++ [class.ctor]p5:
1880 // A default constructor for a class X is a constructor of class X
1881 // that can be called without an argument. If there is no
1882 // user-declared constructor for class X, a default constructor is
1883 // implicitly declared. An implicitly-declared default constructor
1884 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001885 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001886 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001887 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001888 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001889 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001890 Context.getFunctionType(Context.VoidTy,
1891 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001892 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001893 /*isExplicit=*/false,
1894 /*isInline=*/true,
1895 /*isImplicitlyDeclared=*/true);
1896 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001897 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001898 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001899 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001900 }
1901
1902 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1903 // C++ [class.copy]p4:
1904 // If the class definition does not explicitly declare a copy
1905 // constructor, one is declared implicitly.
1906
1907 // C++ [class.copy]p5:
1908 // The implicitly-declared copy constructor for a class X will
1909 // have the form
1910 //
1911 // X::X(const X&)
1912 //
1913 // if
1914 bool HasConstCopyConstructor = true;
1915
1916 // -- each direct or virtual base class B of X has a copy
1917 // constructor whose first parameter is of type const B& or
1918 // const volatile B&, and
1919 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1920 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1921 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001922 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001923 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001924 = BaseClassDecl->hasConstCopyConstructor(Context);
1925 }
1926
1927 // -- for all the nonstatic data members of X that are of a
1928 // class type M (or array thereof), each such class type
1929 // has a copy constructor whose first parameter is of type
1930 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001931 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1932 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001933 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001934 QualType FieldType = (*Field)->getType();
1935 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1936 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001937 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001938 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001939 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001940 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001941 = FieldClassDecl->hasConstCopyConstructor(Context);
1942 }
1943 }
1944
Sebastian Redl64b45f72009-01-05 20:52:13 +00001945 // Otherwise, the implicitly declared copy constructor will have
1946 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001947 //
1948 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001949 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001950 if (HasConstCopyConstructor)
1951 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001952 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001953
Sebastian Redl64b45f72009-01-05 20:52:13 +00001954 // An implicitly-declared copy constructor is an inline public
1955 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001956 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001957 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001958 CXXConstructorDecl *CopyConstructor
1959 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001960 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001961 Context.getFunctionType(Context.VoidTy,
1962 &ArgType, 1,
1963 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001964 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001965 /*isExplicit=*/false,
1966 /*isInline=*/true,
1967 /*isImplicitlyDeclared=*/true);
1968 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001969 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001970 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001971
1972 // Add the parameter to the constructor.
1973 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1974 ClassDecl->getLocation(),
1975 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001976 ArgType, /*DInfo=*/0,
1977 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001978 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001979 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001980 }
1981
Sebastian Redl64b45f72009-01-05 20:52:13 +00001982 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1983 // Note: The following rules are largely analoguous to the copy
1984 // constructor rules. Note that virtual bases are not taken into account
1985 // for determining the argument type of the operator. Note also that
1986 // operators taking an object instead of a reference are allowed.
1987 //
1988 // C++ [class.copy]p10:
1989 // If the class definition does not explicitly declare a copy
1990 // assignment operator, one is declared implicitly.
1991 // The implicitly-defined copy assignment operator for a class X
1992 // will have the form
1993 //
1994 // X& X::operator=(const X&)
1995 //
1996 // if
1997 bool HasConstCopyAssignment = true;
1998
1999 // -- each direct base class B of X has a copy assignment operator
2000 // whose parameter is of type const B&, const volatile B& or B,
2001 // and
2002 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2003 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002004 assert(!Base->getType()->isDependentType() &&
2005 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002006 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002007 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002008 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002009 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002010 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002011 }
2012
2013 // -- for all the nonstatic data members of X that are of a class
2014 // type M (or array thereof), each such class type has a copy
2015 // assignment operator whose parameter is of type const M&,
2016 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002017 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2018 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002019 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002020 QualType FieldType = (*Field)->getType();
2021 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2022 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002023 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002024 const CXXRecordDecl *FieldClassDecl
2025 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002026 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002027 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002028 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002029 }
2030 }
2031
2032 // Otherwise, the implicitly declared copy assignment operator will
2033 // have the form
2034 //
2035 // X& X::operator=(X&)
2036 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002037 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002038 if (HasConstCopyAssignment)
2039 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002040 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002041
2042 // An implicitly-declared copy assignment operator is an inline public
2043 // member of its class.
2044 DeclarationName Name =
2045 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2046 CXXMethodDecl *CopyAssignment =
2047 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2048 Context.getFunctionType(RetType, &ArgType, 1,
2049 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002050 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002051 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002052 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002053 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002054 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002055
2056 // Add the parameter to the operator.
2057 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2058 ClassDecl->getLocation(),
2059 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002060 ArgType, /*DInfo=*/0,
2061 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002062 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002063
2064 // Don't call addedAssignmentOperator. There is no way to distinguish an
2065 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002066 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002067 }
2068
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002069 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002070 // C++ [class.dtor]p2:
2071 // If a class has no user-declared destructor, a destructor is
2072 // declared implicitly. An implicitly-declared destructor is an
2073 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002074 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002075 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002076 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002077 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002078 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002079 Context.getFunctionType(Context.VoidTy,
2080 0, 0, false, 0),
2081 /*isInline=*/true,
2082 /*isImplicitlyDeclared=*/true);
2083 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002084 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002085 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002086 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002087 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002088}
2089
Douglas Gregor6569d682009-05-27 23:11:45 +00002090void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002091 Decl *D = TemplateD.getAs<Decl>();
2092 if (!D)
2093 return;
2094
2095 TemplateParameterList *Params = 0;
2096 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2097 Params = Template->getTemplateParameters();
2098 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2099 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2100 Params = PartialSpec->getTemplateParameters();
2101 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002102 return;
2103
Douglas Gregor6569d682009-05-27 23:11:45 +00002104 for (TemplateParameterList::iterator Param = Params->begin(),
2105 ParamEnd = Params->end();
2106 Param != ParamEnd; ++Param) {
2107 NamedDecl *Named = cast<NamedDecl>(*Param);
2108 if (Named->getDeclName()) {
2109 S->AddDecl(DeclPtrTy::make(Named));
2110 IdResolver.AddDecl(Named);
2111 }
2112 }
2113}
2114
Douglas Gregor72b505b2008-12-16 21:30:33 +00002115/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2116/// parsing a top-level (non-nested) C++ class, and we are now
2117/// parsing those parts of the given Method declaration that could
2118/// not be parsed earlier (C++ [class.mem]p2), such as default
2119/// arguments. This action should enter the scope of the given
2120/// Method declaration as if we had just parsed the qualified method
2121/// name. However, it should not bring the parameters into scope;
2122/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002123void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002124 if (!MethodD)
2125 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002127 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Douglas Gregor72b505b2008-12-16 21:30:33 +00002129 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002130 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002131 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002132 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2133 SS.setScopeRep(
2134 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002135 ActOnCXXEnterDeclaratorScope(S, SS);
2136}
2137
2138/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2139/// C++ method declaration. We're (re-)introducing the given
2140/// function parameter into scope for use in parsing later parts of
2141/// the method declaration. For example, we could see an
2142/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002143void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002144 if (!ParamD)
2145 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Chris Lattnerb28317a2009-03-28 19:18:32 +00002147 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002148
2149 // If this parameter has an unparsed default argument, clear it out
2150 // to make way for the parsed default argument.
2151 if (Param->hasUnparsedDefaultArg())
2152 Param->setDefaultArg(0);
2153
Chris Lattnerb28317a2009-03-28 19:18:32 +00002154 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002155 if (Param->getDeclName())
2156 IdResolver.AddDecl(Param);
2157}
2158
2159/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2160/// processing the delayed method declaration for Method. The method
2161/// declaration is now considered finished. There may be a separate
2162/// ActOnStartOfFunctionDef action later (not necessarily
2163/// immediately!) for this method, if it was also defined inside the
2164/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002165void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002166 if (!MethodD)
2167 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002169 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Chris Lattnerb28317a2009-03-28 19:18:32 +00002171 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002172 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002173 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002174 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2175 SS.setScopeRep(
2176 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002177 ActOnCXXExitDeclaratorScope(S, SS);
2178
2179 // Now that we have our default arguments, check the constructor
2180 // again. It could produce additional diagnostics or affect whether
2181 // the class has implicitly-declared destructors, among other
2182 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002183 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2184 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002185
2186 // Check the default arguments, which we may have added.
2187 if (!Method->isInvalidDecl())
2188 CheckCXXDefaultArguments(Method);
2189}
2190
Douglas Gregor42a552f2008-11-05 20:51:48 +00002191/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002192/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002193/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002194/// emit diagnostics and set the invalid bit to true. In any case, the type
2195/// will be updated to reflect a well-formed type for the constructor and
2196/// returned.
2197QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2198 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002199 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002200
2201 // C++ [class.ctor]p3:
2202 // A constructor shall not be virtual (10.3) or static (9.4). A
2203 // constructor can be invoked for a const, volatile or const
2204 // volatile object. A constructor shall not be declared const,
2205 // volatile, or const volatile (9.3.2).
2206 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002207 if (!D.isInvalidType())
2208 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2209 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2210 << SourceRange(D.getIdentifierLoc());
2211 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002212 }
2213 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002214 if (!D.isInvalidType())
2215 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2216 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2217 << SourceRange(D.getIdentifierLoc());
2218 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002219 SC = FunctionDecl::None;
2220 }
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Chris Lattner65401802009-04-25 08:28:21 +00002222 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2223 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002224 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002225 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2226 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002227 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002228 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2229 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002230 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002231 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2232 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002233 }
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Douglas Gregor42a552f2008-11-05 20:51:48 +00002235 // Rebuild the function type "R" without any type qualifiers (in
2236 // case any of the errors above fired) and with "void" as the
2237 // return type, since constructors don't have return types. We
2238 // *always* have to do this, because GetTypeForDeclarator will
2239 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002240 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002241 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2242 Proto->getNumArgs(),
2243 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002244}
2245
Douglas Gregor72b505b2008-12-16 21:30:33 +00002246/// CheckConstructor - Checks a fully-formed constructor for
2247/// well-formedness, issuing any diagnostics required. Returns true if
2248/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002249void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002250 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002251 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2252 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002253 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002254
2255 // C++ [class.copy]p3:
2256 // A declaration of a constructor for a class X is ill-formed if
2257 // its first parameter is of type (optionally cv-qualified) X and
2258 // either there are no other parameters or else all other
2259 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002260 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002261 ((Constructor->getNumParams() == 1) ||
2262 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002263 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002264 QualType ParamType = Constructor->getParamDecl(0)->getType();
2265 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2266 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002267 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2268 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002269 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002270 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002271 }
2272 }
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Douglas Gregor72b505b2008-12-16 21:30:33 +00002274 // Notify the class that we've added a constructor.
2275 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002276}
2277
Mike Stump1eb44332009-09-09 15:08:12 +00002278static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002279FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2280 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2281 FTI.ArgInfo[0].Param &&
2282 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2283}
2284
Douglas Gregor42a552f2008-11-05 20:51:48 +00002285/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2286/// the well-formednes of the destructor declarator @p D with type @p
2287/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002288/// emit diagnostics and set the declarator to invalid. Even if this happens,
2289/// will be updated to reflect a well-formed type for the destructor and
2290/// returned.
2291QualType Sema::CheckDestructorDeclarator(Declarator &D,
2292 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002293 // C++ [class.dtor]p1:
2294 // [...] A typedef-name that names a class is a class-name
2295 // (7.1.3); however, a typedef-name that names a class shall not
2296 // be used as the identifier in the declarator for a destructor
2297 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002298 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00002299 if (isa<TypedefType>(DeclaratorType)) {
2300 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002301 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002302 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002303 }
2304
2305 // C++ [class.dtor]p2:
2306 // A destructor is used to destroy objects of its class type. A
2307 // destructor takes no parameters, and no return type can be
2308 // specified for it (not even void). The address of a destructor
2309 // shall not be taken. A destructor shall not be static. A
2310 // destructor can be invoked for a const, volatile or const
2311 // volatile object. A destructor shall not be declared const,
2312 // volatile or const volatile (9.3.2).
2313 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002314 if (!D.isInvalidType())
2315 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2316 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2317 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002318 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002319 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002320 }
Chris Lattner65401802009-04-25 08:28:21 +00002321 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002322 // Destructors don't have return types, but the parser will
2323 // happily parse something like:
2324 //
2325 // class X {
2326 // float ~X();
2327 // };
2328 //
2329 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002330 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2331 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2332 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Chris Lattner65401802009-04-25 08:28:21 +00002335 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2336 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002337 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002338 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2339 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002340 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002341 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2342 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002343 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002344 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2345 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002346 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002347 }
2348
2349 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002350 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002351 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2352
2353 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002354 FTI.freeArgs();
2355 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002356 }
2357
Mike Stump1eb44332009-09-09 15:08:12 +00002358 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002359 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002360 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002361 D.setInvalidType();
2362 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002363
2364 // Rebuild the function type "R" without any type qualifiers or
2365 // parameters (in case any of the errors above fired) and with
2366 // "void" as the return type, since destructors don't have return
2367 // types. We *always* have to do this, because GetTypeForDeclarator
2368 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002369 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002370}
2371
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002372/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2373/// well-formednes of the conversion function declarator @p D with
2374/// type @p R. If there are any errors in the declarator, this routine
2375/// will emit diagnostics and return true. Otherwise, it will return
2376/// false. Either way, the type @p R will be updated to reflect a
2377/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002378void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002379 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002380 // C++ [class.conv.fct]p1:
2381 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002382 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002383 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002384 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002385 if (!D.isInvalidType())
2386 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2387 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2388 << SourceRange(D.getIdentifierLoc());
2389 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002390 SC = FunctionDecl::None;
2391 }
Chris Lattner6e475012009-04-25 08:35:12 +00002392 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002393 // Conversion functions don't have return types, but the parser will
2394 // happily parse something like:
2395 //
2396 // class X {
2397 // float operator bool();
2398 // };
2399 //
2400 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002401 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2402 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2403 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002404 }
2405
2406 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002407 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002408 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2409
2410 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002411 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002412 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002413 }
2414
Mike Stump1eb44332009-09-09 15:08:12 +00002415 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002416 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002417 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002418 D.setInvalidType();
2419 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002420
2421 // C++ [class.conv.fct]p4:
2422 // The conversion-type-id shall not represent a function type nor
2423 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002424 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002425 if (ConvType->isArrayType()) {
2426 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2427 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002428 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002429 } else if (ConvType->isFunctionType()) {
2430 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2431 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002432 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002433 }
2434
2435 // Rebuild the function type "R" without any parameters (in case any
2436 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002437 // return type.
2438 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002439 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002440
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002441 // C++0x explicit conversion operators.
2442 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002443 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002444 diag::warn_explicit_conversion_functions)
2445 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002446}
2447
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002448/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2449/// the declaration of the given C++ conversion function. This routine
2450/// is responsible for recording the conversion function in the C++
2451/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002452Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002453 assert(Conversion && "Expected to receive a conversion function declaration");
2454
Douglas Gregor9d350972008-12-12 08:25:50 +00002455 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002456
2457 // Make sure we aren't redeclaring the conversion function.
2458 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002459
2460 // C++ [class.conv.fct]p1:
2461 // [...] A conversion function is never used to convert a
2462 // (possibly cv-qualified) object to the (possibly cv-qualified)
2463 // same object type (or a reference to it), to a (possibly
2464 // cv-qualified) base class of that type (or a reference to it),
2465 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002466 // FIXME: Suppress this warning if the conversion function ends up being a
2467 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002468 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002469 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002470 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002471 ConvType = ConvTypeRef->getPointeeType();
2472 if (ConvType->isRecordType()) {
2473 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2474 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002475 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002476 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002477 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002478 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002479 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002480 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002481 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002482 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002483 }
2484
Douglas Gregor70316a02008-12-26 15:00:45 +00002485 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002486 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002487 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002488 = Conversion->getDescribedFunctionTemplate())
2489 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002490 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002491 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002492 Conv = Conversions->function_begin(),
2493 ConvEnd = Conversions->function_end();
2494 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002495 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002496 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002497 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002498 }
2499 }
2500 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002501 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002502 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002503 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002504 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002505 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002506
Chris Lattnerb28317a2009-03-28 19:18:32 +00002507 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002508}
2509
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002510//===----------------------------------------------------------------------===//
2511// Namespace Handling
2512//===----------------------------------------------------------------------===//
2513
2514/// ActOnStartNamespaceDef - This is called at the start of a namespace
2515/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002516Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2517 SourceLocation IdentLoc,
2518 IdentifierInfo *II,
2519 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002520 NamespaceDecl *Namespc =
2521 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2522 Namespc->setLBracLoc(LBrace);
2523
2524 Scope *DeclRegionScope = NamespcScope->getParent();
2525
2526 if (II) {
2527 // C++ [namespace.def]p2:
2528 // The identifier in an original-namespace-definition shall not have been
2529 // previously defined in the declarative region in which the
2530 // original-namespace-definition appears. The identifier in an
2531 // original-namespace-definition is the name of the namespace. Subsequently
2532 // in that declarative region, it is treated as an original-namespace-name.
2533
John McCallf36e02d2009-10-09 21:13:30 +00002534 NamedDecl *PrevDecl
2535 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Douglas Gregor44b43212008-12-11 16:49:14 +00002537 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2538 // This is an extended namespace definition.
2539 // Attach this namespace decl to the chain of extended namespace
2540 // definitions.
2541 OrigNS->setNextNamespace(Namespc);
2542 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002543
Mike Stump1eb44332009-09-09 15:08:12 +00002544 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002545 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002546 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002547 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002548 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002549 } else if (PrevDecl) {
2550 // This is an invalid name redefinition.
2551 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2552 << Namespc->getDeclName();
2553 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2554 Namespc->setInvalidDecl();
2555 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002556 } else if (II->isStr("std") &&
2557 CurContext->getLookupContext()->isTranslationUnit()) {
2558 // This is the first "real" definition of the namespace "std", so update
2559 // our cache of the "std" namespace to point at this definition.
2560 if (StdNamespace) {
2561 // We had already defined a dummy namespace "std". Link this new
2562 // namespace definition to the dummy namespace "std".
2563 StdNamespace->setNextNamespace(Namespc);
2564 StdNamespace->setLocation(IdentLoc);
2565 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2566 }
2567
2568 // Make our StdNamespace cache point at the first real definition of the
2569 // "std" namespace.
2570 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002571 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002572
2573 PushOnScopeChains(Namespc, DeclRegionScope);
2574 } else {
John McCall9aeed322009-10-01 00:25:31 +00002575 // Anonymous namespaces.
2576
2577 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2578 // behaves as if it were replaced by
2579 // namespace unique { /* empty body */ }
2580 // using namespace unique;
2581 // namespace unique { namespace-body }
2582 // where all occurrences of 'unique' in a translation unit are
2583 // replaced by the same identifier and this identifier differs
2584 // from all other identifiers in the entire program.
2585
2586 // We just create the namespace with an empty name and then add an
2587 // implicit using declaration, just like the standard suggests.
2588 //
2589 // CodeGen enforces the "universally unique" aspect by giving all
2590 // declarations semantically contained within an anonymous
2591 // namespace internal linkage.
2592
2593 assert(Namespc->isAnonymousNamespace());
2594 CurContext->addDecl(Namespc);
2595
2596 UsingDirectiveDecl* UD
2597 = UsingDirectiveDecl::Create(Context, CurContext,
2598 /* 'using' */ LBrace,
2599 /* 'namespace' */ SourceLocation(),
2600 /* qualifier */ SourceRange(),
2601 /* NNS */ NULL,
2602 /* identifier */ SourceLocation(),
2603 Namespc,
2604 /* Ancestor */ CurContext);
2605 UD->setImplicit();
2606 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002607 }
2608
2609 // Although we could have an invalid decl (i.e. the namespace name is a
2610 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002611 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2612 // for the namespace has the declarations that showed up in that particular
2613 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002614 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002615 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002616}
2617
2618/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2619/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002620void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2621 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002622 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2623 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2624 Namespc->setRBracLoc(RBrace);
2625 PopDeclContext();
2626}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002627
Chris Lattnerb28317a2009-03-28 19:18:32 +00002628Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2629 SourceLocation UsingLoc,
2630 SourceLocation NamespcLoc,
2631 const CXXScopeSpec &SS,
2632 SourceLocation IdentLoc,
2633 IdentifierInfo *NamespcName,
2634 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002635 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2636 assert(NamespcName && "Invalid NamespcName.");
2637 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002638 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002639
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002640 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002641
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002642 // Lookup namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002643 LookupResult R;
2644 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002645 if (R.isAmbiguous()) {
2646 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002647 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002648 }
John McCallf36e02d2009-10-09 21:13:30 +00002649 if (!R.empty()) {
2650 NamedDecl *NS = R.getFoundDecl();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002651 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002652 // C++ [namespace.udir]p1:
2653 // A using-directive specifies that the names in the nominated
2654 // namespace can be used in the scope in which the
2655 // using-directive appears after the using-directive. During
2656 // unqualified name lookup (3.4.1), the names appear as if they
2657 // were declared in the nearest enclosing namespace which
2658 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002659 // namespace. [Note: in this context, "contains" means "contains
2660 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002661
2662 // Find enclosing context containing both using-directive and
2663 // nominated namespace.
2664 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2665 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2666 CommonAncestor = CommonAncestor->getParent();
2667
Mike Stump1eb44332009-09-09 15:08:12 +00002668 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002669 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002670 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002671 SS.getRange(),
2672 (NestedNameSpecifier *)SS.getScopeRep(),
2673 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002674 cast<NamespaceDecl>(NS),
2675 CommonAncestor);
2676 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002677 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002678 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002679 }
2680
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002681 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002682 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002683 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002684}
2685
2686void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2687 // If scope has associated entity, then using directive is at namespace
2688 // or translation unit scope. We add UsingDirectiveDecls, into
2689 // it's lookup structure.
2690 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002691 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002692 else
2693 // Otherwise it is block-sope. using-directives will affect lookup
2694 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002695 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002696}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002697
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002698
2699Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002700 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002701 SourceLocation UsingLoc,
2702 const CXXScopeSpec &SS,
2703 SourceLocation IdentLoc,
2704 IdentifierInfo *TargetName,
2705 OverloadedOperatorKind Op,
2706 AttributeList *AttrList,
2707 bool IsTypeName) {
Eli Friedman5d39dee2009-06-27 05:59:59 +00002708 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002709 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002711 DeclarationName Name;
2712 if (TargetName)
2713 Name = TargetName;
2714 else
2715 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump1eb44332009-09-09 15:08:12 +00002716
2717 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002718 Name, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002719 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002720 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002721 UD->setAccess(AS);
2722 }
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Anders Carlssonc72160b2009-08-28 05:40:36 +00002724 return DeclPtrTy::make(UD);
2725}
2726
2727NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2728 const CXXScopeSpec &SS,
2729 SourceLocation IdentLoc,
2730 DeclarationName Name,
2731 AttributeList *AttrList,
2732 bool IsTypeName) {
2733 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2734 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002735
Anders Carlsson550b14b2009-08-28 05:49:21 +00002736 // FIXME: We ignore attributes for now.
2737 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002739 if (SS.isEmpty()) {
2740 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002741 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002742 }
Mike Stump1eb44332009-09-09 15:08:12 +00002743
2744 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002745 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2746
Anders Carlsson550b14b2009-08-28 05:49:21 +00002747 if (isUnknownSpecialization(SS)) {
2748 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2749 SS.getRange(), NNS,
2750 IdentLoc, Name, IsTypeName);
2751 }
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002753 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002755 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2756 // C++0x N2914 [namespace.udecl]p3:
2757 // A using-declaration used as a member-declaration shall refer to a member
2758 // of a base class of the class being defined, shall refer to a member of an
2759 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002760 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002761 // a member of a base class of the class being defined.
2762 const Type *Ty = NNS->getAsType();
2763 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2764 Diag(SS.getRange().getBegin(),
2765 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2766 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002767 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002768 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002769
2770 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2771 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002772 } else {
2773 // C++0x N2914 [namespace.udecl]p8:
2774 // A using-declaration for a class member shall be a member-declaration.
2775 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002776 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002777 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002778 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002779 }
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002781 // C++0x N2914 [namespace.udecl]p9:
2782 // In a using-declaration, a prefix :: refers to the global namespace.
2783 if (NNS->getKind() == NestedNameSpecifier::Global)
2784 LookupContext = Context.getTranslationUnitDecl();
2785 else
2786 LookupContext = NNS->getAsNamespace();
2787 }
2788
2789
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002790 // Lookup target name.
John McCallf36e02d2009-10-09 21:13:30 +00002791 LookupResult R;
2792 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002793
John McCallf36e02d2009-10-09 21:13:30 +00002794 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002795 Diag(IdentLoc, diag::err_no_member)
2796 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002797 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002798 }
2799
John McCallf36e02d2009-10-09 21:13:30 +00002800 // FIXME: handle ambiguity?
2801 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002803 if (IsTypeName && !isa<TypeDecl>(ND)) {
2804 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002805 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002806 }
2807
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002808 // C++0x N2914 [namespace.udecl]p6:
2809 // A using-declaration shall not name a namespace.
2810 if (isa<NamespaceDecl>(ND)) {
2811 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2812 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002813 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002814 }
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Anders Carlssonc72160b2009-08-28 05:40:36 +00002816 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2817 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002818}
2819
Anders Carlsson81c85c42009-03-28 23:53:49 +00002820/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2821/// is a namespace alias, returns the namespace it points to.
2822static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2823 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2824 return AD->getNamespace();
2825 return dyn_cast_or_null<NamespaceDecl>(D);
2826}
2827
Mike Stump1eb44332009-09-09 15:08:12 +00002828Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002829 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002830 SourceLocation AliasLoc,
2831 IdentifierInfo *Alias,
2832 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002833 SourceLocation IdentLoc,
2834 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Anders Carlsson81c85c42009-03-28 23:53:49 +00002836 // Lookup the namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002837 LookupResult R;
2838 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlsson81c85c42009-03-28 23:53:49 +00002839
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002840 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00002841 if (NamedDecl *PrevDecl
2842 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002843 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002844 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002845 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00002846 if (!R.isAmbiguous() && !R.empty() &&
2847 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00002848 return DeclPtrTy();
2849 }
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002851 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2852 diag::err_redefinition_different_kind;
2853 Diag(AliasLoc, DiagID) << Alias;
2854 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002855 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002856 }
2857
Anders Carlsson5721c682009-03-28 06:42:02 +00002858 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002859 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002860 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002861 }
Mike Stump1eb44332009-09-09 15:08:12 +00002862
John McCallf36e02d2009-10-09 21:13:30 +00002863 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00002864 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002865 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002866 }
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002868 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002869 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2870 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002871 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00002872 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002873
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002874 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002875 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002876}
2877
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002878void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2879 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002880 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2881 !Constructor->isUsed()) &&
2882 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002883
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002884 CXXRecordDecl *ClassDecl
2885 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002886 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump1eb44332009-09-09 15:08:12 +00002887 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002888 // implicitly defined, all the implicitly-declared default constructors
2889 // for its base class and its non-static data members shall have been
2890 // implicitly defined.
2891 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002892 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2893 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002894 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002895 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002896 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002897 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002898 BaseClassDecl->getDefaultConstructor(Context))
2899 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002900 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002901 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00002902 << Context.getTagDeclType(ClassDecl) << 0
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002903 << Context.getTagDeclType(BaseClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002904 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002905 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002906 err = true;
2907 }
2908 }
2909 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002910 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2911 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002912 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2913 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2914 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002915 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002916 CXXRecordDecl *FieldClassDecl
2917 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002918 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002919 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002920 FieldClassDecl->getDefaultConstructor(Context))
2921 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002922 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002923 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00002924 << Context.getTagDeclType(ClassDecl) << 1 <<
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002925 Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian0c728f12009-10-08 22:15:49 +00002926 Diag((*Field)->getLocation(), diag::note_field_decl);
Mike Stump1eb44332009-09-09 15:08:12 +00002927 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002928 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002929 err = true;
2930 }
2931 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002932 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002933 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002934 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002935 Diag((*Field)->getLocation(), diag::note_declared_at);
2936 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002937 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002938 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002939 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002940 Diag((*Field)->getLocation(), diag::note_declared_at);
2941 err = true;
2942 }
2943 }
2944 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002945 Constructor->setUsed();
2946 else
2947 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002948}
2949
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002950void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00002951 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002952 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2953 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00002954
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002955 CXXRecordDecl *ClassDecl
2956 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2957 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2958 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00002959 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002960 // implicitly defined, all the implicitly-declared default destructors
2961 // for its base class and its non-static data members shall have been
2962 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002963 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2964 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002965 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002966 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002967 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002968 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002969 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2970 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2971 else
Mike Stump1eb44332009-09-09 15:08:12 +00002972 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002973 "DefineImplicitDestructor - missing dtor in a base class");
2974 }
2975 }
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002977 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2978 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002979 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2980 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2981 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002982 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002983 CXXRecordDecl *FieldClassDecl
2984 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2985 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002986 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002987 const_cast<CXXDestructorDecl*>(
2988 FieldClassDecl->getDestructor(Context)))
2989 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2990 else
Mike Stump1eb44332009-09-09 15:08:12 +00002991 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002992 "DefineImplicitDestructor - missing dtor in class of a data member");
2993 }
2994 }
2995 }
2996 Destructor->setUsed();
2997}
2998
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002999void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3000 CXXMethodDecl *MethodDecl) {
3001 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3002 MethodDecl->getOverloadedOperator() == OO_Equal &&
3003 !MethodDecl->isUsed()) &&
3004 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003006 CXXRecordDecl *ClassDecl
3007 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003009 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003010 // Before the implicitly-declared copy assignment operator for a class is
3011 // implicitly defined, all implicitly-declared copy assignment operators
3012 // for its direct base classes and its nonstatic data members shall have
3013 // been implicitly defined.
3014 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003015 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3016 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003017 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003018 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003019 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003020 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3021 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3022 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003023 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3024 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003025 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3026 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3027 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003028 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003029 CXXRecordDecl *FieldClassDecl
3030 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003031 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003032 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3033 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003034 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003035 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003036 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3037 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003038 Diag(CurrentLocation, diag::note_first_required_here);
3039 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003040 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003041 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003042 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3043 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003044 Diag(CurrentLocation, diag::note_first_required_here);
3045 err = true;
3046 }
3047 }
3048 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003049 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003050}
3051
3052CXXMethodDecl *
3053Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3054 CXXRecordDecl *ClassDecl) {
3055 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3056 QualType RHSType(LHSType);
3057 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003058 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003059 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003060 RHSType = Context.getCVRQualifiedType(RHSType,
3061 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003062 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3063 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003064 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003065 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3066 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003067 SourceLocation()));
3068 Expr *Args[2] = { &*LHS, &*RHS };
3069 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003070 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003071 CandidateSet);
3072 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003073 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003074 ClassDecl->getLocation(), Best) == OR_Success)
3075 return cast<CXXMethodDecl>(Best->Function);
3076 assert(false &&
3077 "getAssignOperatorMethod - copy assignment operator method not found");
3078 return 0;
3079}
3080
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003081void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3082 CXXConstructorDecl *CopyConstructor,
3083 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003084 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003085 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3086 !CopyConstructor->isUsed()) &&
3087 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003089 CXXRecordDecl *ClassDecl
3090 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3091 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003092 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003093 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003094 // implicitly defined, all the implicitly-declared copy constructors
3095 // for its base class and its non-static data members shall have been
3096 // implicitly defined.
3097 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3098 Base != ClassDecl->bases_end(); ++Base) {
3099 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003100 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003101 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003102 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003103 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003104 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003105 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3106 FieldEnd = ClassDecl->field_end();
3107 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003108 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3109 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3110 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003111 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003112 CXXRecordDecl *FieldClassDecl
3113 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003114 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003115 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003116 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003117 }
3118 }
3119 CopyConstructor->setUsed();
3120}
3121
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003122Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003123Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003124 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003125 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003126 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Douglas Gregor39da0b82009-09-09 23:08:42 +00003128 // C++ [class.copy]p15:
3129 // Whenever a temporary class object is copied using a copy constructor, and
3130 // this object and the copy have the same cv-unqualified type, an
3131 // implementation is permitted to treat the original and the copy as two
3132 // different ways of referring to the same object and not perform a copy at
3133 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003135 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003136 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003137 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003138 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3139 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003140 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3141 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3142 E = ICE->getSubExpr();
3143
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003144 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3145 Elidable = true;
3146 }
Mike Stump1eb44332009-09-09 15:08:12 +00003147
3148 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003149 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003150}
3151
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003152/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3153/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003154Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003155Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3156 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003157 MultiExprArg ExprArgs) {
3158 unsigned NumExprs = ExprArgs.size();
3159 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Douglas Gregor39da0b82009-09-09 23:08:42 +00003161 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3162 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003163}
3164
Anders Carlssone7624a72009-08-27 05:08:22 +00003165Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003166Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3167 QualType Ty,
3168 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003169 MultiExprArg Args,
3170 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003171 unsigned NumExprs = Args.size();
3172 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Douglas Gregor39da0b82009-09-09 23:08:42 +00003174 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3175 TyBeginLoc, Exprs,
3176 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003177}
3178
3179
Mike Stump1eb44332009-09-09 15:08:12 +00003180bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003181 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003182 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003183 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003184 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003185 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003186 if (TempResult.isInvalid())
3187 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003189 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003190 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003191 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003192 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003193
Anders Carlssonfe2de492009-08-25 05:18:00 +00003194 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003195}
3196
Mike Stump1eb44332009-09-09 15:08:12 +00003197void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003198 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003199 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003200 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003201 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003202 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003203 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003204}
3205
Mike Stump1eb44332009-09-09 15:08:12 +00003206/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003207/// ActOnDeclarator, when a C++ direct initializer is present.
3208/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003209void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3210 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003211 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003212 SourceLocation *CommaLocs,
3213 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003214 unsigned NumExprs = Exprs.size();
3215 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003216 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003217
3218 // If there is no declaration, there was an error parsing it. Just ignore
3219 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003220 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003221 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003223 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3224 if (!VDecl) {
3225 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3226 RealDecl->setInvalidDecl();
3227 return;
3228 }
3229
Douglas Gregor83ddad32009-08-26 21:14:46 +00003230 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003231 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003232 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3233 //
3234 // Clients that want to distinguish between the two forms, can check for
3235 // direct initializer using VarDecl::hasCXXDirectInitializer().
3236 // A major benefit is that clients that don't particularly care about which
3237 // exactly form was it (like the CodeGen) can handle both cases without
3238 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003239
Douglas Gregor83ddad32009-08-26 21:14:46 +00003240 // If either the declaration has a dependent type or if any of the expressions
3241 // is type-dependent, we represent the initialization via a ParenListExpr for
3242 // later use during template instantiation.
3243 if (VDecl->getType()->isDependentType() ||
3244 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3245 // Let clients know that initialization was done with a direct initializer.
3246 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Douglas Gregor83ddad32009-08-26 21:14:46 +00003248 // Store the initialization expressions as a ParenListExpr.
3249 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003250 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003251 new (Context) ParenListExpr(Context, LParenLoc,
3252 (Expr **)Exprs.release(),
3253 NumExprs, RParenLoc));
3254 return;
3255 }
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Douglas Gregor83ddad32009-08-26 21:14:46 +00003257
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003258 // C++ 8.5p11:
3259 // The form of initialization (using parentheses or '=') is generally
3260 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003261 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003262 QualType DeclInitType = VDecl->getType();
3263 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003264 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003265
Douglas Gregor615c5d42009-03-24 16:43:20 +00003266 // FIXME: This isn't the right place to complete the type.
3267 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3268 diag::err_typecheck_decl_incomplete_type)) {
3269 VDecl->setInvalidDecl();
3270 return;
3271 }
3272
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003273 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003274 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3275
Douglas Gregor18fe5682008-11-03 20:45:27 +00003276 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003277 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003278 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003279 VDecl->getLocation(),
3280 SourceRange(VDecl->getLocation(),
3281 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003283 IK_Direct,
3284 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003285 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003286 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003287 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003288 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003289 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003290 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003291 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003292 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003293 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003294 return;
3295 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003296
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003297 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003298 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3299 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003300 RealDecl->setInvalidDecl();
3301 return;
3302 }
3303
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003304 // Let clients know that initialization was done with a direct initializer.
3305 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003306
3307 assert(NumExprs == 1 && "Expected 1 expression");
3308 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003309 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3310 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003311}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003312
Douglas Gregor39da0b82009-09-09 23:08:42 +00003313/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3314/// may occur as part of direct-initialization or copy-initialization.
3315///
3316/// \param ClassType the type of the object being initialized, which must have
3317/// class type.
3318///
3319/// \param ArgsPtr the arguments provided to initialize the object
3320///
3321/// \param Loc the source location where the initialization occurs
3322///
3323/// \param Range the source range that covers the entire initialization
3324///
3325/// \param InitEntity the name of the entity being initialized, if known
3326///
3327/// \param Kind the type of initialization being performed
3328///
3329/// \param ConvertedArgs a vector that will be filled in with the
3330/// appropriately-converted arguments to the constructor (if initialization
3331/// succeeded).
3332///
3333/// \returns the constructor used to initialize the object, if successful.
3334/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003335CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003336Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003337 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003338 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003339 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003340 InitializationKind Kind,
3341 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003342 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003343 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003344 Expr **Args = (Expr **)ArgsPtr.get();
3345 unsigned NumArgs = ArgsPtr.size();
3346
Mike Stump1eb44332009-09-09 15:08:12 +00003347 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003348 // If the initialization is direct-initialization, or if it is
3349 // copy-initialization where the cv-unqualified version of the
3350 // source type is the same class as, or a derived class of, the
3351 // class of the destination, constructors are considered. The
3352 // applicable constructors are enumerated (13.3.1.3), and the
3353 // best one is chosen through overload resolution (13.3). The
3354 // constructor so selected is called to initialize the object,
3355 // with the initializer expression(s) as its argument(s). If no
3356 // constructor applies, or the overload resolution is ambiguous,
3357 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003358 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3359 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003360
3361 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003362 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003363 = Context.DeclarationNames.getCXXConstructorName(
3364 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003365 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003366 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003367 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003368 // Find the constructor (which may be a template).
3369 CXXConstructorDecl *Constructor = 0;
3370 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3371 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003372 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003373 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3374 else
3375 Constructor = cast<CXXConstructorDecl>(*Con);
3376
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003377 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003378 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003379 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003380 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3381 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003382 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003383 Args, NumArgs, CandidateSet);
3384 else
3385 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3386 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003387 }
3388
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003389 // FIXME: When we decide not to synthesize the implicitly-declared
3390 // constructors, we'll need to make them appear here.
3391
Douglas Gregor18fe5682008-11-03 20:45:27 +00003392 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003393 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003394 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003395 // We found a constructor. Break out so that we can convert the arguments
3396 // appropriately.
3397 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003398
Douglas Gregor18fe5682008-11-03 20:45:27 +00003399 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003400 if (InitEntity)
3401 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003402 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003403 else
3404 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003405 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003406 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003407 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Douglas Gregor18fe5682008-11-03 20:45:27 +00003409 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003410 if (InitEntity)
3411 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3412 else
3413 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003414 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3415 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003416
3417 case OR_Deleted:
3418 if (InitEntity)
3419 Diag(Loc, diag::err_ovl_deleted_init)
3420 << Best->Function->isDeleted()
3421 << InitEntity << Range;
3422 else
3423 Diag(Loc, diag::err_ovl_deleted_init)
3424 << Best->Function->isDeleted()
3425 << InitEntity << Range;
3426 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3427 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003428 }
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Douglas Gregor39da0b82009-09-09 23:08:42 +00003430 // Convert the arguments, fill in default arguments, etc.
3431 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3432 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3433 return 0;
3434
3435 return Constructor;
3436}
3437
3438/// \brief Given a constructor and the set of arguments provided for the
3439/// constructor, convert the arguments and add any required default arguments
3440/// to form a proper call to this constructor.
3441///
3442/// \returns true if an error occurred, false otherwise.
3443bool
3444Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3445 MultiExprArg ArgsPtr,
3446 SourceLocation Loc,
3447 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3448 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3449 unsigned NumArgs = ArgsPtr.size();
3450 Expr **Args = (Expr **)ArgsPtr.get();
3451
3452 const FunctionProtoType *Proto
3453 = Constructor->getType()->getAs<FunctionProtoType>();
3454 assert(Proto && "Constructor without a prototype?");
3455 unsigned NumArgsInProto = Proto->getNumArgs();
3456 unsigned NumArgsToCheck = NumArgs;
3457
3458 // If too few arguments are available, we'll fill in the rest with defaults.
3459 if (NumArgs < NumArgsInProto) {
3460 NumArgsToCheck = NumArgsInProto;
3461 ConvertedArgs.reserve(NumArgsInProto);
3462 } else {
3463 ConvertedArgs.reserve(NumArgs);
3464 if (NumArgs > NumArgsInProto)
3465 NumArgsToCheck = NumArgsInProto;
3466 }
3467
3468 // Convert arguments
3469 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3470 QualType ProtoArgType = Proto->getArgType(i);
3471
3472 Expr *Arg;
3473 if (i < NumArgs) {
3474 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003475
3476 // Pass the argument.
3477 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3478 return true;
3479
3480 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003481 } else {
3482 ParmVarDecl *Param = Constructor->getParamDecl(i);
3483
3484 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3485 if (DefArg.isInvalid())
3486 return true;
3487
3488 Arg = DefArg.takeAs<Expr>();
3489 }
3490
3491 ConvertedArgs.push_back(Arg);
3492 }
3493
3494 // If this is a variadic call, handle args passed through "...".
3495 if (Proto->isVariadic()) {
3496 // Promote the arguments (C99 6.5.2.2p7).
3497 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3498 Expr *Arg = Args[i];
3499 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3500 return true;
3501
3502 ConvertedArgs.push_back(Arg);
3503 Args[i] = 0;
3504 }
3505 }
3506
3507 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003508}
3509
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003510/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3511/// determine whether they are reference-related,
3512/// reference-compatible, reference-compatible with added
3513/// qualification, or incompatible, for use in C++ initialization by
3514/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3515/// type, and the first type (T1) is the pointee type of the reference
3516/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003517Sema::ReferenceCompareResult
3518Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003519 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003520 assert(!T1->isReferenceType() &&
3521 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003522 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3523
3524 T1 = Context.getCanonicalType(T1);
3525 T2 = Context.getCanonicalType(T2);
3526 QualType UnqualT1 = T1.getUnqualifiedType();
3527 QualType UnqualT2 = T2.getUnqualifiedType();
3528
3529 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003530 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003531 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003532 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003533 if (UnqualT1 == UnqualT2)
3534 DerivedToBase = false;
3535 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3536 DerivedToBase = true;
3537 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003538 return Ref_Incompatible;
3539
3540 // At this point, we know that T1 and T2 are reference-related (at
3541 // least).
3542
3543 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003544 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003545 // reference-related to T2 and cv1 is the same cv-qualification
3546 // as, or greater cv-qualification than, cv2. For purposes of
3547 // overload resolution, cases for which cv1 is greater
3548 // cv-qualification than cv2 are identified as
3549 // reference-compatible with added qualification (see 13.3.3.2).
3550 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3551 return Ref_Compatible;
3552 else if (T1.isMoreQualifiedThan(T2))
3553 return Ref_Compatible_With_Added_Qualification;
3554 else
3555 return Ref_Related;
3556}
3557
3558/// CheckReferenceInit - Check the initialization of a reference
3559/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3560/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003561/// list), and DeclType is the type of the declaration. When ICS is
3562/// non-null, this routine will compute the implicit conversion
3563/// sequence according to C++ [over.ics.ref] and will not produce any
3564/// diagnostics; when ICS is null, it will emit diagnostics when any
3565/// errors are found. Either way, a return value of true indicates
3566/// that there was a failure, a return value of false indicates that
3567/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003568///
3569/// When @p SuppressUserConversions, user-defined conversions are
3570/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003571/// When @p AllowExplicit, we also permit explicit user-defined
3572/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003573/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003574bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003575Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003576 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003577 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003578 bool AllowExplicit, bool ForceRValue,
3579 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003580 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3581
Ted Kremenek6217b802009-07-29 21:53:49 +00003582 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003583 QualType T2 = Init->getType();
3584
Douglas Gregor904eed32008-11-10 20:40:00 +00003585 // If the initializer is the address of an overloaded function, try
3586 // to resolve the overloaded function. If all goes well, T2 is the
3587 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003588 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003589 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003590 ICS != 0);
3591 if (Fn) {
3592 // Since we're performing this reference-initialization for
3593 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003594 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003595 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003596 return true;
3597
Anders Carlsson96ad5332009-10-21 17:16:23 +00003598 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003599 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003600
3601 T2 = Fn->getType();
3602 }
3603 }
3604
Douglas Gregor15da57e2008-10-29 02:00:59 +00003605 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003606 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003607 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003608 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3609 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003610 ReferenceCompareResult RefRelationship
Douglas Gregor15da57e2008-10-29 02:00:59 +00003611 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3612
3613 // Most paths end in a failed conversion.
3614 if (ICS)
3615 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003616
3617 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003618 // A reference to type "cv1 T1" is initialized by an expression
3619 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003620
3621 // -- If the initializer expression
3622
Sebastian Redla9845802009-03-29 15:27:50 +00003623 // Rvalue references cannot bind to lvalues (N2812).
3624 // There is absolutely no situation where they can. In particular, note that
3625 // this is ill-formed, even if B has a user-defined conversion to A&&:
3626 // B b;
3627 // A&& r = b;
3628 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3629 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003630 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003631 << Init->getSourceRange();
3632 return true;
3633 }
3634
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003635 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003636 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3637 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003638 //
3639 // Note that the bit-field check is skipped if we are just computing
3640 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003641 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003642 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003643 BindsDirectly = true;
3644
Douglas Gregor15da57e2008-10-29 02:00:59 +00003645 if (ICS) {
3646 // C++ [over.ics.ref]p1:
3647 // When a parameter of reference type binds directly (8.5.3)
3648 // to an argument expression, the implicit conversion sequence
3649 // is the identity conversion, unless the argument expression
3650 // has a type that is a derived class of the parameter type,
3651 // in which case the implicit conversion sequence is a
3652 // derived-to-base Conversion (13.3.3.1).
3653 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3654 ICS->Standard.First = ICK_Identity;
3655 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3656 ICS->Standard.Third = ICK_Identity;
3657 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3658 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003659 ICS->Standard.ReferenceBinding = true;
3660 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003661 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003662 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003663
3664 // Nothing more to do: the inaccessibility/ambiguity check for
3665 // derived-to-base conversions is suppressed when we're
3666 // computing the implicit conversion sequence (C++
3667 // [over.best.ics]p2).
3668 return false;
3669 } else {
3670 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003671 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3672 if (DerivedToBase)
3673 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003674 else if(CheckExceptionSpecCompatibility(Init, T1))
3675 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003676 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003677 }
3678 }
3679
3680 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003681 // implicitly converted to an lvalue of type "cv3 T3,"
3682 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003683 // 92) (this conversion is selected by enumerating the
3684 // applicable conversion functions (13.3.1.6) and choosing
3685 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003686 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003687 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003688 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003689 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003690
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003691 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003692 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003693 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003694 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003695 = Conversions->function_begin();
3696 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003697 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003698 = dyn_cast<FunctionTemplateDecl>(*Func);
3699 CXXConversionDecl *Conv;
3700 if (ConvTemplate)
3701 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3702 else
3703 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003704
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003705 // If the conversion function doesn't return a reference type,
3706 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003707 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003708 (AllowExplicit || !Conv->isExplicit())) {
3709 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003710 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003711 CandidateSet);
3712 else
3713 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3714 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003715 }
3716
3717 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003718 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003719 case OR_Success:
3720 // This is a direct binding.
3721 BindsDirectly = true;
3722
3723 if (ICS) {
3724 // C++ [over.ics.ref]p1:
3725 //
3726 // [...] If the parameter binds directly to the result of
3727 // applying a conversion function to the argument
3728 // expression, the implicit conversion sequence is a
3729 // user-defined conversion sequence (13.3.3.1.2), with the
3730 // second standard conversion sequence either an identity
3731 // conversion or, if the conversion function returns an
3732 // entity of a type that is a derived class of the parameter
3733 // type, a derived-to-base Conversion.
3734 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3735 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3736 ICS->UserDefined.After = Best->FinalConversion;
3737 ICS->UserDefined.ConversionFunction = Best->Function;
3738 assert(ICS->UserDefined.After.ReferenceBinding &&
3739 ICS->UserDefined.After.DirectBinding &&
3740 "Expected a direct reference binding!");
3741 return false;
3742 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003743 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003744 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003745 CastExpr::CK_UserDefinedConversion,
3746 cast<CXXMethodDecl>(Best->Function),
3747 Owned(Init));
3748 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003749
3750 if (CheckExceptionSpecCompatibility(Init, T1))
3751 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003752 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3753 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003754 }
3755 break;
3756
3757 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003758 if (ICS) {
3759 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3760 Cand != CandidateSet.end(); ++Cand)
3761 if (Cand->Viable)
3762 ICS->ConversionFunctionSet.push_back(Cand->Function);
3763 break;
3764 }
3765 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3766 << Init->getSourceRange();
3767 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003768 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003770 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003771 case OR_Deleted:
3772 // There was no suitable conversion, or we found a deleted
3773 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003774 break;
3775 }
3776 }
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003778 if (BindsDirectly) {
3779 // C++ [dcl.init.ref]p4:
3780 // [...] In all cases where the reference-related or
3781 // reference-compatible relationship of two types is used to
3782 // establish the validity of a reference binding, and T1 is a
3783 // base class of T2, a program that necessitates such a binding
3784 // is ill-formed if T1 is an inaccessible (clause 11) or
3785 // ambiguous (10.2) base class of T2.
3786 //
3787 // Note that we only check this condition when we're allowed to
3788 // complain about errors, because we should not be checking for
3789 // ambiguity (or inaccessibility) unless the reference binding
3790 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003791 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003792 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003793 Init->getSourceRange());
3794 else
3795 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003796 }
3797
3798 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003799 // type (i.e., cv1 shall be const), or the reference shall be an
3800 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003801 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003802 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003803 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003804 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3805 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003806 return true;
3807 }
3808
3809 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003810 // class type, and "cv1 T1" is reference-compatible with
3811 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003812 // following ways (the choice is implementation-defined):
3813 //
3814 // -- The reference is bound to the object represented by
3815 // the rvalue (see 3.10) or to a sub-object within that
3816 // object.
3817 //
Eli Friedman33a31382009-08-05 19:21:58 +00003818 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003819 // a constructor is called to copy the entire rvalue
3820 // object into the temporary. The reference is bound to
3821 // the temporary or to a sub-object within the
3822 // temporary.
3823 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003824 // The constructor that would be used to make the copy
3825 // shall be callable whether or not the copy is actually
3826 // done.
3827 //
Sebastian Redla9845802009-03-29 15:27:50 +00003828 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003829 // freedom, so we will always take the first option and never build
3830 // a temporary in this case. FIXME: We will, however, have to check
3831 // for the presence of a copy constructor in C++98/03 mode.
3832 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003833 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3834 if (ICS) {
3835 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3836 ICS->Standard.First = ICK_Identity;
3837 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3838 ICS->Standard.Third = ICK_Identity;
3839 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3840 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003841 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003842 ICS->Standard.DirectBinding = false;
3843 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003844 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003845 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003846 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3847 if (DerivedToBase)
3848 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003849 else if(CheckExceptionSpecCompatibility(Init, T1))
3850 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003851 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003852 }
3853 return false;
3854 }
3855
Eli Friedman33a31382009-08-05 19:21:58 +00003856 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003857 // initialized from the initializer expression using the
3858 // rules for a non-reference copy initialization (8.5). The
3859 // reference is then bound to the temporary. If T1 is
3860 // reference-related to T2, cv1 must be the same
3861 // cv-qualification as, or greater cv-qualification than,
3862 // cv2; otherwise, the program is ill-formed.
3863 if (RefRelationship == Ref_Related) {
3864 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3865 // we would be reference-compatible or reference-compatible with
3866 // added qualification. But that wasn't the case, so the reference
3867 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003868 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003869 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003870 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3871 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003872 return true;
3873 }
3874
Douglas Gregor734d9862009-01-30 23:27:23 +00003875 // If at least one of the types is a class type, the types are not
3876 // related, and we aren't allowed any user conversions, the
3877 // reference binding fails. This case is important for breaking
3878 // recursion, since TryImplicitConversion below will attempt to
3879 // create a temporary through the use of a copy constructor.
3880 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3881 (T1->isRecordType() || T2->isRecordType())) {
3882 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003883 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00003884 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3885 return true;
3886 }
3887
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003888 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003889 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003890 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003891 //
Sebastian Redla9845802009-03-29 15:27:50 +00003892 // When a parameter of reference type is not bound directly to
3893 // an argument expression, the conversion sequence is the one
3894 // required to convert the argument expression to the
3895 // underlying type of the reference according to
3896 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3897 // to copy-initializing a temporary of the underlying type with
3898 // the argument expression. Any difference in top-level
3899 // cv-qualification is subsumed by the initialization itself
3900 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003901 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3902 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003903 /*ForceRValue=*/false,
3904 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003905
Sebastian Redla9845802009-03-29 15:27:50 +00003906 // Of course, that's still a reference binding.
3907 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3908 ICS->Standard.ReferenceBinding = true;
3909 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003910 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003911 ImplicitConversionSequence::UserDefinedConversion) {
3912 ICS->UserDefined.After.ReferenceBinding = true;
3913 ICS->UserDefined.After.RRefBinding = isRValRef;
3914 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003915 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3916 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003917 ImplicitConversionSequence Conversions;
3918 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3919 false, false,
3920 Conversions);
3921 if (badConversion) {
3922 if ((Conversions.ConversionKind ==
3923 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00003924 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00003925 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003926 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3927 for (int j = Conversions.ConversionFunctionSet.size()-1;
3928 j >= 0; j--) {
3929 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3930 Diag(Func->getLocation(), diag::err_ovl_candidate);
3931 }
3932 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00003933 else {
3934 if (isRValRef)
3935 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3936 << Init->getSourceRange();
3937 else
3938 Diag(DeclLoc, diag::err_invalid_initialization)
3939 << DeclType << Init->getType() << Init->getSourceRange();
3940 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003941 }
3942 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003943 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003944}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003945
3946/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3947/// of this overloaded operator is well-formed. If so, returns false;
3948/// otherwise, emits appropriate diagnostics and returns true.
3949bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003950 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003951 "Expected an overloaded operator declaration");
3952
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003953 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3954
Mike Stump1eb44332009-09-09 15:08:12 +00003955 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003956 // The allocation and deallocation functions, operator new,
3957 // operator new[], operator delete and operator delete[], are
3958 // described completely in 3.7.3. The attributes and restrictions
3959 // found in the rest of this subclause do not apply to them unless
3960 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003961 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003962 if (Op == OO_New || Op == OO_Array_New ||
3963 Op == OO_Delete || Op == OO_Array_Delete)
3964 return false;
3965
3966 // C++ [over.oper]p6:
3967 // An operator function shall either be a non-static member
3968 // function or be a non-member function and have at least one
3969 // parameter whose type is a class, a reference to a class, an
3970 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003971 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3972 if (MethodDecl->isStatic())
3973 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003974 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003975 } else {
3976 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003977 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3978 ParamEnd = FnDecl->param_end();
3979 Param != ParamEnd; ++Param) {
3980 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003981 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3982 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003983 ClassOrEnumParam = true;
3984 break;
3985 }
3986 }
3987
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003988 if (!ClassOrEnumParam)
3989 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003990 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003991 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003992 }
3993
3994 // C++ [over.oper]p8:
3995 // An operator function cannot have default arguments (8.3.6),
3996 // except where explicitly stated below.
3997 //
Mike Stump1eb44332009-09-09 15:08:12 +00003998 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003999 // (C++ [over.call]p1).
4000 if (Op != OO_Call) {
4001 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4002 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004003 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004004 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004005 diag::err_operator_overload_default_arg)
4006 << FnDecl->getDeclName();
4007 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004008 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004009 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004010 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004011 }
4012 }
4013
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004014 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4015 { false, false, false }
4016#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4017 , { Unary, Binary, MemberOnly }
4018#include "clang/Basic/OperatorKinds.def"
4019 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004020
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004021 bool CanBeUnaryOperator = OperatorUses[Op][0];
4022 bool CanBeBinaryOperator = OperatorUses[Op][1];
4023 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004024
4025 // C++ [over.oper]p8:
4026 // [...] Operator functions cannot have more or fewer parameters
4027 // than the number required for the corresponding operator, as
4028 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004029 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004030 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004031 if (Op != OO_Call &&
4032 ((NumParams == 1 && !CanBeUnaryOperator) ||
4033 (NumParams == 2 && !CanBeBinaryOperator) ||
4034 (NumParams < 1) || (NumParams > 2))) {
4035 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004036 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004037 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004038 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004039 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004040 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004041 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004042 assert(CanBeBinaryOperator &&
4043 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004044 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004045 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004046
Chris Lattner416e46f2008-11-21 07:57:12 +00004047 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004048 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004049 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004050
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004051 // Overloaded operators other than operator() cannot be variadic.
4052 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004053 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004054 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004055 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004056 }
4057
4058 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004059 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4060 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004061 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004062 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004063 }
4064
4065 // C++ [over.inc]p1:
4066 // The user-defined function called operator++ implements the
4067 // prefix and postfix ++ operator. If this function is a member
4068 // function with no parameters, or a non-member function with one
4069 // parameter of class or enumeration type, it defines the prefix
4070 // increment operator ++ for objects of that type. If the function
4071 // is a member function with one parameter (which shall be of type
4072 // int) or a non-member function with two parameters (the second
4073 // of which shall be of type int), it defines the postfix
4074 // increment operator ++ for objects of that type.
4075 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4076 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4077 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004078 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004079 ParamIsInt = BT->getKind() == BuiltinType::Int;
4080
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004081 if (!ParamIsInt)
4082 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004083 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004084 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004085 }
4086
Sebastian Redl64b45f72009-01-05 20:52:13 +00004087 // Notify the class if it got an assignment operator.
4088 if (Op == OO_Equal) {
4089 // Would have returned earlier otherwise.
4090 assert(isa<CXXMethodDecl>(FnDecl) &&
4091 "Overloaded = not member, but not filtered.");
4092 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00004093 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004094 Method->getParent()->addedAssignmentOperator(Context, Method);
4095 }
4096
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004097 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004098}
Chris Lattner5a003a42008-12-17 07:09:26 +00004099
Douglas Gregor074149e2009-01-05 19:45:36 +00004100/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4101/// linkage specification, including the language and (if present)
4102/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4103/// the location of the language string literal, which is provided
4104/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4105/// the '{' brace. Otherwise, this linkage specification does not
4106/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004107Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4108 SourceLocation ExternLoc,
4109 SourceLocation LangLoc,
4110 const char *Lang,
4111 unsigned StrSize,
4112 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004113 LinkageSpecDecl::LanguageIDs Language;
4114 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4115 Language = LinkageSpecDecl::lang_c;
4116 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4117 Language = LinkageSpecDecl::lang_cxx;
4118 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004119 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004120 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004121 }
Mike Stump1eb44332009-09-09 15:08:12 +00004122
Chris Lattnercc98eac2008-12-17 07:13:27 +00004123 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Douglas Gregor074149e2009-01-05 19:45:36 +00004125 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004126 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004127 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004128 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004129 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004130 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004131}
4132
Douglas Gregor074149e2009-01-05 19:45:36 +00004133/// ActOnFinishLinkageSpecification - Completely the definition of
4134/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4135/// valid, it's the position of the closing '}' brace in a linkage
4136/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004137Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4138 DeclPtrTy LinkageSpec,
4139 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004140 if (LinkageSpec)
4141 PopDeclContext();
4142 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004143}
4144
Douglas Gregord308e622009-05-18 20:51:54 +00004145/// \brief Perform semantic analysis for the variable declaration that
4146/// occurs within a C++ catch clause, returning the newly-created
4147/// variable.
4148VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004149 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004150 IdentifierInfo *Name,
4151 SourceLocation Loc,
4152 SourceRange Range) {
4153 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004154
4155 // Arrays and functions decay.
4156 if (ExDeclType->isArrayType())
4157 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4158 else if (ExDeclType->isFunctionType())
4159 ExDeclType = Context.getPointerType(ExDeclType);
4160
4161 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4162 // The exception-declaration shall not denote a pointer or reference to an
4163 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004164 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004165 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004166 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004167 Invalid = true;
4168 }
Douglas Gregord308e622009-05-18 20:51:54 +00004169
Sebastian Redl4b07b292008-12-22 19:15:10 +00004170 QualType BaseType = ExDeclType;
4171 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004172 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004173 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004174 BaseType = Ptr->getPointeeType();
4175 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004176 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004177 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004178 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004179 BaseType = Ref->getPointeeType();
4180 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004181 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004182 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004183 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004184 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004185 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004186
Mike Stump1eb44332009-09-09 15:08:12 +00004187 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004188 RequireNonAbstractType(Loc, ExDeclType,
4189 diag::err_abstract_type_in_decl,
4190 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004191 Invalid = true;
4192
Douglas Gregord308e622009-05-18 20:51:54 +00004193 // FIXME: Need to test for ability to copy-construct and destroy the
4194 // exception variable.
4195
Sebastian Redl8351da02008-12-22 21:35:02 +00004196 // FIXME: Need to check for abstract classes.
4197
Mike Stump1eb44332009-09-09 15:08:12 +00004198 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004199 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004200
4201 if (Invalid)
4202 ExDecl->setInvalidDecl();
4203
4204 return ExDecl;
4205}
4206
4207/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4208/// handler.
4209Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004210 DeclaratorInfo *DInfo = 0;
4211 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004212
4213 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004214 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004215 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004216 // The scope should be freshly made just for us. There is just no way
4217 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004218 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004219 if (PrevDecl->isTemplateParameter()) {
4220 // Maybe we will complain about the shadowed template parameter.
4221 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004222 }
4223 }
4224
Chris Lattnereaaebc72009-04-25 08:06:05 +00004225 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004226 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4227 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004228 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004229 }
4230
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004231 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004232 D.getIdentifier(),
4233 D.getIdentifierLoc(),
4234 D.getDeclSpec().getSourceRange());
4235
Chris Lattnereaaebc72009-04-25 08:06:05 +00004236 if (Invalid)
4237 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004238
Sebastian Redl4b07b292008-12-22 19:15:10 +00004239 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004240 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004241 PushOnScopeChains(ExDecl, S);
4242 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004243 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004244
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004245 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004246 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004247}
Anders Carlssonfb311762009-03-14 00:25:26 +00004248
Mike Stump1eb44332009-09-09 15:08:12 +00004249Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004250 ExprArg assertexpr,
4251 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004252 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004253 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004254 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4255
Anders Carlssonc3082412009-03-14 00:33:21 +00004256 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4257 llvm::APSInt Value(32);
4258 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4259 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4260 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004261 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004262 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004263
Anders Carlssonc3082412009-03-14 00:33:21 +00004264 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004265 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004266 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004267 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004268 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004269 }
4270 }
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Anders Carlsson77d81422009-03-15 17:35:16 +00004272 assertexpr.release();
4273 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004274 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004275 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004277 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004278 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004279}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004280
John McCalldd4a3b02009-09-16 22:47:08 +00004281/// Handle a friend type declaration. This works in tandem with
4282/// ActOnTag.
4283///
4284/// Notes on friend class templates:
4285///
4286/// We generally treat friend class declarations as if they were
4287/// declaring a class. So, for example, the elaborated type specifier
4288/// in a friend declaration is required to obey the restrictions of a
4289/// class-head (i.e. no typedefs in the scope chain), template
4290/// parameters are required to match up with simple template-ids, &c.
4291/// However, unlike when declaring a template specialization, it's
4292/// okay to refer to a template specialization without an empty
4293/// template parameter declaration, e.g.
4294/// friend class A<T>::B<unsigned>;
4295/// We permit this as a special case; if there are any template
4296/// parameters present at all, require proper matching, i.e.
4297/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004298Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004299 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004300 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004301
4302 assert(DS.isFriendSpecified());
4303 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4304
John McCalldd4a3b02009-09-16 22:47:08 +00004305 // Try to convert the decl specifier to a type. This works for
4306 // friend templates because ActOnTag never produces a ClassTemplateDecl
4307 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004308 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004309 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4310 if (TheDeclarator.isInvalidType())
4311 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004312
John McCalldd4a3b02009-09-16 22:47:08 +00004313 // This is definitely an error in C++98. It's probably meant to
4314 // be forbidden in C++0x, too, but the specification is just
4315 // poorly written.
4316 //
4317 // The problem is with declarations like the following:
4318 // template <T> friend A<T>::foo;
4319 // where deciding whether a class C is a friend or not now hinges
4320 // on whether there exists an instantiation of A that causes
4321 // 'foo' to equal C. There are restrictions on class-heads
4322 // (which we declare (by fiat) elaborated friend declarations to
4323 // be) that makes this tractable.
4324 //
4325 // FIXME: handle "template <> friend class A<T>;", which
4326 // is possibly well-formed? Who even knows?
4327 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4328 Diag(Loc, diag::err_tagless_friend_type_template)
4329 << DS.getSourceRange();
4330 return DeclPtrTy();
4331 }
4332
John McCall02cace72009-08-28 07:59:38 +00004333 // C++ [class.friend]p2:
4334 // An elaborated-type-specifier shall be used in a friend declaration
4335 // for a class.*
4336 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004337 // This is one of the rare places in Clang where it's legitimate to
4338 // ask about the "spelling" of the type.
4339 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4340 // If we evaluated the type to a record type, suggest putting
4341 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004342 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004343 RecordDecl *RD = RT->getDecl();
4344
4345 std::string InsertionText = std::string(" ") + RD->getKindName();
4346
John McCalle3af0232009-10-07 23:34:25 +00004347 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4348 << (unsigned) RD->getTagKind()
4349 << T
4350 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004351 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4352 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004353 return DeclPtrTy();
4354 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004355 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4356 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004357 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004358 }
4359 }
4360
John McCalle3af0232009-10-07 23:34:25 +00004361 // Enum types cannot be friends.
4362 if (T->getAs<EnumType>()) {
4363 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4364 << SourceRange(DS.getFriendSpecLoc());
4365 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004366 }
John McCall02cace72009-08-28 07:59:38 +00004367
John McCall02cace72009-08-28 07:59:38 +00004368 // C++98 [class.friend]p1: A friend of a class is a function
4369 // or class that is not a member of the class . . .
4370 // But that's a silly restriction which nobody implements for
4371 // inner classes, and C++0x removes it anyway, so we only report
4372 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004373 if (!getLangOptions().CPlusPlus0x)
4374 if (const RecordType *RT = T->getAs<RecordType>())
4375 if (RT->getDecl()->getDeclContext() == CurContext)
4376 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004377
John McCalldd4a3b02009-09-16 22:47:08 +00004378 Decl *D;
4379 if (TempParams.size())
4380 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4381 TempParams.size(),
4382 (TemplateParameterList**) TempParams.release(),
4383 T.getTypePtr(),
4384 DS.getFriendSpecLoc());
4385 else
4386 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4387 DS.getFriendSpecLoc());
4388 D->setAccess(AS_public);
4389 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004390
John McCalldd4a3b02009-09-16 22:47:08 +00004391 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004392}
4393
John McCallbbbcdd92009-09-11 21:02:39 +00004394Sema::DeclPtrTy
4395Sema::ActOnFriendFunctionDecl(Scope *S,
4396 Declarator &D,
4397 bool IsDefinition,
4398 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004399 const DeclSpec &DS = D.getDeclSpec();
4400
4401 assert(DS.isFriendSpecified());
4402 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4403
4404 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004405 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004406 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004407
4408 // C++ [class.friend]p1
4409 // A friend of a class is a function or class....
4410 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004411 // It *doesn't* see through dependent types, which is correct
4412 // according to [temp.arg.type]p3:
4413 // If a declaration acquires a function type through a
4414 // type dependent on a template-parameter and this causes
4415 // a declaration that does not use the syntactic form of a
4416 // function declarator to have a function type, the program
4417 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004418 if (!T->isFunctionType()) {
4419 Diag(Loc, diag::err_unexpected_friend);
4420
4421 // It might be worthwhile to try to recover by creating an
4422 // appropriate declaration.
4423 return DeclPtrTy();
4424 }
4425
4426 // C++ [namespace.memdef]p3
4427 // - If a friend declaration in a non-local class first declares a
4428 // class or function, the friend class or function is a member
4429 // of the innermost enclosing namespace.
4430 // - The name of the friend is not found by simple name lookup
4431 // until a matching declaration is provided in that namespace
4432 // scope (either before or after the class declaration granting
4433 // friendship).
4434 // - If a friend function is called, its name may be found by the
4435 // name lookup that considers functions from namespaces and
4436 // classes associated with the types of the function arguments.
4437 // - When looking for a prior declaration of a class or a function
4438 // declared as a friend, scopes outside the innermost enclosing
4439 // namespace scope are not considered.
4440
John McCall02cace72009-08-28 07:59:38 +00004441 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4442 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004443 assert(Name);
4444
John McCall67d1a672009-08-06 02:15:43 +00004445 // The context we found the declaration in, or in which we should
4446 // create the declaration.
4447 DeclContext *DC;
4448
4449 // FIXME: handle local classes
4450
4451 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004452 NamedDecl *PrevDecl = 0;
John McCall67d1a672009-08-06 02:15:43 +00004453 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004454 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004455 DC = computeDeclContext(ScopeQual);
4456
4457 // FIXME: handle dependent contexts
4458 if (!DC) return DeclPtrTy();
4459
John McCallf36e02d2009-10-09 21:13:30 +00004460 LookupResult R;
4461 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4462 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004463
4464 // If searching in that context implicitly found a declaration in
4465 // a different context, treat it like it wasn't found at all.
4466 // TODO: better diagnostics for this case. Suggesting the right
4467 // qualified scope would be nice...
Douglas Gregor182ddf02009-09-28 00:08:27 +00004468 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004469 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004470 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4471 return DeclPtrTy();
4472 }
4473
4474 // C++ [class.friend]p1: A friend of a class is a function or
4475 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004476 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004477 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4478
John McCall67d1a672009-08-06 02:15:43 +00004479 // Otherwise walk out to the nearest namespace scope looking for matches.
4480 } else {
4481 // TODO: handle local class contexts.
4482
4483 DC = CurContext;
4484 while (true) {
4485 // Skip class contexts. If someone can cite chapter and verse
4486 // for this behavior, that would be nice --- it's what GCC and
4487 // EDG do, and it seems like a reasonable intent, but the spec
4488 // really only says that checks for unqualified existing
4489 // declarations should stop at the nearest enclosing namespace,
4490 // not that they should only consider the nearest enclosing
4491 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004492 while (DC->isRecord())
4493 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004494
John McCallf36e02d2009-10-09 21:13:30 +00004495 LookupResult R;
4496 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4497 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004498
4499 // TODO: decide what we think about using declarations.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004500 if (PrevDecl)
John McCall67d1a672009-08-06 02:15:43 +00004501 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004502
John McCall67d1a672009-08-06 02:15:43 +00004503 if (DC->isFileContext()) break;
4504 DC = DC->getParent();
4505 }
4506
4507 // C++ [class.friend]p1: A friend of a class is a function or
4508 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004509 // C++0x changes this for both friend types and functions.
4510 // Most C++ 98 compilers do seem to give an error here, so
4511 // we do, too.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004512 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004513 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4514 }
4515
Douglas Gregor182ddf02009-09-28 00:08:27 +00004516 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004517 // This implies that it has to be an operator or function.
John McCall02cace72009-08-28 07:59:38 +00004518 if (D.getKind() == Declarator::DK_Constructor ||
4519 D.getKind() == Declarator::DK_Destructor ||
4520 D.getKind() == Declarator::DK_Conversion) {
John McCall67d1a672009-08-06 02:15:43 +00004521 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall02cace72009-08-28 07:59:38 +00004522 (D.getKind() == Declarator::DK_Constructor ? 0 :
4523 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004524 return DeclPtrTy();
4525 }
John McCall67d1a672009-08-06 02:15:43 +00004526 }
4527
Douglas Gregor182ddf02009-09-28 00:08:27 +00004528 bool Redeclaration = false;
4529 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregora735b202009-10-13 14:39:41 +00004530 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004531 IsDefinition,
4532 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004533 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004534
Douglas Gregor182ddf02009-09-28 00:08:27 +00004535 assert(ND->getDeclContext() == DC);
4536 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004537
John McCallab88d972009-08-31 22:39:49 +00004538 // Add the function declaration to the appropriate lookup tables,
4539 // adjusting the redeclarations list as necessary. We don't
4540 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004541 //
John McCallab88d972009-08-31 22:39:49 +00004542 // Also update the scope-based lookup if the target context's
4543 // lookup context is in lexical scope.
4544 if (!CurContext->isDependentContext()) {
4545 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004546 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004547 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004548 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004549 }
John McCall02cace72009-08-28 07:59:38 +00004550
4551 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004552 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004553 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004554 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004555 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004556
Douglas Gregor182ddf02009-09-28 00:08:27 +00004557 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004558}
4559
Chris Lattnerb28317a2009-03-28 19:18:32 +00004560void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004561 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004562
Chris Lattnerb28317a2009-03-28 19:18:32 +00004563 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004564 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4565 if (!Fn) {
4566 Diag(DelLoc, diag::err_deleted_non_function);
4567 return;
4568 }
4569 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4570 Diag(DelLoc, diag::err_deleted_decl_not_first);
4571 Diag(Prev->getLocation(), diag::note_previous_declaration);
4572 // If the declaration wasn't the first, we delete the function anyway for
4573 // recovery.
4574 }
4575 Fn->setDeleted();
4576}
Sebastian Redl13e88542009-04-27 21:33:24 +00004577
4578static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4579 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4580 ++CI) {
4581 Stmt *SubStmt = *CI;
4582 if (!SubStmt)
4583 continue;
4584 if (isa<ReturnStmt>(SubStmt))
4585 Self.Diag(SubStmt->getSourceRange().getBegin(),
4586 diag::err_return_in_constructor_handler);
4587 if (!isa<Expr>(SubStmt))
4588 SearchForReturnInStmt(Self, SubStmt);
4589 }
4590}
4591
4592void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4593 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4594 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4595 SearchForReturnInStmt(*this, Handler);
4596 }
4597}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004598
Mike Stump1eb44332009-09-09 15:08:12 +00004599bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004600 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004601 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4602 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004603
4604 QualType CNewTy = Context.getCanonicalType(NewTy);
4605 QualType COldTy = Context.getCanonicalType(OldTy);
4606
Mike Stump1eb44332009-09-09 15:08:12 +00004607 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004608 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4609 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004610
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004611 // Check if the return types are covariant
4612 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004613
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004614 /// Both types must be pointers or references to classes.
4615 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4616 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4617 NewClassTy = NewPT->getPointeeType();
4618 OldClassTy = OldPT->getPointeeType();
4619 }
4620 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4621 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4622 NewClassTy = NewRT->getPointeeType();
4623 OldClassTy = OldRT->getPointeeType();
4624 }
4625 }
Mike Stump1eb44332009-09-09 15:08:12 +00004626
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004627 // The return types aren't either both pointers or references to a class type.
4628 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004629 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004630 diag::err_different_return_type_for_overriding_virtual_function)
4631 << New->getDeclName() << NewTy << OldTy;
4632 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004633
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004634 return true;
4635 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004636
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004637 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4638 // Check if the new class derives from the old class.
4639 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4640 Diag(New->getLocation(),
4641 diag::err_covariant_return_not_derived)
4642 << New->getDeclName() << NewTy << OldTy;
4643 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4644 return true;
4645 }
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004647 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004648 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004649 diag::err_covariant_return_inaccessible_base,
4650 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4651 // FIXME: Should this point to the return type?
4652 New->getLocation(), SourceRange(), New->getDeclName())) {
4653 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4654 return true;
4655 }
4656 }
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004658 // The qualifiers of the return types must be the same.
4659 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4660 Diag(New->getLocation(),
4661 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004662 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004663 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4664 return true;
4665 };
Mike Stump1eb44332009-09-09 15:08:12 +00004666
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004667
4668 // The new class type must have the same or less qualifiers as the old type.
4669 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4670 Diag(New->getLocation(),
4671 diag::err_covariant_return_type_class_type_more_qualified)
4672 << New->getDeclName() << NewTy << OldTy;
4673 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4674 return true;
4675 };
Mike Stump1eb44332009-09-09 15:08:12 +00004676
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004677 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004678}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004679
4680/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4681/// initializer for the declaration 'Dcl'.
4682/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4683/// static data member of class X, names should be looked up in the scope of
4684/// class X.
4685void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004686 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004688 Decl *D = Dcl.getAs<Decl>();
4689 // If there is no declaration, there was an error parsing it.
4690 if (D == 0)
4691 return;
4692
4693 // Check whether it is a declaration with a nested name specifier like
4694 // int foo::bar;
4695 if (!D->isOutOfLine())
4696 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004698 // C++ [basic.lookup.unqual]p13
4699 //
4700 // A name used in the definition of a static data member of class X
4701 // (after the qualified-id of the static member) is looked up as if the name
4702 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004704 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004705 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004706}
4707
4708/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4709/// initializer for the declaration 'Dcl'.
4710void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004711 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004713 Decl *D = Dcl.getAs<Decl>();
4714 // If there is no declaration, there was an error parsing it.
4715 if (D == 0)
4716 return;
4717
4718 // Check whether it is a declaration with a nested name specifier like
4719 // int foo::bar;
4720 if (!D->isOutOfLine())
4721 return;
4722
4723 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004724 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004725}