blob: a45c22e2981d2d786df60b763ea2c95ee03f016c [file] [log] [blame]
Chris Lattner199abbc2008-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 Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Chris Lattner58258242008-04-10 02:22:51 +000026#include "llvm/Support/Compiler.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm> // for std::equal
Douglas Gregor29a92472008-10-22 17:49:05 +000028#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000029#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000030
31using namespace clang;
32
Chris Lattner58258242008-04-10 02:22:51 +000033//===----------------------------------------------------------------------===//
34// CheckDefaultArgumentVisitor
35//===----------------------------------------------------------------------===//
36
Chris Lattnerb0d38442008-04-12 23:52:44 +000037namespace {
38 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
39 /// the default argument of a parameter to determine whether it
40 /// contains any ill-formed subexpressions. For example, this will
41 /// diagnose the use of local variables or parameters within the
42 /// default argument expression.
Mike Stump11289f42009-09-09 15:08:12 +000043 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000044 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000045 Expr *DefaultArg;
46 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000047
Chris Lattnerb0d38442008-04-12 23:52:44 +000048 public:
Mike Stump11289f42009-09-09 15:08:12 +000049 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000051
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 bool VisitExpr(Expr *Node);
53 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000054 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 };
Chris Lattner58258242008-04-10 02:22:51 +000056
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 /// VisitExpr - Visit all of the children of this expression.
58 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
59 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000060 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000061 E = Node->child_end(); I != E; ++I)
62 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000064 }
65
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 /// VisitDeclRefExpr - Visit a reference to a declaration, to
67 /// determine whether this declaration can be used in the default
68 /// argument expression.
69 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000070 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
72 // C++ [dcl.fct.default]p9
73 // Default arguments are evaluated each time the function is
74 // called. The order of evaluation of function arguments is
75 // unspecified. Consequently, parameters of a function shall not
76 // be used in default argument expressions, even if they are not
77 // evaluated. Parameters of a function declared before a default
78 // argument expression are in scope and can hide namespace and
79 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000080 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000081 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000082 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000083 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000084 // C++ [dcl.fct.default]p7
85 // Local variables shall not be used in default argument
86 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000087 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000088 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000089 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000090 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000091 }
Chris Lattner58258242008-04-10 02:22:51 +000092
Douglas Gregor8e12c382008-11-04 13:41:56 +000093 return false;
94 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000095
Douglas Gregor97a9c812008-11-04 14:32:21 +000096 /// VisitCXXThisExpr - Visit a C++ "this" expression.
97 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
98 // C++ [dcl.fct.default]p8:
99 // The keyword this shall not be used in a default argument of a
100 // member function.
101 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_this)
103 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000104 }
Chris Lattner58258242008-04-10 02:22:51 +0000105}
106
Anders Carlssonc80a1272009-08-25 02:29:20 +0000107bool
108Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000109 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000110 QualType ParamType = Param->getType();
111
Anders Carlsson114056f2009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssonc80a1272009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000119
Anders Carlssonc80a1272009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000126 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000127 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000128 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000129
130 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000131
Anders Carlssonc80a1272009-08-25 02:29:20 +0000132 // Okay: add the default argument to the parameter
133 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000134
Anders Carlssonc80a1272009-08-25 02:29:20 +0000135 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000136
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000137 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138}
139
Chris Lattner58258242008-04-10 02:22:51 +0000140/// ActOnParamDefaultArgument - Check whether the default argument
141/// provided for a function parameter is well-formed. If so, attach it
142/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000143void
Mike Stump11289f42009-09-09 15:08:12 +0000144Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000145 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000146 if (!param || !defarg.get())
147 return;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Chris Lattner83f095c2009-03-28 19:18:32 +0000149 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000150 UnparsedDefaultArgLocs.erase(Param);
151
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000152 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000153 QualType ParamType = Param->getType();
154
155 // Default arguments are only permitted in C++
156 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000157 Diag(EqualLoc, diag::err_param_default_argument)
158 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000159 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000160 return;
161 }
162
Anders Carlssonf1c26952009-08-25 01:02:06 +0000163 // Check that the default argument is well-formed
164 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
165 if (DefaultArgChecker.Visit(DefaultArg.get())) {
166 Param->setInvalidDecl();
167 return;
168 }
Mike Stump11289f42009-09-09 15:08:12 +0000169
Anders Carlssonc80a1272009-08-25 02:29:20 +0000170 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000171}
172
Douglas Gregor58354032008-12-24 00:01:03 +0000173/// ActOnParamUnparsedDefaultArgument - We've seen a default
174/// argument for a function parameter, but we can't parse it yet
175/// because we're inside a class definition. Note that this default
176/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000177void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000178 SourceLocation EqualLoc,
179 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000180 if (!param)
181 return;
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattner83f095c2009-03-28 19:18:32 +0000183 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000184 if (Param)
185 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000186
Anders Carlsson84613c42009-06-12 16:51:40 +0000187 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000188}
189
Douglas Gregor4d87df52008-12-16 21:30:33 +0000190/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
191/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000192void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000193 if (!param)
194 return;
Mike Stump11289f42009-09-09 15:08:12 +0000195
Anders Carlsson84613c42009-06-12 16:51:40 +0000196 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000197
Anders Carlsson84613c42009-06-12 16:51:40 +0000198 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000199
Anders Carlsson84613c42009-06-12 16:51:40 +0000200 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000201}
202
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000203/// CheckExtraCXXDefaultArguments - Check for any extra default
204/// arguments in the declarator, which is not a function declaration
205/// or definition and therefore is not permitted to have default
206/// arguments. This routine should be invoked for every declarator
207/// that is not a function declaration or definition.
208void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
209 // C++ [dcl.fct.default]p3
210 // A default argument expression shall be specified only in the
211 // parameter-declaration-clause of a function declaration or in a
212 // template-parameter (14.1). It shall not be specified for a
213 // parameter pack. If it is specified in a
214 // parameter-declaration-clause, it shall not occur within a
215 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000216 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000217 DeclaratorChunk &chunk = D.getTypeObject(i);
218 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000219 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
220 ParmVarDecl *Param =
221 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000222 if (Param->hasUnparsedDefaultArg()) {
223 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
225 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
226 delete Toks;
227 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000228 } else if (Param->getDefaultArg()) {
229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << Param->getDefaultArg()->getSourceRange();
231 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000232 }
233 }
234 }
235 }
236}
237
Chris Lattner199abbc2008-04-08 05:04:30 +0000238// MergeCXXFunctionDecl - Merge two declarations of the same C++
239// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000240// type. Subroutine of MergeFunctionDecl. Returns true if there was an
241// error, false otherwise.
242bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
243 bool Invalid = false;
244
Chris Lattner199abbc2008-04-08 05:04:30 +0000245 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000246 // For non-template functions, default arguments can be added in
247 // later declarations of a function in the same
248 // scope. Declarations in different scopes have completely
249 // distinct sets of default arguments. That is, declarations in
250 // inner scopes do not acquire default arguments from
251 // declarations in outer scopes, and vice versa. In a given
252 // function declaration, all parameters subsequent to a
253 // parameter with a default argument shall have default
254 // arguments supplied in this or previous declarations. A
255 // default argument shall not be redefined by a later
256 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000257 //
258 // C++ [dcl.fct.default]p6:
259 // Except for member functions of class templates, the default arguments
260 // in a member function definition that appears outside of the class
261 // definition are added to the set of default arguments provided by the
262 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000263 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
264 ParmVarDecl *OldParam = Old->getParamDecl(p);
265 ParmVarDecl *NewParam = New->getParamDecl(p);
266
Douglas Gregorc732aba2009-09-11 18:44:32 +0000267 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000268 // FIXME: If the parameter doesn't have an identifier then the location
269 // points to the '=' which means that the fixit hint won't remove any
270 // extra spaces between the type and the '='.
271 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson1566eb52009-11-10 03:32:44 +0000272 if (NewParam->getIdentifier())
273 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000274
Mike Stump11289f42009-09-09 15:08:12 +0000275 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000276 diag::err_param_default_argument_redefinition)
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000277 << NewParam->getDefaultArgRange()
278 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
279 NewParam->getLocEnd()));
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280
281 // Look for the function declaration where the default argument was
282 // actually written, which may be a declaration prior to Old.
283 for (FunctionDecl *Older = Old->getPreviousDeclaration();
284 Older; Older = Older->getPreviousDeclaration()) {
285 if (!Older->getParamDecl(p)->hasDefaultArg())
286 break;
287
288 OldParam = Older->getParamDecl(p);
289 }
290
291 Diag(OldParam->getLocation(), diag::note_previous_definition)
292 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000293 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000294 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000295 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000296 if (OldParam->hasUninstantiatedDefaultArg())
297 NewParam->setUninstantiatedDefaultArg(
298 OldParam->getUninstantiatedDefaultArg());
299 else
300 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000301 } else if (NewParam->hasDefaultArg()) {
302 if (New->getDescribedFunctionTemplate()) {
303 // Paragraph 4, quoted above, only applies to non-template functions.
304 Diag(NewParam->getLocation(),
305 diag::err_param_default_argument_template_redecl)
306 << NewParam->getDefaultArgRange();
307 Diag(Old->getLocation(), diag::note_template_prev_declaration)
308 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000309 } else if (New->getTemplateSpecializationKind()
310 != TSK_ImplicitInstantiation &&
311 New->getTemplateSpecializationKind() != TSK_Undeclared) {
312 // C++ [temp.expr.spec]p21:
313 // Default function arguments shall not be specified in a declaration
314 // or a definition for one of the following explicit specializations:
315 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000316 // - the explicit specialization of a member function template;
317 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000318 // template where the class template specialization to which the
319 // member function specialization belongs is implicitly
320 // instantiated.
321 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
322 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
323 << New->getDeclName()
324 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000325 } else if (New->getDeclContext()->isDependentContext()) {
326 // C++ [dcl.fct.default]p6 (DR217):
327 // Default arguments for a member function of a class template shall
328 // be specified on the initial declaration of the member function
329 // within the class template.
330 //
331 // Reading the tea leaves a bit in DR217 and its reference to DR205
332 // leads me to the conclusion that one cannot add default function
333 // arguments for an out-of-line definition of a member function of a
334 // dependent type.
335 int WhichKind = 2;
336 if (CXXRecordDecl *Record
337 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
338 if (Record->getDescribedClassTemplate())
339 WhichKind = 0;
340 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
341 WhichKind = 1;
342 else
343 WhichKind = 2;
344 }
345
346 Diag(NewParam->getLocation(),
347 diag::err_param_default_argument_member_template_redecl)
348 << WhichKind
349 << NewParam->getDefaultArgRange();
350 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000351 }
352 }
353
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000354 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000355 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
356 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000357 Invalid = true;
358 }
359
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000360 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000361}
362
363/// CheckCXXDefaultArguments - Verify that the default arguments for a
364/// function declaration are well-formed according to C++
365/// [dcl.fct.default].
366void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
367 unsigned NumParams = FD->getNumParams();
368 unsigned p;
369
370 // Find first parameter with a default argument
371 for (p = 0; p < NumParams; ++p) {
372 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000373 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000374 break;
375 }
376
377 // C++ [dcl.fct.default]p4:
378 // In a given function declaration, all parameters
379 // subsequent to a parameter with a default argument shall
380 // have default arguments supplied in this or previous
381 // declarations. A default argument shall not be redefined
382 // by a later declaration (not even to the same value).
383 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000384 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000385 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000386 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000387 if (Param->isInvalidDecl())
388 /* We already complained about this parameter. */;
389 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000390 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000391 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000392 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000393 else
Mike Stump11289f42009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000395 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 LastMissingDefaultArg = p;
398 }
399 }
400
401 if (LastMissingDefaultArg > 0) {
402 // Some default arguments were missing. Clear out all of the
403 // default arguments up to (and including) the last missing
404 // default argument, so that we leave the function parameters
405 // in a semantically valid state.
406 for (p = 0; p <= LastMissingDefaultArg; ++p) {
407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000408 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000409 if (!Param->hasUnparsedDefaultArg())
410 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000411 Param->setDefaultArg(0);
412 }
413 }
414 }
415}
Douglas Gregor556877c2008-04-13 21:30:24 +0000416
Douglas Gregor61956c42008-10-31 09:07:45 +0000417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000423 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000424 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000425 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
427 } else
428 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
429
430 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000431 return &II == CurDecl->getIdentifier();
432 else
433 return false;
434}
435
Mike Stump11289f42009-09-09 15:08:12 +0000436/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000437///
438/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
439/// and returns NULL otherwise.
440CXXBaseSpecifier *
441Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
442 SourceRange SpecifierRange,
443 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000444 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000445 SourceLocation BaseLoc) {
446 // C++ [class.union]p1:
447 // A union shall not have base classes.
448 if (Class->isUnion()) {
449 Diag(Class->getLocation(), diag::err_base_clause_on_union)
450 << SpecifierRange;
451 return 0;
452 }
453
454 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000455 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000456 Class->getTagKind() == RecordDecl::TK_class,
457 Access, BaseType);
458
459 // Base specifiers must be record types.
460 if (!BaseType->isRecordType()) {
461 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
462 return 0;
463 }
464
465 // C++ [class.union]p1:
466 // A union shall not be used as a base class.
467 if (BaseType->isUnionType()) {
468 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.derived]p2:
473 // The class-name in a base-specifier shall not be an incompletely
474 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000475 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000476 PDiag(diag::err_incomplete_base_class)
477 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000478 return 0;
479
Eli Friedmanc96d4962009-08-15 21:55:26 +0000480 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000481 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000482 assert(BaseDecl && "Record type has no declaration");
483 BaseDecl = BaseDecl->getDefinition(Context);
484 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000485 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
486 assert(CXXBaseDecl && "Base type is not a C++ type");
487 if (!CXXBaseDecl->isEmpty())
488 Class->setEmpty(false);
489 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 Class->setPolymorphic(true);
491
492 // C++ [dcl.init.aggr]p1:
493 // An aggregate is [...] a class with [...] no base classes [...].
494 Class->setAggregate(false);
495 Class->setPOD(false);
496
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000497 if (Virtual) {
498 // C++ [class.ctor]p5:
499 // A constructor is trivial if its class has no virtual base classes.
500 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000501
502 // C++ [class.copy]p6:
503 // A copy constructor is trivial if its class has no virtual base classes.
504 Class->setHasTrivialCopyConstructor(false);
505
506 // C++ [class.copy]p11:
507 // A copy assignment operator is trivial if its class has no virtual
508 // base classes.
509 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000510
511 // C++0x [meta.unary.prop] is_empty:
512 // T is a class type, but not a union type, with ... no virtual base
513 // classes
514 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000515 } else {
516 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000517 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000518 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000519 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
520 Class->setHasTrivialConstructor(false);
521
522 // C++ [class.copy]p6:
523 // A copy constructor is trivial if all the direct base classes of its
524 // class have trivial copy constructors.
525 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
526 Class->setHasTrivialCopyConstructor(false);
527
528 // C++ [class.copy]p11:
529 // A copy assignment operator is trivial if all the direct base classes
530 // of its class have trivial copy assignment operators.
531 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
532 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000533 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000534
535 // C++ [class.ctor]p3:
536 // A destructor is trivial if all the direct base classes of its class
537 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000538 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
539 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000540
Douglas Gregor463421d2009-03-03 04:44:36 +0000541 // Create the base specifier.
542 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000543 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
544 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000545 Access, BaseType);
546}
547
Douglas Gregor556877c2008-04-13 21:30:24 +0000548/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
549/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000550/// example:
551/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000552/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000553Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000554Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000555 bool Virtual, AccessSpecifier Access,
556 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000557 if (!classdecl)
558 return true;
559
Douglas Gregorc40290e2009-03-09 23:48:35 +0000560 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000561 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000562 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000563 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
564 Virtual, Access,
565 BaseType, BaseLoc))
566 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Douglas Gregor463421d2009-03-03 04:44:36 +0000568 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000569}
Douglas Gregor556877c2008-04-13 21:30:24 +0000570
Douglas Gregor463421d2009-03-03 04:44:36 +0000571/// \brief Performs the actual work of attaching the given base class
572/// specifiers to a C++ class.
573bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
574 unsigned NumBases) {
575 if (NumBases == 0)
576 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000577
578 // Used to keep track of which base types we have already seen, so
579 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000580 // that the key is always the unqualified canonical type of the base
581 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000582 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
583
584 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000585 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000586 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000587 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000588 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000589 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000590 NewBaseType = NewBaseType.getUnqualifiedType();
591
Douglas Gregor29a92472008-10-22 17:49:05 +0000592 if (KnownBaseTypes[NewBaseType]) {
593 // C++ [class.mi]p3:
594 // A class shall not be specified as a direct base class of a
595 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000597 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000598 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000599 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000600
601 // Delete the duplicate base class specifier; we're going to
602 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000603 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000604
605 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000606 } else {
607 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000608 KnownBaseTypes[NewBaseType] = Bases[idx];
609 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000610 }
611 }
612
613 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000614 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000615
616 // Delete the remaining (good) base class specifiers, since their
617 // data has been copied into the CXXRecordDecl.
618 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000619 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000620
621 return Invalid;
622}
623
624/// ActOnBaseSpecifiers - Attach the given base specifiers to the
625/// class, after checking whether there are any duplicate base
626/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000627void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000628 unsigned NumBases) {
629 if (!ClassDecl || !Bases || !NumBases)
630 return;
631
632 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000633 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000634 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000635}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000636
Douglas Gregor36d1b142009-10-06 17:59:45 +0000637/// \brief Determine whether the type \p Derived is a C++ class that is
638/// derived from the type \p Base.
639bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
640 if (!getLangOptions().CPlusPlus)
641 return false;
642
643 const RecordType *DerivedRT = Derived->getAs<RecordType>();
644 if (!DerivedRT)
645 return false;
646
647 const RecordType *BaseRT = Base->getAs<RecordType>();
648 if (!BaseRT)
649 return false;
650
651 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
652 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
653 return DerivedRD->isDerivedFrom(BaseRD);
654}
655
656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
661
662 const RecordType *DerivedRT = Derived->getAs<RecordType>();
663 if (!DerivedRT)
664 return false;
665
666 const RecordType *BaseRT = Base->getAs<RecordType>();
667 if (!BaseRT)
668 return false;
669
670 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
671 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
672 return DerivedRD->isDerivedFrom(BaseRD, Paths);
673}
674
675/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
676/// conversion (where Derived and Base are class types) is
677/// well-formed, meaning that the conversion is unambiguous (and
678/// that all of the base classes are accessible). Returns true
679/// and emits a diagnostic if the code is ill-formed, returns false
680/// otherwise. Loc is the location where this routine should point to
681/// if there is an error, and Range is the source range to highlight
682/// if there is an error.
683bool
684Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
685 unsigned InaccessibleBaseID,
686 unsigned AmbigiousBaseConvID,
687 SourceLocation Loc, SourceRange Range,
688 DeclarationName Name) {
689 // First, determine whether the path from Derived to Base is
690 // ambiguous. This is slightly more expensive than checking whether
691 // the Derived to Base conversion exists, because here we need to
692 // explore multiple paths to determine if there is an ambiguity.
693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
694 /*DetectVirtual=*/false);
695 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
696 assert(DerivationOkay &&
697 "Can only be used with a derived-to-base conversion");
698 (void)DerivationOkay;
699
700 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000701 if (InaccessibleBaseID == 0)
702 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000703 // Check that the base class can be accessed.
704 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
705 Name);
706 }
707
708 // We know that the derived-to-base conversion is ambiguous, and
709 // we're going to produce a diagnostic. Perform the derived-to-base
710 // search just one more time to compute all of the possible paths so
711 // that we can print them out. This is more expensive than any of
712 // the previous derived-to-base checks we've done, but at this point
713 // performance isn't as much of an issue.
714 Paths.clear();
715 Paths.setRecordingPaths(true);
716 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
717 assert(StillOkay && "Can only be used with a derived-to-base conversion");
718 (void)StillOkay;
719
720 // Build up a textual representation of the ambiguous paths, e.g.,
721 // D -> B -> A, that will be used to illustrate the ambiguous
722 // conversions in the diagnostic. We only print one of the paths
723 // to each base class subobject.
724 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
725
726 Diag(Loc, AmbigiousBaseConvID)
727 << Derived << Base << PathDisplayStr << Range << Name;
728 return true;
729}
730
731bool
732Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000733 SourceLocation Loc, SourceRange Range,
734 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000735 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000736 IgnoreAccess ? 0 :
737 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000738 diag::err_ambiguous_derived_to_base_conv,
739 Loc, Range, DeclarationName());
740}
741
742
743/// @brief Builds a string representing ambiguous paths from a
744/// specific derived class to different subobjects of the same base
745/// class.
746///
747/// This function builds a string that can be used in error messages
748/// to show the different paths that one can take through the
749/// inheritance hierarchy to go from the derived class to different
750/// subobjects of a base class. The result looks something like this:
751/// @code
752/// struct D -> struct B -> struct A
753/// struct D -> struct C -> struct A
754/// @endcode
755std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
756 std::string PathDisplayStr;
757 std::set<unsigned> DisplayedPaths;
758 for (CXXBasePaths::paths_iterator Path = Paths.begin();
759 Path != Paths.end(); ++Path) {
760 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
761 // We haven't displayed a path to this particular base
762 // class subobject yet.
763 PathDisplayStr += "\n ";
764 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
765 for (CXXBasePath::const_iterator Element = Path->begin();
766 Element != Path->end(); ++Element)
767 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
768 }
769 }
770
771 return PathDisplayStr;
772}
773
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000774//===----------------------------------------------------------------------===//
775// C++ class member Handling
776//===----------------------------------------------------------------------===//
777
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000778/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
779/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
780/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000781/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000782Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000783Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000784 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000785 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000786 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000787 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000788 Expr *BitWidth = static_cast<Expr*>(BW);
789 Expr *Init = static_cast<Expr*>(InitExpr);
790 SourceLocation Loc = D.getIdentifierLoc();
791
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000792 bool isFunc = D.isFunctionDeclarator();
793
John McCall07e91c02009-08-06 02:15:43 +0000794 assert(!DS.isFriendSpecified());
795
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000796 // C++ 9.2p6: A member shall not be declared to have automatic storage
797 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000798 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
799 // data members and cannot be applied to names declared const or static,
800 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000801 switch (DS.getStorageClassSpec()) {
802 case DeclSpec::SCS_unspecified:
803 case DeclSpec::SCS_typedef:
804 case DeclSpec::SCS_static:
805 // FALL THROUGH.
806 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000807 case DeclSpec::SCS_mutable:
808 if (isFunc) {
809 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000810 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000811 else
Chris Lattner3b054132008-11-19 05:08:23 +0000812 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000813
Sebastian Redl8071edb2008-11-17 23:24:37 +0000814 // FIXME: It would be nicer if the keyword was ignored only for this
815 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000816 D.getMutableDeclSpec().ClearStorageClassSpecs();
817 } else {
818 QualType T = GetTypeForDeclarator(D, S);
819 diag::kind err = static_cast<diag::kind>(0);
820 if (T->isReferenceType())
821 err = diag::err_mutable_reference;
822 else if (T.isConstQualified())
823 err = diag::err_mutable_const;
824 if (err != 0) {
825 if (DS.getStorageClassSpecLoc().isValid())
826 Diag(DS.getStorageClassSpecLoc(), err);
827 else
828 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000829 // FIXME: It would be nicer if the keyword was ignored only for this
830 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000831 D.getMutableDeclSpec().ClearStorageClassSpecs();
832 }
833 }
834 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000835 default:
836 if (DS.getStorageClassSpecLoc().isValid())
837 Diag(DS.getStorageClassSpecLoc(),
838 diag::err_storageclass_invalid_for_member);
839 else
840 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
841 D.getMutableDeclSpec().ClearStorageClassSpecs();
842 }
843
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000844 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000845 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000846 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000847 // Check also for this case:
848 //
849 // typedef int f();
850 // f a;
851 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000852 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000853 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000854 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000855
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000856 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
857 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000858 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000859
860 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000861 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000862 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000863 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
864 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000865 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000866 } else {
Douglas Gregor3447e762009-08-20 22:52:58 +0000867 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
868 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000869 if (!Member) {
870 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000871 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000872 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000873
874 // Non-instance-fields can't have a bitfield.
875 if (BitWidth) {
876 if (Member->isInvalidDecl()) {
877 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000878 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000879 // C++ 9.6p3: A bit-field shall not be a static member.
880 // "static member 'A' cannot be a bit-field"
881 Diag(Loc, diag::err_static_not_bitfield)
882 << Name << BitWidth->getSourceRange();
883 } else if (isa<TypedefDecl>(Member)) {
884 // "typedef member 'x' cannot be a bit-field"
885 Diag(Loc, diag::err_typedef_not_bitfield)
886 << Name << BitWidth->getSourceRange();
887 } else {
888 // A function typedef ("typedef int f(); f a;").
889 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
890 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000891 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000892 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattnerd26760a2009-03-05 23:01:03 +0000895 DeleteExpr(BitWidth);
896 BitWidth = 0;
897 Member->setInvalidDecl();
898 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000899
900 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000901
Douglas Gregor3447e762009-08-20 22:52:58 +0000902 // If we have declared a member function template, set the access of the
903 // templated declaration as well.
904 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
905 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000906 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000907
Douglas Gregor92751d42008-11-17 22:58:34 +0000908 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000909
Douglas Gregor0c880302009-03-11 23:00:04 +0000910 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000911 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000912 if (Deleted) // FIXME: Source location is not very good.
913 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000914
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000916 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000917 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000918 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000919 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000920}
921
Douglas Gregore8381c02008-11-05 04:29:56 +0000922/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000923Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000924Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000925 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000926 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000927 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000928 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000929 SourceLocation IdLoc,
930 SourceLocation LParenLoc,
931 ExprTy **Args, unsigned NumArgs,
932 SourceLocation *CommaLocs,
933 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000934 if (!ConstructorD)
935 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000936
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000937 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000938
939 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000940 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000941 if (!Constructor) {
942 // The user wrote a constructor initializer on a function that is
943 // not a C++ constructor. Ignore the error for now, because we may
944 // have more member initializers coming; we'll diagnose it just
945 // once in ActOnMemInitializers.
946 return true;
947 }
948
949 CXXRecordDecl *ClassDecl = Constructor->getParent();
950
951 // C++ [class.base.init]p2:
952 // Names in a mem-initializer-id are looked up in the scope of the
953 // constructor’s class and, if not found in that scope, are looked
954 // up in the scope containing the constructor’s
955 // definition. [Note: if the constructor’s class contains a member
956 // with the same name as a direct or virtual base class of the
957 // class, a mem-initializer-id naming the member or base class and
958 // composed of a single identifier refers to the class member. A
959 // mem-initializer-id for the hidden base class may be specified
960 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000961 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000962 // Look for a member, first.
963 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000964 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000965 = ClassDecl->lookup(MemberOrBase);
966 if (Result.first != Result.second)
967 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000968
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000969 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000970
Eli Friedman8e1433b2009-07-29 19:44:27 +0000971 if (Member)
972 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
973 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000974 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000975 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000976 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000977 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000978 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000979 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
980 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000981
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000982 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000983
Eli Friedman8e1433b2009-07-29 19:44:27 +0000984 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
985 RParenLoc, ClassDecl);
986}
987
John McCalle22a04a2009-11-04 23:02:40 +0000988/// Checks an initializer expression for use of uninitialized fields, such as
989/// containing the field that is being initialized. Returns true if there is an
990/// uninitialized field was used an updates the SourceLocation parameter; false
991/// otherwise.
992static bool InitExprContainsUninitializedFields(const Stmt* S,
993 const FieldDecl* LhsField,
994 SourceLocation* L) {
995 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
996 if (ME) {
997 const NamedDecl* RhsField = ME->getMemberDecl();
998 if (RhsField == LhsField) {
999 // Initializing a field with itself. Throw a warning.
1000 // But wait; there are exceptions!
1001 // Exception #1: The field may not belong to this record.
1002 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1003 const Expr* base = ME->getBase();
1004 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1005 // Even though the field matches, it does not belong to this record.
1006 return false;
1007 }
1008 // None of the exceptions triggered; return true to indicate an
1009 // uninitialized field was used.
1010 *L = ME->getMemberLoc();
1011 return true;
1012 }
1013 }
1014 bool found = false;
1015 for (Stmt::const_child_iterator it = S->child_begin();
1016 it != S->child_end() && found == false;
1017 ++it) {
1018 if (isa<CallExpr>(S)) {
1019 // Do not descend into function calls or constructors, as the use
1020 // of an uninitialized field may be valid. One would have to inspect
1021 // the contents of the function/ctor to determine if it is safe or not.
1022 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1023 // may be safe, depending on what the function/ctor does.
1024 continue;
1025 }
1026 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1027 }
1028 return found;
1029}
1030
Eli Friedman8e1433b2009-07-29 19:44:27 +00001031Sema::MemInitResult
1032Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1033 unsigned NumArgs, SourceLocation IdLoc,
1034 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001035 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1036 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1037 ExprTemporaries.clear();
1038
John McCalle22a04a2009-11-04 23:02:40 +00001039 // Diagnose value-uses of fields to initialize themselves, e.g.
1040 // foo(foo)
1041 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001042 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001043 for (unsigned i = 0; i < NumArgs; ++i) {
1044 SourceLocation L;
1045 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1046 // FIXME: Return true in the case when other fields are used before being
1047 // uninitialized. For example, let this field be the i'th field. When
1048 // initializing the i'th field, throw a warning if any of the >= i'th
1049 // fields are used, as they are not yet initialized.
1050 // Right now we are only handling the case where the i'th field uses
1051 // itself in its initializer.
1052 Diag(L, diag::warn_field_is_uninit);
1053 }
1054 }
1055
Eli Friedman8e1433b2009-07-29 19:44:27 +00001056 bool HasDependentArg = false;
1057 for (unsigned i = 0; i < NumArgs; i++)
1058 HasDependentArg |= Args[i]->isTypeDependent();
1059
1060 CXXConstructorDecl *C = 0;
1061 QualType FieldType = Member->getType();
1062 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1063 FieldType = Array->getElementType();
1064 if (FieldType->isDependentType()) {
1065 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001066 } else if (FieldType->isRecordType()) {
1067 // Member is a record (struct/union/class), so pass the initializer
1068 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001069 if (!HasDependentArg) {
1070 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1071
1072 C = PerformInitializationByConstructor(FieldType,
1073 MultiExprArg(*this,
1074 (void**)Args,
1075 NumArgs),
1076 IdLoc,
1077 SourceRange(IdLoc, RParenLoc),
1078 Member->getDeclName(), IK_Direct,
1079 ConstructorArgs);
1080
1081 if (C) {
1082 // Take over the constructor arguments as our own.
1083 NumArgs = ConstructorArgs.size();
1084 Args = (Expr **)ConstructorArgs.take();
1085 }
1086 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001087 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001088 // The member type is not a record type (or an array of record
1089 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001090 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001091 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1092 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001093 Expr *NewExp;
1094 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001095 if (FieldType->isReferenceType()) {
1096 Diag(IdLoc, diag::err_null_intialized_reference_member)
1097 << Member->getDeclName();
1098 return Diag(Member->getLocation(), diag::note_declared_at);
1099 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001100 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1101 NumArgs = 1;
1102 }
1103 else
1104 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001105 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1106 return true;
1107 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001108 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001109
1110 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1111 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1112 ExprTemporaries.clear();
1113
Eli Friedman8e1433b2009-07-29 19:44:27 +00001114 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +00001115 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001116 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001117}
1118
1119Sema::MemInitResult
1120Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1121 unsigned NumArgs, SourceLocation IdLoc,
1122 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1123 bool HasDependentArg = false;
1124 for (unsigned i = 0; i < NumArgs; i++)
1125 HasDependentArg |= Args[i]->isTypeDependent();
1126
1127 if (!BaseType->isDependentType()) {
1128 if (!BaseType->isRecordType())
1129 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1130 << BaseType << SourceRange(IdLoc, RParenLoc);
1131
1132 // C++ [class.base.init]p2:
1133 // [...] Unless the mem-initializer-id names a nonstatic data
1134 // member of the constructor’s class or a direct or virtual base
1135 // of that class, the mem-initializer is ill-formed. A
1136 // mem-initializer-list can initialize a base class using any
1137 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001138
Eli Friedman8e1433b2009-07-29 19:44:27 +00001139 // First, check for a direct base class.
1140 const CXXBaseSpecifier *DirectBaseSpec = 0;
1141 for (CXXRecordDecl::base_class_const_iterator Base =
1142 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump11289f42009-09-09 15:08:12 +00001143 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman8e1433b2009-07-29 19:44:27 +00001144 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1145 // We found a direct base of this type. That's what we're
1146 // initializing.
1147 DirectBaseSpec = &*Base;
1148 break;
1149 }
1150 }
Mike Stump11289f42009-09-09 15:08:12 +00001151
Eli Friedman8e1433b2009-07-29 19:44:27 +00001152 // Check for a virtual base class.
1153 // FIXME: We might be able to short-circuit this if we know in advance that
1154 // there are no virtual bases.
1155 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1156 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1157 // We haven't found a base yet; search the class hierarchy for a
1158 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001159 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1160 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001161 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001162 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001163 Path != Paths.end(); ++Path) {
1164 if (Path->back().Base->isVirtual()) {
1165 VirtualBaseSpec = Path->back().Base;
1166 break;
1167 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001168 }
1169 }
1170 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001171
1172 // C++ [base.class.init]p2:
1173 // If a mem-initializer-id is ambiguous because it designates both
1174 // a direct non-virtual base class and an inherited virtual base
1175 // class, the mem-initializer is ill-formed.
1176 if (DirectBaseSpec && VirtualBaseSpec)
1177 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1178 << BaseType << SourceRange(IdLoc, RParenLoc);
1179 // C++ [base.class.init]p2:
1180 // Unless the mem-initializer-id names a nonstatic data membeer of the
1181 // constructor's class ot a direst or virtual base of that class, the
1182 // mem-initializer is ill-formed.
1183 if (!DirectBaseSpec && !VirtualBaseSpec)
1184 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1185 << BaseType << ClassDecl->getNameAsCString()
1186 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001187 }
1188
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001189 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001190 if (!BaseType->isDependentType() && !HasDependentArg) {
1191 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001192 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001193 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1194
1195 C = PerformInitializationByConstructor(BaseType,
1196 MultiExprArg(*this,
1197 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +00001198 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001199 Name, IK_Direct,
1200 ConstructorArgs);
1201 if (C) {
1202 // Take over the constructor arguments as our own.
1203 NumArgs = ConstructorArgs.size();
1204 Args = (Expr **)ConstructorArgs.take();
1205 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001206 }
1207
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001208 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1209 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1210 ExprTemporaries.clear();
1211
Mike Stump11289f42009-09-09 15:08:12 +00001212 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001213 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001214}
1215
Eli Friedman9cf6b592009-11-09 19:20:36 +00001216bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001217Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001218 CXXBaseOrMemberInitializer **Initializers,
1219 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001220 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001221 // We need to build the initializer AST according to order of construction
1222 // and not what user specified in the Initializers list.
1223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1224 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1225 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1226 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001227 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001228
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001229 for (unsigned i = 0; i < NumInitializers; i++) {
1230 CXXBaseOrMemberInitializer *Member = Initializers[i];
1231 if (Member->isBaseInitializer()) {
1232 if (Member->getBaseClass()->isDependentType())
1233 HasDependentBaseInit = true;
1234 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1235 } else {
1236 AllBaseFields[Member->getMember()] = Member;
1237 }
1238 }
Mike Stump11289f42009-09-09 15:08:12 +00001239
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001240 if (HasDependentBaseInit) {
1241 // FIXME. This does not preserve the ordering of the initializers.
1242 // Try (with -Wreorder)
1243 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001244 // template<class X> struct B : A<X> {
1245 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001246 // int x1;
1247 // };
1248 // B<int> x;
1249 // On seeing one dependent type, we should essentially exit this routine
1250 // while preserving user-declared initializer list. When this routine is
1251 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001252 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001253
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001254 // If we have a dependent base initialization, we can't determine the
1255 // association between initializers and bases; just dump the known
1256 // initializers into the list, and don't try to deal with other bases.
1257 for (unsigned i = 0; i < NumInitializers; i++) {
1258 CXXBaseOrMemberInitializer *Member = Initializers[i];
1259 if (Member->isBaseInitializer())
1260 AllToInit.push_back(Member);
1261 }
1262 } else {
1263 // Push virtual bases before others.
1264 for (CXXRecordDecl::base_class_iterator VBase =
1265 ClassDecl->vbases_begin(),
1266 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1267 if (VBase->getType()->isDependentType())
1268 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001269 if (CXXBaseOrMemberInitializer *Value
1270 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001271 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001272 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001273 else {
Mike Stump11289f42009-09-09 15:08:12 +00001274 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001275 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001276 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001277 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001278 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001279 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1280 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1281 << 0 << VBase->getType();
1282 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1283 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001284 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001285 continue;
1286 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001287
Anders Carlsson561f7932009-10-29 15:46:07 +00001288 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1289 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1290 Constructor->getLocation(), CtorArgs))
1291 continue;
1292
1293 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1294
Anders Carlssonbdd12402009-11-13 20:11:49 +00001295 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1296 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1297 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001298 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001299 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1300 CtorArgs.takeAs<Expr>(),
1301 CtorArgs.size(), Ctor,
1302 SourceLocation(),
1303 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001304 AllToInit.push_back(Member);
1305 }
1306 }
Mike Stump11289f42009-09-09 15:08:12 +00001307
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001308 for (CXXRecordDecl::base_class_iterator Base =
1309 ClassDecl->bases_begin(),
1310 E = ClassDecl->bases_end(); Base != E; ++Base) {
1311 // Virtuals are in the virtual base list and already constructed.
1312 if (Base->isVirtual())
1313 continue;
1314 // Skip dependent types.
1315 if (Base->getType()->isDependentType())
1316 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001317 if (CXXBaseOrMemberInitializer *Value
1318 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001319 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001320 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001321 else {
Mike Stump11289f42009-09-09 15:08:12 +00001322 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001323 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001324 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001325 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001326 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001327 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1328 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1329 << 0 << Base->getType();
1330 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1331 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001332 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001333 continue;
1334 }
1335
1336 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1337 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1338 Constructor->getLocation(), CtorArgs))
1339 continue;
1340
1341 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001342
Anders Carlssonbdd12402009-11-13 20:11:49 +00001343 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1344 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1345 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001346 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001347 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1348 CtorArgs.takeAs<Expr>(),
1349 CtorArgs.size(), Ctor,
1350 SourceLocation(),
1351 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001352 AllToInit.push_back(Member);
1353 }
1354 }
1355 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001357 // non-static data members.
1358 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1359 E = ClassDecl->field_end(); Field != E; ++Field) {
1360 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001361 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001362 Field->getType()->getAs<RecordType>()) {
1363 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001364 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001365 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001366 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1367 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1368 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1369 // set to the anonymous union data member used in the initializer
1370 // list.
1371 Value->setMember(*Field);
1372 Value->setAnonUnionMember(*FA);
1373 AllToInit.push_back(Value);
1374 break;
1375 }
1376 }
1377 }
1378 continue;
1379 }
1380 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1381 AllToInit.push_back(Value);
1382 continue;
1383 }
Mike Stump11289f42009-09-09 15:08:12 +00001384
Eli Friedmand7686ef2009-11-09 01:05:47 +00001385 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001386 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001387
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001388 QualType FT = Context.getBaseElementType((*Field)->getType());
1389 if (const RecordType* RT = FT->getAs<RecordType>()) {
1390 CXXConstructorDecl *Ctor =
1391 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001392 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001393 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1394 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1395 << 1 << (*Field)->getDeclName();
1396 Diag(Field->getLocation(), diag::note_field_decl);
1397 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1398 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001399 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001400 continue;
1401 }
1402
1403 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1404 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1405 Constructor->getLocation(), CtorArgs))
1406 continue;
1407
Anders Carlssonbdd12402009-11-13 20:11:49 +00001408 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1409 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1410 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001411 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001412 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1413 CtorArgs.size(), Ctor,
1414 SourceLocation(),
1415 SourceLocation());
1416
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001417 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001418 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1419 if (FT.isConstQualified() && Ctor->isTrivial()) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001420 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001421 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1422 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001423 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001424 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001425 }
1426 }
1427 else if (FT->isReferenceType()) {
1428 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001429 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1430 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001431 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001432 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001433 }
1434 else if (FT.isConstQualified()) {
1435 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001436 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1437 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001438 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001439 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001440 }
1441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001443 NumInitializers = AllToInit.size();
1444 if (NumInitializers > 0) {
1445 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1446 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1447 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001448
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001449 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1450 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1451 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1452 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001453
1454 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001455}
1456
Eli Friedman952c15d2009-07-21 19:28:10 +00001457static void *GetKeyForTopLevelField(FieldDecl *Field) {
1458 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001459 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001460 if (RT->getDecl()->isAnonymousStructOrUnion())
1461 return static_cast<void *>(RT->getDecl());
1462 }
1463 return static_cast<void *>(Field);
1464}
1465
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001466static void *GetKeyForBase(QualType BaseType) {
1467 if (const RecordType *RT = BaseType->getAs<RecordType>())
1468 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001469
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001470 assert(0 && "Unexpected base type!");
1471 return 0;
1472}
1473
Mike Stump11289f42009-09-09 15:08:12 +00001474static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001475 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001476 // For fields injected into the class via declaration of an anonymous union,
1477 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001478 if (Member->isMemberInitializer()) {
1479 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001480
Eli Friedmand7686ef2009-11-09 01:05:47 +00001481 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001482 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001483 // in AnonUnionMember field.
1484 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1485 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001486 if (Field->getDeclContext()->isRecord()) {
1487 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1488 if (RD->isAnonymousStructOrUnion())
1489 return static_cast<void *>(RD);
1490 }
1491 return static_cast<void *>(Field);
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001494 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001495}
1496
John McCallc90f6d72009-11-04 23:13:52 +00001497/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001498void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001499 SourceLocation ColonLoc,
1500 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001501 if (!ConstructorDecl)
1502 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001503
1504 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001505
1506 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001507 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001508
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001509 if (!Constructor) {
1510 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1511 return;
1512 }
Mike Stump11289f42009-09-09 15:08:12 +00001513
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001514 if (!Constructor->isDependentContext()) {
1515 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1516 bool err = false;
1517 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001518 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001519 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1520 void *KeyToMember = GetKeyForMember(Member);
1521 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1522 if (!PrevMember) {
1523 PrevMember = Member;
1524 continue;
1525 }
1526 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001527 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001528 diag::error_multiple_mem_initialization)
1529 << Field->getNameAsString();
1530 else {
1531 Type *BaseClass = Member->getBaseClass();
1532 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001533 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001534 diag::error_multiple_base_initialization)
John McCalla1925362009-09-29 23:03:30 +00001535 << QualType(BaseClass, 0);
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001536 }
1537 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1538 << 0;
1539 err = true;
1540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001542 if (err)
1543 return;
1544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Eli Friedmand7686ef2009-11-09 01:05:47 +00001546 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001547 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001548 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001549
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001550 if (Constructor->isDependentContext())
1551 return;
Mike Stump11289f42009-09-09 15:08:12 +00001552
1553 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001554 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001555 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001556 Diagnostic::Ignored)
1557 return;
Mike Stump11289f42009-09-09 15:08:12 +00001558
Anders Carlssone0eebb32009-08-27 05:45:01 +00001559 // Also issue warning if order of ctor-initializer list does not match order
1560 // of 1) base class declarations and 2) order of non-static data members.
1561 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001562
Anders Carlssone0eebb32009-08-27 05:45:01 +00001563 CXXRecordDecl *ClassDecl
1564 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1565 // Push virtual bases before others.
1566 for (CXXRecordDecl::base_class_iterator VBase =
1567 ClassDecl->vbases_begin(),
1568 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001569 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001570
Anders Carlssone0eebb32009-08-27 05:45:01 +00001571 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1572 E = ClassDecl->bases_end(); Base != E; ++Base) {
1573 // Virtuals are alread in the virtual base list and are constructed
1574 // first.
1575 if (Base->isVirtual())
1576 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001577 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001578 }
Mike Stump11289f42009-09-09 15:08:12 +00001579
Anders Carlssone0eebb32009-08-27 05:45:01 +00001580 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1581 E = ClassDecl->field_end(); Field != E; ++Field)
1582 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001583
Anders Carlssone0eebb32009-08-27 05:45:01 +00001584 int Last = AllBaseOrMembers.size();
1585 int curIndex = 0;
1586 CXXBaseOrMemberInitializer *PrevMember = 0;
1587 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001588 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001589 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1590 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001591
Anders Carlssone0eebb32009-08-27 05:45:01 +00001592 for (; curIndex < Last; curIndex++)
1593 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1594 break;
1595 if (curIndex == Last) {
1596 assert(PrevMember && "Member not in member list?!");
1597 // Initializer as specified in ctor-initializer list is out of order.
1598 // Issue a warning diagnostic.
1599 if (PrevMember->isBaseInitializer()) {
1600 // Diagnostics is for an initialized base class.
1601 Type *BaseClass = PrevMember->getBaseClass();
1602 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001603 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001604 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001605 } else {
1606 FieldDecl *Field = PrevMember->getMember();
1607 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001608 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001609 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001610 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001611 // Also the note!
1612 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001613 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001614 diag::note_fieldorbase_initialized_here) << 0
1615 << Field->getNameAsString();
1616 else {
1617 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001618 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001619 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001620 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001621 }
1622 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001623 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001624 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001625 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001626 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001627 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001628}
1629
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001630void
1631Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1632 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1633 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump11289f42009-09-09 15:08:12 +00001634
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001635 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1636 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1637 if (VBase->getType()->isDependentType())
1638 continue;
1639 // Skip over virtual bases which have trivial destructors.
1640 CXXRecordDecl *BaseClassDecl
1641 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1642 if (BaseClassDecl->hasTrivialDestructor())
1643 continue;
1644 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001645 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001646 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001647
1648 uintptr_t Member =
1649 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001650 | CXXDestructorDecl::VBASE;
1651 AllToDestruct.push_back(Member);
1652 }
1653 for (CXXRecordDecl::base_class_iterator Base =
1654 ClassDecl->bases_begin(),
1655 E = ClassDecl->bases_end(); Base != E; ++Base) {
1656 if (Base->isVirtual())
1657 continue;
1658 if (Base->getType()->isDependentType())
1659 continue;
1660 // Skip over virtual bases which have trivial destructors.
1661 CXXRecordDecl *BaseClassDecl
1662 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1663 if (BaseClassDecl->hasTrivialDestructor())
1664 continue;
1665 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001666 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001667 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001668 uintptr_t Member =
1669 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001670 | CXXDestructorDecl::DRCTNONVBASE;
1671 AllToDestruct.push_back(Member);
1672 }
Mike Stump11289f42009-09-09 15:08:12 +00001673
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001674 // non-static data members.
1675 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1676 E = ClassDecl->field_end(); Field != E; ++Field) {
1677 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001678
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001679 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1680 // Skip over virtual bases which have trivial destructors.
1681 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1682 if (FieldClassDecl->hasTrivialDestructor())
1683 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001684 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001685 FieldClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001686 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001687 const_cast<CXXDestructorDecl*>(Dtor));
1688 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1689 AllToDestruct.push_back(Member);
1690 }
1691 }
Mike Stump11289f42009-09-09 15:08:12 +00001692
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001693 unsigned NumDestructions = AllToDestruct.size();
1694 if (NumDestructions > 0) {
1695 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump11289f42009-09-09 15:08:12 +00001696 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001697 new (Context) uintptr_t [NumDestructions];
1698 // Insert in reverse order.
1699 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1700 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1701 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1702 }
1703}
1704
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001705void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001706 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001707 return;
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001709 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001710
1711 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001712 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001713 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001714}
1715
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001716namespace {
1717 /// PureVirtualMethodCollector - traverses a class and its superclasses
1718 /// and determines if it has any pure virtual methods.
1719 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1720 ASTContext &Context;
1721
Sebastian Redlb7d64912009-03-22 21:28:55 +00001722 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001723 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001724
1725 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001726 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001727
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001728 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001729
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001730 public:
Mike Stump11289f42009-09-09 15:08:12 +00001731 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001732 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001733
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001734 MethodList List;
1735 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001736
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001737 // Copy the temporary list to methods, and make sure to ignore any
1738 // null entries.
1739 for (size_t i = 0, e = List.size(); i != e; ++i) {
1740 if (List[i])
1741 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001742 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001743 }
Mike Stump11289f42009-09-09 15:08:12 +00001744
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001745 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001746
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001747 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1748 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001749 };
Mike Stump11289f42009-09-09 15:08:12 +00001750
1751 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001752 MethodList& Methods) {
1753 // First, collect the pure virtual methods for the base classes.
1754 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1755 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001756 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001757 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001758 if (BaseDecl && BaseDecl->isAbstract())
1759 Collect(BaseDecl, Methods);
1760 }
1761 }
Mike Stump11289f42009-09-09 15:08:12 +00001762
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001763 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001764 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001765
Anders Carlsson3c012712009-05-17 00:00:05 +00001766 MethodSetTy OverriddenMethods;
1767 size_t MethodsSize = Methods.size();
1768
Mike Stump11289f42009-09-09 15:08:12 +00001769 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001770 i != e; ++i) {
1771 // Traverse the record, looking for methods.
1772 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001773 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001774 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001775 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001776
Anders Carlsson700179432009-10-18 19:34:08 +00001777 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001778 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1779 E = MD->end_overridden_methods(); I != E; ++I) {
1780 // Keep track of the overridden methods.
1781 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001782 }
1783 }
1784 }
Mike Stump11289f42009-09-09 15:08:12 +00001785
1786 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001787 // overridden.
1788 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1789 if (OverriddenMethods.count(Methods[i]))
1790 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001791 }
Mike Stump11289f42009-09-09 15:08:12 +00001792
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001793 }
1794}
Douglas Gregore8381c02008-11-05 04:29:56 +00001795
Anders Carlssoneabf7702009-08-27 00:13:57 +00001796
Mike Stump11289f42009-09-09 15:08:12 +00001797bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001798 unsigned DiagID, AbstractDiagSelID SelID,
1799 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001800 if (SelID == -1)
1801 return RequireNonAbstractType(Loc, T,
1802 PDiag(DiagID), CurrentRD);
1803 else
1804 return RequireNonAbstractType(Loc, T,
1805 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001806}
1807
Anders Carlssoneabf7702009-08-27 00:13:57 +00001808bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1809 const PartialDiagnostic &PD,
1810 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001811 if (!getLangOptions().CPlusPlus)
1812 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001813
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001814 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001815 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001816 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001817
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001818 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001819 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001820 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001821 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001822
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001823 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001824 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001827 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001828 if (!RT)
1829 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001830
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001831 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1832 if (!RD)
1833 return false;
1834
Anders Carlssonb57738b2009-03-24 17:23:42 +00001835 if (CurrentRD && CurrentRD != RD)
1836 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001837
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001838 if (!RD->isAbstract())
1839 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001840
Anders Carlssoneabf7702009-08-27 00:13:57 +00001841 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001842
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001843 // Check if we've already emitted the list of pure virtual functions for this
1844 // class.
1845 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1846 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001847
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001848 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001849
1850 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001851 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1852 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001853
1854 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001855 MD->getDeclName();
1856 }
1857
1858 if (!PureVirtualClassDiagSet)
1859 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1860 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001862 return true;
1863}
1864
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001865namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001866 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001867 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1868 Sema &SemaRef;
1869 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001870
Anders Carlssonb57738b2009-03-24 17:23:42 +00001871 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001872 bool Invalid = false;
1873
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001874 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1875 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001876 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001877
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001878 return Invalid;
1879 }
Mike Stump11289f42009-09-09 15:08:12 +00001880
Anders Carlssonb57738b2009-03-24 17:23:42 +00001881 public:
1882 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1883 : SemaRef(SemaRef), AbstractClass(ac) {
1884 Visit(SemaRef.Context.getTranslationUnitDecl());
1885 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001886
Anders Carlssonb57738b2009-03-24 17:23:42 +00001887 bool VisitFunctionDecl(const FunctionDecl *FD) {
1888 if (FD->isThisDeclarationADefinition()) {
1889 // No need to do the check if we're in a definition, because it requires
1890 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001891 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001892 return VisitDeclContext(FD);
1893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
Anders Carlssonb57738b2009-03-24 17:23:42 +00001895 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001896 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001897 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001898 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1899 diag::err_abstract_type_in_decl,
1900 Sema::AbstractReturnType,
1901 AbstractClass);
1902
Mike Stump11289f42009-09-09 15:08:12 +00001903 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001904 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001905 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001906 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001907 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001908 VD->getOriginalType(),
1909 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001910 Sema::AbstractParamType,
1911 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001912 }
1913
1914 return Invalid;
1915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Anders Carlssonb57738b2009-03-24 17:23:42 +00001917 bool VisitDecl(const Decl* D) {
1918 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1919 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001920
Anders Carlssonb57738b2009-03-24 17:23:42 +00001921 return false;
1922 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001923 };
1924}
1925
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001926void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001927 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001928 SourceLocation LBrac,
1929 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001930 if (!TagDecl)
1931 return;
Mike Stump11289f42009-09-09 15:08:12 +00001932
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001933 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001934 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001935 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001936 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001937
Chris Lattner83f095c2009-03-28 19:18:32 +00001938 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001939 if (!RD->isAbstract()) {
1940 // Collect all the pure virtual methods and see if this is an abstract
1941 // class after all.
1942 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001943 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001944 RD->setAbstract(true);
1945 }
Mike Stump11289f42009-09-09 15:08:12 +00001946
1947 if (RD->isAbstract())
Anders Carlssonb57738b2009-03-24 17:23:42 +00001948 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor3c74d412009-10-14 20:14:33 +00001950 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001951 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001952}
1953
Douglas Gregor05379422008-11-03 17:51:48 +00001954/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1955/// special functions, such as the default constructor, copy
1956/// constructor, or destructor, to the given C++ class (C++
1957/// [special]p1). This routine can only be executed just before the
1958/// definition of the class is complete.
1959void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001960 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001961 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001962
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001963 // FIXME: Implicit declarations have exception specifications, which are
1964 // the union of the specifications of the implicitly called functions.
1965
Douglas Gregor05379422008-11-03 17:51:48 +00001966 if (!ClassDecl->hasUserDeclaredConstructor()) {
1967 // C++ [class.ctor]p5:
1968 // A default constructor for a class X is a constructor of class X
1969 // that can be called without an argument. If there is no
1970 // user-declared constructor for class X, a default constructor is
1971 // implicitly declared. An implicitly-declared default constructor
1972 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001973 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001974 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001975 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001976 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001977 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001978 Context.getFunctionType(Context.VoidTy,
1979 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001980 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001981 /*isExplicit=*/false,
1982 /*isInline=*/true,
1983 /*isImplicitlyDeclared=*/true);
1984 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001985 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001986 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001987 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001988 }
1989
1990 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1991 // C++ [class.copy]p4:
1992 // If the class definition does not explicitly declare a copy
1993 // constructor, one is declared implicitly.
1994
1995 // C++ [class.copy]p5:
1996 // The implicitly-declared copy constructor for a class X will
1997 // have the form
1998 //
1999 // X::X(const X&)
2000 //
2001 // if
2002 bool HasConstCopyConstructor = true;
2003
2004 // -- each direct or virtual base class B of X has a copy
2005 // constructor whose first parameter is of type const B& or
2006 // const volatile B&, and
2007 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2008 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2009 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002010 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002011 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002012 = BaseClassDecl->hasConstCopyConstructor(Context);
2013 }
2014
2015 // -- for all the nonstatic data members of X that are of a
2016 // class type M (or array thereof), each such class type
2017 // has a copy constructor whose first parameter is of type
2018 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002019 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2020 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002021 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002022 QualType FieldType = (*Field)->getType();
2023 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2024 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002025 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002026 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002027 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002028 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002029 = FieldClassDecl->hasConstCopyConstructor(Context);
2030 }
2031 }
2032
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002033 // Otherwise, the implicitly declared copy constructor will have
2034 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002035 //
2036 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002037 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002038 if (HasConstCopyConstructor)
2039 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002040 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002041
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002042 // An implicitly-declared copy constructor is an inline public
2043 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002044 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002045 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002046 CXXConstructorDecl *CopyConstructor
2047 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002048 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002049 Context.getFunctionType(Context.VoidTy,
2050 &ArgType, 1,
2051 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002052 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002053 /*isExplicit=*/false,
2054 /*isInline=*/true,
2055 /*isImplicitlyDeclared=*/true);
2056 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002057 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002058 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002059
2060 // Add the parameter to the constructor.
2061 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2062 ClassDecl->getLocation(),
2063 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002064 ArgType, /*DInfo=*/0,
2065 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002066 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002067 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002068 }
2069
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002070 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2071 // Note: The following rules are largely analoguous to the copy
2072 // constructor rules. Note that virtual bases are not taken into account
2073 // for determining the argument type of the operator. Note also that
2074 // operators taking an object instead of a reference are allowed.
2075 //
2076 // C++ [class.copy]p10:
2077 // If the class definition does not explicitly declare a copy
2078 // assignment operator, one is declared implicitly.
2079 // The implicitly-defined copy assignment operator for a class X
2080 // will have the form
2081 //
2082 // X& X::operator=(const X&)
2083 //
2084 // if
2085 bool HasConstCopyAssignment = true;
2086
2087 // -- each direct base class B of X has a copy assignment operator
2088 // whose parameter is of type const B&, const volatile B& or B,
2089 // and
2090 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2091 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002092 assert(!Base->getType()->isDependentType() &&
2093 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002094 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002095 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002096 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002097 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002098 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002099 }
2100
2101 // -- for all the nonstatic data members of X that are of a class
2102 // type M (or array thereof), each such class type has a copy
2103 // assignment operator whose parameter is of type const M&,
2104 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002105 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2106 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002107 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002108 QualType FieldType = (*Field)->getType();
2109 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2110 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002111 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002112 const CXXRecordDecl *FieldClassDecl
2113 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002114 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002115 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002116 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002117 }
2118 }
2119
2120 // Otherwise, the implicitly declared copy assignment operator will
2121 // have the form
2122 //
2123 // X& X::operator=(X&)
2124 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002125 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002126 if (HasConstCopyAssignment)
2127 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002128 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002129
2130 // An implicitly-declared copy assignment operator is an inline public
2131 // member of its class.
2132 DeclarationName Name =
2133 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2134 CXXMethodDecl *CopyAssignment =
2135 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2136 Context.getFunctionType(RetType, &ArgType, 1,
2137 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002138 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002139 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002140 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002141 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002142 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002143
2144 // Add the parameter to the operator.
2145 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2146 ClassDecl->getLocation(),
2147 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002148 ArgType, /*DInfo=*/0,
2149 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002150 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002151
2152 // Don't call addedAssignmentOperator. There is no way to distinguish an
2153 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002154 ClassDecl->addDecl(CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002155 }
2156
Douglas Gregor1349b452008-12-15 21:24:18 +00002157 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002158 // C++ [class.dtor]p2:
2159 // If a class has no user-declared destructor, a destructor is
2160 // declared implicitly. An implicitly-declared destructor is an
2161 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002162 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002163 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002164 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002165 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002166 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002167 Context.getFunctionType(Context.VoidTy,
2168 0, 0, false, 0),
2169 /*isInline=*/true,
2170 /*isImplicitlyDeclared=*/true);
2171 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002172 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002173 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002174 ClassDecl->addDecl(Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002175 }
Douglas Gregor05379422008-11-03 17:51:48 +00002176}
2177
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002178void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002179 Decl *D = TemplateD.getAs<Decl>();
2180 if (!D)
2181 return;
2182
2183 TemplateParameterList *Params = 0;
2184 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2185 Params = Template->getTemplateParameters();
2186 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2187 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2188 Params = PartialSpec->getTemplateParameters();
2189 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002190 return;
2191
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002192 for (TemplateParameterList::iterator Param = Params->begin(),
2193 ParamEnd = Params->end();
2194 Param != ParamEnd; ++Param) {
2195 NamedDecl *Named = cast<NamedDecl>(*Param);
2196 if (Named->getDeclName()) {
2197 S->AddDecl(DeclPtrTy::make(Named));
2198 IdResolver.AddDecl(Named);
2199 }
2200 }
2201}
2202
Douglas Gregor4d87df52008-12-16 21:30:33 +00002203/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2204/// parsing a top-level (non-nested) C++ class, and we are now
2205/// parsing those parts of the given Method declaration that could
2206/// not be parsed earlier (C++ [class.mem]p2), such as default
2207/// arguments. This action should enter the scope of the given
2208/// Method declaration as if we had just parsed the qualified method
2209/// name. However, it should not bring the parameters into scope;
2210/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002211void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002212 if (!MethodD)
2213 return;
Mike Stump11289f42009-09-09 15:08:12 +00002214
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002215 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002216
Douglas Gregor4d87df52008-12-16 21:30:33 +00002217 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002218 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002219 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002220 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2221 SS.setScopeRep(
2222 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002223 ActOnCXXEnterDeclaratorScope(S, SS);
2224}
2225
2226/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2227/// C++ method declaration. We're (re-)introducing the given
2228/// function parameter into scope for use in parsing later parts of
2229/// the method declaration. For example, we could see an
2230/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002231void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002232 if (!ParamD)
2233 return;
Mike Stump11289f42009-09-09 15:08:12 +00002234
Chris Lattner83f095c2009-03-28 19:18:32 +00002235 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002236
2237 // If this parameter has an unparsed default argument, clear it out
2238 // to make way for the parsed default argument.
2239 if (Param->hasUnparsedDefaultArg())
2240 Param->setDefaultArg(0);
2241
Chris Lattner83f095c2009-03-28 19:18:32 +00002242 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002243 if (Param->getDeclName())
2244 IdResolver.AddDecl(Param);
2245}
2246
2247/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2248/// processing the delayed method declaration for Method. The method
2249/// declaration is now considered finished. There may be a separate
2250/// ActOnStartOfFunctionDef action later (not necessarily
2251/// immediately!) for this method, if it was also defined inside the
2252/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002253void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002254 if (!MethodD)
2255 return;
Mike Stump11289f42009-09-09 15:08:12 +00002256
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002257 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattner83f095c2009-03-28 19:18:32 +00002259 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002260 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002261 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002262 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2263 SS.setScopeRep(
2264 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002265 ActOnCXXExitDeclaratorScope(S, SS);
2266
2267 // Now that we have our default arguments, check the constructor
2268 // again. It could produce additional diagnostics or affect whether
2269 // the class has implicitly-declared destructors, among other
2270 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2272 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002273
2274 // Check the default arguments, which we may have added.
2275 if (!Method->isInvalidDecl())
2276 CheckCXXDefaultArguments(Method);
2277}
2278
Douglas Gregor831c93f2008-11-05 20:51:48 +00002279/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002280/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002281/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002282/// emit diagnostics and set the invalid bit to true. In any case, the type
2283/// will be updated to reflect a well-formed type for the constructor and
2284/// returned.
2285QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2286 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002287 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002288
2289 // C++ [class.ctor]p3:
2290 // A constructor shall not be virtual (10.3) or static (9.4). A
2291 // constructor can be invoked for a const, volatile or const
2292 // volatile object. A constructor shall not be declared const,
2293 // volatile, or const volatile (9.3.2).
2294 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002295 if (!D.isInvalidType())
2296 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2297 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2298 << SourceRange(D.getIdentifierLoc());
2299 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002300 }
2301 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002302 if (!D.isInvalidType())
2303 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2304 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2305 << SourceRange(D.getIdentifierLoc());
2306 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002307 SC = FunctionDecl::None;
2308 }
Mike Stump11289f42009-09-09 15:08:12 +00002309
Chris Lattner38378bf2009-04-25 08:28:21 +00002310 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2311 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002312 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2314 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002315 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002316 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2317 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002318 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002319 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2320 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002321 }
Mike Stump11289f42009-09-09 15:08:12 +00002322
Douglas Gregor831c93f2008-11-05 20:51:48 +00002323 // Rebuild the function type "R" without any type qualifiers (in
2324 // case any of the errors above fired) and with "void" as the
2325 // return type, since constructors don't have return types. We
2326 // *always* have to do this, because GetTypeForDeclarator will
2327 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002328 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002329 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2330 Proto->getNumArgs(),
2331 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002332}
2333
Douglas Gregor4d87df52008-12-16 21:30:33 +00002334/// CheckConstructor - Checks a fully-formed constructor for
2335/// well-formedness, issuing any diagnostics required. Returns true if
2336/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002337void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002338 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002339 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2340 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002341 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002342
2343 // C++ [class.copy]p3:
2344 // A declaration of a constructor for a class X is ill-formed if
2345 // its first parameter is of type (optionally cv-qualified) X and
2346 // either there are no other parameters or else all other
2347 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002348 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002349 ((Constructor->getNumParams() == 1) ||
2350 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002351 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2352 Constructor->getTemplateSpecializationKind()
2353 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002354 QualType ParamType = Constructor->getParamDecl(0)->getType();
2355 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2356 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002357 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2358 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002359 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002360
2361 // FIXME: Rather that making the constructor invalid, we should endeavor
2362 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002363 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002364 }
2365 }
Mike Stump11289f42009-09-09 15:08:12 +00002366
Douglas Gregor4d87df52008-12-16 21:30:33 +00002367 // Notify the class that we've added a constructor.
2368 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002369}
2370
Mike Stump11289f42009-09-09 15:08:12 +00002371static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002372FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2373 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2374 FTI.ArgInfo[0].Param &&
2375 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2376}
2377
Douglas Gregor831c93f2008-11-05 20:51:48 +00002378/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2379/// the well-formednes of the destructor declarator @p D with type @p
2380/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002381/// emit diagnostics and set the declarator to invalid. Even if this happens,
2382/// will be updated to reflect a well-formed type for the destructor and
2383/// returned.
2384QualType Sema::CheckDestructorDeclarator(Declarator &D,
2385 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002386 // C++ [class.dtor]p1:
2387 // [...] A typedef-name that names a class is a class-name
2388 // (7.1.3); however, a typedef-name that names a class shall not
2389 // be used as the identifier in the declarator for a destructor
2390 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002391 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002392 if (isa<TypedefType>(DeclaratorType)) {
2393 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002394 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002395 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002396 }
2397
2398 // C++ [class.dtor]p2:
2399 // A destructor is used to destroy objects of its class type. A
2400 // destructor takes no parameters, and no return type can be
2401 // specified for it (not even void). The address of a destructor
2402 // shall not be taken. A destructor shall not be static. A
2403 // destructor can be invoked for a const, volatile or const
2404 // volatile object. A destructor shall not be declared const,
2405 // volatile or const volatile (9.3.2).
2406 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002407 if (!D.isInvalidType())
2408 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2409 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2410 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002411 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002412 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002413 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002414 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002415 // Destructors don't have return types, but the parser will
2416 // happily parse something like:
2417 //
2418 // class X {
2419 // float ~X();
2420 // };
2421 //
2422 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002423 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2424 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2425 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002426 }
Mike Stump11289f42009-09-09 15:08:12 +00002427
Chris Lattner38378bf2009-04-25 08:28:21 +00002428 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2429 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002430 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002431 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2432 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002433 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002434 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2435 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002436 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002437 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2438 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002439 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002440 }
2441
2442 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002443 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002444 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2445
2446 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002447 FTI.freeArgs();
2448 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002449 }
2450
Mike Stump11289f42009-09-09 15:08:12 +00002451 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002452 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002453 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002454 D.setInvalidType();
2455 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002456
2457 // Rebuild the function type "R" without any type qualifiers or
2458 // parameters (in case any of the errors above fired) and with
2459 // "void" as the return type, since destructors don't have return
2460 // types. We *always* have to do this, because GetTypeForDeclarator
2461 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002462 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002463}
2464
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002465/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2466/// well-formednes of the conversion function declarator @p D with
2467/// type @p R. If there are any errors in the declarator, this routine
2468/// will emit diagnostics and return true. Otherwise, it will return
2469/// false. Either way, the type @p R will be updated to reflect a
2470/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002471void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002472 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002473 // C++ [class.conv.fct]p1:
2474 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002475 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002476 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002477 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002478 if (!D.isInvalidType())
2479 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2480 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2481 << SourceRange(D.getIdentifierLoc());
2482 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002483 SC = FunctionDecl::None;
2484 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002485 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002486 // Conversion functions don't have return types, but the parser will
2487 // happily parse something like:
2488 //
2489 // class X {
2490 // float operator bool();
2491 // };
2492 //
2493 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002494 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2495 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2496 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002497 }
2498
2499 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002500 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002501 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2502
2503 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002504 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002505 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002506 }
2507
Mike Stump11289f42009-09-09 15:08:12 +00002508 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002509 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002510 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002511 D.setInvalidType();
2512 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002513
2514 // C++ [class.conv.fct]p4:
2515 // The conversion-type-id shall not represent a function type nor
2516 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002517 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002518 if (ConvType->isArrayType()) {
2519 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2520 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002521 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002522 } else if (ConvType->isFunctionType()) {
2523 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2524 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002525 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002526 }
2527
2528 // Rebuild the function type "R" without any parameters (in case any
2529 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002530 // return type.
2531 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002532 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002533
Douglas Gregor5fb53972009-01-14 15:45:31 +00002534 // C++0x explicit conversion operators.
2535 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002536 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002537 diag::warn_explicit_conversion_functions)
2538 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002539}
2540
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002541/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2542/// the declaration of the given C++ conversion function. This routine
2543/// is responsible for recording the conversion function in the C++
2544/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002545Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002546 assert(Conversion && "Expected to receive a conversion function declaration");
2547
Douglas Gregor4287b372008-12-12 08:25:50 +00002548 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002549
2550 // Make sure we aren't redeclaring the conversion function.
2551 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002552
2553 // C++ [class.conv.fct]p1:
2554 // [...] A conversion function is never used to convert a
2555 // (possibly cv-qualified) object to the (possibly cv-qualified)
2556 // same object type (or a reference to it), to a (possibly
2557 // cv-qualified) base class of that type (or a reference to it),
2558 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002559 // FIXME: Suppress this warning if the conversion function ends up being a
2560 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002561 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002562 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002563 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002564 ConvType = ConvTypeRef->getPointeeType();
2565 if (ConvType->isRecordType()) {
2566 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2567 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002568 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002569 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002570 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002571 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002572 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002573 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002574 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002575 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002576 }
2577
Douglas Gregor1dc98262008-12-26 15:00:45 +00002578 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002579 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002580 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002581 = Conversion->getDescribedFunctionTemplate())
2582 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor1dc98262008-12-26 15:00:45 +00002583 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002584 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor1dc98262008-12-26 15:00:45 +00002585 Conv = Conversions->function_begin(),
2586 ConvEnd = Conversions->function_end();
2587 Conv != ConvEnd; ++Conv) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002588 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor1dc98262008-12-26 15:00:45 +00002589 *Conv = Conversion;
Chris Lattner83f095c2009-03-28 19:18:32 +00002590 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002591 }
2592 }
2593 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002594 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002595 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002596 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002597 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002598 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002599
Chris Lattner83f095c2009-03-28 19:18:32 +00002600 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002601}
2602
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002603//===----------------------------------------------------------------------===//
2604// Namespace Handling
2605//===----------------------------------------------------------------------===//
2606
2607/// ActOnStartNamespaceDef - This is called at the start of a namespace
2608/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002609Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2610 SourceLocation IdentLoc,
2611 IdentifierInfo *II,
2612 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002613 NamespaceDecl *Namespc =
2614 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2615 Namespc->setLBracLoc(LBrace);
2616
2617 Scope *DeclRegionScope = NamespcScope->getParent();
2618
2619 if (II) {
2620 // C++ [namespace.def]p2:
2621 // The identifier in an original-namespace-definition shall not have been
2622 // previously defined in the declarative region in which the
2623 // original-namespace-definition appears. The identifier in an
2624 // original-namespace-definition is the name of the namespace. Subsequently
2625 // in that declarative region, it is treated as an original-namespace-name.
2626
John McCall9f3059a2009-10-09 21:13:30 +00002627 NamedDecl *PrevDecl
2628 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump11289f42009-09-09 15:08:12 +00002629
Douglas Gregor91f84212008-12-11 16:49:14 +00002630 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2631 // This is an extended namespace definition.
2632 // Attach this namespace decl to the chain of extended namespace
2633 // definitions.
2634 OrigNS->setNextNamespace(Namespc);
2635 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002636
Mike Stump11289f42009-09-09 15:08:12 +00002637 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002638 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002639 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002640 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002641 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002642 } else if (PrevDecl) {
2643 // This is an invalid name redefinition.
2644 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2645 << Namespc->getDeclName();
2646 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2647 Namespc->setInvalidDecl();
2648 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002649 } else if (II->isStr("std") &&
2650 CurContext->getLookupContext()->isTranslationUnit()) {
2651 // This is the first "real" definition of the namespace "std", so update
2652 // our cache of the "std" namespace to point at this definition.
2653 if (StdNamespace) {
2654 // We had already defined a dummy namespace "std". Link this new
2655 // namespace definition to the dummy namespace "std".
2656 StdNamespace->setNextNamespace(Namespc);
2657 StdNamespace->setLocation(IdentLoc);
2658 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2659 }
2660
2661 // Make our StdNamespace cache point at the first real definition of the
2662 // "std" namespace.
2663 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002664 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002665
2666 PushOnScopeChains(Namespc, DeclRegionScope);
2667 } else {
John McCall4fa53422009-10-01 00:25:31 +00002668 // Anonymous namespaces.
2669
2670 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2671 // behaves as if it were replaced by
2672 // namespace unique { /* empty body */ }
2673 // using namespace unique;
2674 // namespace unique { namespace-body }
2675 // where all occurrences of 'unique' in a translation unit are
2676 // replaced by the same identifier and this identifier differs
2677 // from all other identifiers in the entire program.
2678
2679 // We just create the namespace with an empty name and then add an
2680 // implicit using declaration, just like the standard suggests.
2681 //
2682 // CodeGen enforces the "universally unique" aspect by giving all
2683 // declarations semantically contained within an anonymous
2684 // namespace internal linkage.
2685
2686 assert(Namespc->isAnonymousNamespace());
2687 CurContext->addDecl(Namespc);
2688
2689 UsingDirectiveDecl* UD
2690 = UsingDirectiveDecl::Create(Context, CurContext,
2691 /* 'using' */ LBrace,
2692 /* 'namespace' */ SourceLocation(),
2693 /* qualifier */ SourceRange(),
2694 /* NNS */ NULL,
2695 /* identifier */ SourceLocation(),
2696 Namespc,
2697 /* Ancestor */ CurContext);
2698 UD->setImplicit();
2699 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002700 }
2701
2702 // Although we could have an invalid decl (i.e. the namespace name is a
2703 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002704 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2705 // for the namespace has the declarations that showed up in that particular
2706 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002707 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002708 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002709}
2710
2711/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2712/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002713void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2714 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002715 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2716 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2717 Namespc->setRBracLoc(RBrace);
2718 PopDeclContext();
2719}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002720
Chris Lattner83f095c2009-03-28 19:18:32 +00002721Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2722 SourceLocation UsingLoc,
2723 SourceLocation NamespcLoc,
2724 const CXXScopeSpec &SS,
2725 SourceLocation IdentLoc,
2726 IdentifierInfo *NamespcName,
2727 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002728 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2729 assert(NamespcName && "Invalid NamespcName.");
2730 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002731 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002732
Douglas Gregor889ceb72009-02-03 19:21:40 +00002733 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002734
Douglas Gregor34074322009-01-14 22:20:51 +00002735 // Lookup namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002736 LookupResult R;
2737 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002738 if (R.isAmbiguous()) {
2739 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002740 return DeclPtrTy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002741 }
John McCall9f3059a2009-10-09 21:13:30 +00002742 if (!R.empty()) {
2743 NamedDecl *NS = R.getFoundDecl();
Douglas Gregorbf3f3222009-11-14 03:27:21 +00002744 // FIXME: Namespace aliases!
Douglas Gregord7c4d982008-12-30 03:27:21 +00002745 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002746 // C++ [namespace.udir]p1:
2747 // A using-directive specifies that the names in the nominated
2748 // namespace can be used in the scope in which the
2749 // using-directive appears after the using-directive. During
2750 // unqualified name lookup (3.4.1), the names appear as if they
2751 // were declared in the nearest enclosing namespace which
2752 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002753 // namespace. [Note: in this context, "contains" means "contains
2754 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002755
2756 // Find enclosing context containing both using-directive and
2757 // nominated namespace.
2758 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2759 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2760 CommonAncestor = CommonAncestor->getParent();
2761
Mike Stump11289f42009-09-09 15:08:12 +00002762 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002763 CurContext, UsingLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002764 NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002765 SS.getRange(),
2766 (NestedNameSpecifier *)SS.getScopeRep(),
2767 IdentLoc,
Douglas Gregor889ceb72009-02-03 19:21:40 +00002768 cast<NamespaceDecl>(NS),
2769 CommonAncestor);
2770 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002771 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002772 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002773 }
2774
Douglas Gregor889ceb72009-02-03 19:21:40 +00002775 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002776 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002777 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002778}
2779
2780void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2781 // If scope has associated entity, then using directive is at namespace
2782 // or translation unit scope. We add UsingDirectiveDecls, into
2783 // it's lookup structure.
2784 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002785 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002786 else
2787 // Otherwise it is block-sope. using-directives will affect lookup
2788 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002789 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002790}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002791
Douglas Gregorfec52632009-06-20 00:51:54 +00002792
2793Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002794 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002795 SourceLocation UsingLoc,
2796 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002797 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002798 AttributeList *AttrList,
2799 bool IsTypeName) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002800 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002801
Douglas Gregor220f4272009-11-04 16:30:06 +00002802 switch (Name.getKind()) {
2803 case UnqualifiedId::IK_Identifier:
2804 case UnqualifiedId::IK_OperatorFunctionId:
2805 case UnqualifiedId::IK_ConversionFunctionId:
2806 break;
2807
2808 case UnqualifiedId::IK_ConstructorName:
2809 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2810 << SS.getRange();
2811 return DeclPtrTy();
2812
2813 case UnqualifiedId::IK_DestructorName:
2814 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2815 << SS.getRange();
2816 return DeclPtrTy();
2817
2818 case UnqualifiedId::IK_TemplateId:
2819 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2820 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2821 return DeclPtrTy();
2822 }
2823
2824 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2825 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2826 Name.getSourceRange().getBegin(),
2827 TargetName, AttrList, IsTypeName);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002828 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002829 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002830 UD->setAccess(AS);
2831 }
Mike Stump11289f42009-09-09 15:08:12 +00002832
Anders Carlsson696a3f12009-08-28 05:40:36 +00002833 return DeclPtrTy::make(UD);
2834}
2835
2836NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2837 const CXXScopeSpec &SS,
2838 SourceLocation IdentLoc,
2839 DeclarationName Name,
2840 AttributeList *AttrList,
2841 bool IsTypeName) {
2842 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2843 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002844
Anders Carlssonf038fc22009-08-28 05:49:21 +00002845 // FIXME: We ignore attributes for now.
2846 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002847
Anders Carlsson59140b32009-08-28 03:16:11 +00002848 if (SS.isEmpty()) {
2849 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002850 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002851 }
Mike Stump11289f42009-09-09 15:08:12 +00002852
2853 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002854 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2855
John McCall84c16cf2009-11-12 03:15:40 +00002856 DeclContext *LookupContext = computeDeclContext(SS);
2857 if (!LookupContext) {
Anders Carlssonf038fc22009-08-28 05:49:21 +00002858 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2859 SS.getRange(), NNS,
2860 IdentLoc, Name, IsTypeName);
2861 }
Mike Stump11289f42009-09-09 15:08:12 +00002862
Anders Carlsson59140b32009-08-28 03:16:11 +00002863 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2864 // C++0x N2914 [namespace.udecl]p3:
2865 // A using-declaration used as a member-declaration shall refer to a member
2866 // of a base class of the class being defined, shall refer to a member of an
2867 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002868 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002869 // a member of a base class of the class being defined.
John McCall84c16cf2009-11-12 03:15:40 +00002870
2871 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2872 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlsson59140b32009-08-28 03:16:11 +00002873 Diag(SS.getRange().getBegin(),
2874 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2875 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002876 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002877 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002878 } else {
2879 // C++0x N2914 [namespace.udecl]p8:
2880 // A using-declaration for a class member shall be a member-declaration.
John McCall84c16cf2009-11-12 03:15:40 +00002881 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002882 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002883 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002884 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002885 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002886 }
2887
Douglas Gregorfec52632009-06-20 00:51:54 +00002888 // Lookup target name.
John McCall9f3059a2009-10-09 21:13:30 +00002889 LookupResult R;
2890 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +00002891
John McCall9f3059a2009-10-09 21:13:30 +00002892 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00002893 Diag(IdentLoc, diag::err_no_member)
2894 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002895 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002896 }
2897
John McCall9f3059a2009-10-09 21:13:30 +00002898 // FIXME: handle ambiguity?
2899 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002900
Anders Carlsson59140b32009-08-28 03:16:11 +00002901 if (IsTypeName && !isa<TypeDecl>(ND)) {
2902 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002903 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002904 }
2905
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002906 // C++0x N2914 [namespace.udecl]p6:
2907 // A using-declaration shall not name a namespace.
2908 if (isa<NamespaceDecl>(ND)) {
2909 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2910 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002911 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002912 }
Mike Stump11289f42009-09-09 15:08:12 +00002913
Anders Carlsson696a3f12009-08-28 05:40:36 +00002914 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2915 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregorfec52632009-06-20 00:51:54 +00002916}
2917
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002918/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2919/// is a namespace alias, returns the namespace it points to.
2920static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2921 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2922 return AD->getNamespace();
2923 return dyn_cast_or_null<NamespaceDecl>(D);
2924}
2925
Mike Stump11289f42009-09-09 15:08:12 +00002926Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002927 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002928 SourceLocation AliasLoc,
2929 IdentifierInfo *Alias,
2930 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002931 SourceLocation IdentLoc,
2932 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00002933
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002934 // Lookup the namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002935 LookupResult R;
2936 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002937
Anders Carlssondca83c42009-03-28 06:23:46 +00002938 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002939 if (NamedDecl *PrevDecl
2940 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002941 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00002942 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002943 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00002944 if (!R.isAmbiguous() && !R.empty() &&
2945 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002946 return DeclPtrTy();
2947 }
Mike Stump11289f42009-09-09 15:08:12 +00002948
Anders Carlssondca83c42009-03-28 06:23:46 +00002949 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2950 diag::err_redefinition_different_kind;
2951 Diag(AliasLoc, DiagID) << Alias;
2952 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00002953 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00002954 }
2955
Anders Carlssonac2c9652009-03-28 06:42:02 +00002956 if (R.isAmbiguous()) {
Anders Carlsson47952ae2009-03-28 22:53:22 +00002957 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002958 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002959 }
Mike Stump11289f42009-09-09 15:08:12 +00002960
John McCall9f3059a2009-10-09 21:13:30 +00002961 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00002962 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00002963 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002964 }
Mike Stump11289f42009-09-09 15:08:12 +00002965
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002966 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00002967 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2968 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00002969 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00002970 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002971
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002972 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002973 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00002974}
2975
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002976void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2977 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00002978 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2979 !Constructor->isUsed()) &&
2980 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002981
Eli Friedman9cf6b592009-11-09 19:20:36 +00002982 CXXRecordDecl *ClassDecl
2983 = cast<CXXRecordDecl>(Constructor->getDeclContext());
2984 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00002985
Eli Friedman9cf6b592009-11-09 19:20:36 +00002986 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
2987 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
2988 << Context.getTagDeclType(ClassDecl);
2989 Constructor->setInvalidDecl();
2990 } else {
2991 Constructor->setUsed();
2992 }
Eli Friedmand7686ef2009-11-09 01:05:47 +00002993 return;
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002994}
2995
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002996void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00002997 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002998 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2999 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump11289f42009-09-09 15:08:12 +00003000
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003001 CXXRecordDecl *ClassDecl
3002 = cast<CXXRecordDecl>(Destructor->getDeclContext());
3003 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3004 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003005 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003006 // implicitly defined, all the implicitly-declared default destructors
3007 // for its base class and its non-static data members shall have been
3008 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003009 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3010 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003011 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003012 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003013 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003014 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003015 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3016 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3017 else
Mike Stump11289f42009-09-09 15:08:12 +00003018 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003019 "DefineImplicitDestructor - missing dtor in a base class");
3020 }
3021 }
Mike Stump11289f42009-09-09 15:08:12 +00003022
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003023 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3024 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003025 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3026 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3027 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003028 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003029 CXXRecordDecl *FieldClassDecl
3030 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3031 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003032 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003033 const_cast<CXXDestructorDecl*>(
3034 FieldClassDecl->getDestructor(Context)))
3035 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3036 else
Mike Stump11289f42009-09-09 15:08:12 +00003037 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003038 "DefineImplicitDestructor - missing dtor in class of a data member");
3039 }
3040 }
3041 }
3042 Destructor->setUsed();
3043}
3044
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003045void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3046 CXXMethodDecl *MethodDecl) {
3047 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3048 MethodDecl->getOverloadedOperator() == OO_Equal &&
3049 !MethodDecl->isUsed()) &&
3050 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003051
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003052 CXXRecordDecl *ClassDecl
3053 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003054
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003055 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003056 // Before the implicitly-declared copy assignment operator for a class is
3057 // implicitly defined, all implicitly-declared copy assignment operators
3058 // for its direct base classes and its nonstatic data members shall have
3059 // been implicitly defined.
3060 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003061 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3062 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003063 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003064 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003065 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003066 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3067 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3068 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003069 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3070 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003071 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3072 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3073 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003074 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003075 CXXRecordDecl *FieldClassDecl
3076 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003077 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003078 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3079 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003080 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003081 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003082 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3083 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003084 Diag(CurrentLocation, diag::note_first_required_here);
3085 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003086 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003087 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003088 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3089 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003090 Diag(CurrentLocation, diag::note_first_required_here);
3091 err = true;
3092 }
3093 }
3094 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003095 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003096}
3097
3098CXXMethodDecl *
3099Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3100 CXXRecordDecl *ClassDecl) {
3101 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3102 QualType RHSType(LHSType);
3103 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003104 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003105 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003106 RHSType = Context.getCVRQualifiedType(RHSType,
3107 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003108 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3109 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003110 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003111 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3112 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003113 SourceLocation()));
3114 Expr *Args[2] = { &*LHS, &*RHS };
3115 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003116 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003117 CandidateSet);
3118 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003119 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003120 ClassDecl->getLocation(), Best) == OR_Success)
3121 return cast<CXXMethodDecl>(Best->Function);
3122 assert(false &&
3123 "getAssignOperatorMethod - copy assignment operator method not found");
3124 return 0;
3125}
3126
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003127void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3128 CXXConstructorDecl *CopyConstructor,
3129 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003130 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003131 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3132 !CopyConstructor->isUsed()) &&
3133 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003134
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003135 CXXRecordDecl *ClassDecl
3136 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3137 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003138 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003139 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003140 // implicitly defined, all the implicitly-declared copy constructors
3141 // for its base class and its non-static data members shall have been
3142 // implicitly defined.
3143 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3144 Base != ClassDecl->bases_end(); ++Base) {
3145 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003146 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003147 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003148 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003149 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003150 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003151 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3152 FieldEnd = ClassDecl->field_end();
3153 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003154 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3155 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3156 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003157 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003158 CXXRecordDecl *FieldClassDecl
3159 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003160 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003161 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003162 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003163 }
3164 }
3165 CopyConstructor->setUsed();
3166}
3167
Anders Carlsson6eb55572009-08-25 05:12:04 +00003168Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003169Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003170 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003171 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003172 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003173
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003174 // C++ [class.copy]p15:
3175 // Whenever a temporary class object is copied using a copy constructor, and
3176 // this object and the copy have the same cv-unqualified type, an
3177 // implementation is permitted to treat the original and the copy as two
3178 // different ways of referring to the same object and not perform a copy at
3179 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003180
Anders Carlsson250aada2009-08-16 05:13:48 +00003181 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003182 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003183 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003184 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3185 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003186 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3187 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3188 E = ICE->getSubExpr();
3189
Anders Carlsson250aada2009-08-16 05:13:48 +00003190 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3191 Elidable = true;
3192 }
Mike Stump11289f42009-09-09 15:08:12 +00003193
3194 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003195 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003196}
3197
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003198/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3199/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003200Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003201Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3202 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003203 MultiExprArg ExprArgs) {
3204 unsigned NumExprs = ExprArgs.size();
3205 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003206
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003207 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3208 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003209}
3210
Anders Carlsson574315a2009-08-27 05:08:22 +00003211Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003212Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3213 QualType Ty,
3214 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003215 MultiExprArg Args,
3216 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003217 unsigned NumExprs = Args.size();
3218 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003219
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003220 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3221 TyBeginLoc, Exprs,
3222 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003223}
3224
3225
Mike Stump11289f42009-09-09 15:08:12 +00003226bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003227 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003228 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003229 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003230 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003231 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003232 if (TempResult.isInvalid())
3233 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003234
Anders Carlsson6eb55572009-08-25 05:12:04 +00003235 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003236 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003237 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003238 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003239
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003240 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003241}
3242
Mike Stump11289f42009-09-09 15:08:12 +00003243void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003244 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003245 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003246 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003247 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003248 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003249 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003250}
3251
Mike Stump11289f42009-09-09 15:08:12 +00003252/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003253/// ActOnDeclarator, when a C++ direct initializer is present.
3254/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003255void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3256 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003257 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003258 SourceLocation *CommaLocs,
3259 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003260 unsigned NumExprs = Exprs.size();
3261 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003262 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003263
3264 // If there is no declaration, there was an error parsing it. Just ignore
3265 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003266 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003267 return;
Mike Stump11289f42009-09-09 15:08:12 +00003268
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003269 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3270 if (!VDecl) {
3271 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3272 RealDecl->setInvalidDecl();
3273 return;
3274 }
3275
Douglas Gregor402250f2009-08-26 21:14:46 +00003276 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003277 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003278 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3279 //
3280 // Clients that want to distinguish between the two forms, can check for
3281 // direct initializer using VarDecl::hasCXXDirectInitializer().
3282 // A major benefit is that clients that don't particularly care about which
3283 // exactly form was it (like the CodeGen) can handle both cases without
3284 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003285
Douglas Gregor402250f2009-08-26 21:14:46 +00003286 // If either the declaration has a dependent type or if any of the expressions
3287 // is type-dependent, we represent the initialization via a ParenListExpr for
3288 // later use during template instantiation.
3289 if (VDecl->getType()->isDependentType() ||
3290 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3291 // Let clients know that initialization was done with a direct initializer.
3292 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003293
Douglas Gregor402250f2009-08-26 21:14:46 +00003294 // Store the initialization expressions as a ParenListExpr.
3295 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003296 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003297 new (Context) ParenListExpr(Context, LParenLoc,
3298 (Expr **)Exprs.release(),
3299 NumExprs, RParenLoc));
3300 return;
3301 }
Mike Stump11289f42009-09-09 15:08:12 +00003302
Douglas Gregor402250f2009-08-26 21:14:46 +00003303
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003304 // C++ 8.5p11:
3305 // The form of initialization (using parentheses or '=') is generally
3306 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003307 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003308 QualType DeclInitType = VDecl->getType();
3309 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003310 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003311
Douglas Gregor4044d992009-03-24 16:43:20 +00003312 // FIXME: This isn't the right place to complete the type.
3313 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3314 diag::err_typecheck_decl_incomplete_type)) {
3315 VDecl->setInvalidDecl();
3316 return;
3317 }
3318
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003319 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003320 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3321
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003322 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003323 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003324 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003325 VDecl->getLocation(),
3326 SourceRange(VDecl->getLocation(),
3327 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003328 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003329 IK_Direct,
3330 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003331 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003332 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003333 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003334 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003335 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003336 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003337 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003338 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003339 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003340 return;
3341 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003342
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003343 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003344 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3345 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003346 RealDecl->setInvalidDecl();
3347 return;
3348 }
3349
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003350 // Let clients know that initialization was done with a direct initializer.
3351 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003352
3353 assert(NumExprs == 1 && "Expected 1 expression");
3354 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003355 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3356 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003357}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003358
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003359/// \brief Add the applicable constructor candidates for an initialization
3360/// by constructor.
3361static void AddConstructorInitializationCandidates(Sema &SemaRef,
3362 QualType ClassType,
3363 Expr **Args,
3364 unsigned NumArgs,
3365 Sema::InitializationKind Kind,
3366 OverloadCandidateSet &CandidateSet) {
3367 // C++ [dcl.init]p14:
3368 // If the initialization is direct-initialization, or if it is
3369 // copy-initialization where the cv-unqualified version of the
3370 // source type is the same class as, or a derived class of, the
3371 // class of the destination, constructors are considered. The
3372 // applicable constructors are enumerated (13.3.1.3), and the
3373 // best one is chosen through overload resolution (13.3). The
3374 // constructor so selected is called to initialize the object,
3375 // with the initializer expression(s) as its argument(s). If no
3376 // constructor applies, or the overload resolution is ambiguous,
3377 // the initialization is ill-formed.
3378 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3379 assert(ClassRec && "Can only initialize a class type here");
3380
3381 // FIXME: When we decide not to synthesize the implicitly-declared
3382 // constructors, we'll need to make them appear here.
3383
3384 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3385 DeclarationName ConstructorName
3386 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3387 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3388 DeclContext::lookup_const_iterator Con, ConEnd;
3389 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3390 Con != ConEnd; ++Con) {
3391 // Find the constructor (which may be a template).
3392 CXXConstructorDecl *Constructor = 0;
3393 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3394 if (ConstructorTmpl)
3395 Constructor
3396 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3397 else
3398 Constructor = cast<CXXConstructorDecl>(*Con);
3399
3400 if ((Kind == Sema::IK_Direct) ||
3401 (Kind == Sema::IK_Copy &&
3402 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3403 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3404 if (ConstructorTmpl)
3405 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
3406 Args, NumArgs, CandidateSet);
3407 else
3408 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3409 }
3410 }
3411}
3412
3413/// \brief Attempt to perform initialization by constructor
3414/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3415/// copy-initialization.
3416///
3417/// This routine determines whether initialization by constructor is possible,
3418/// but it does not emit any diagnostics in the case where the initialization
3419/// is ill-formed.
3420///
3421/// \param ClassType the type of the object being initialized, which must have
3422/// class type.
3423///
3424/// \param Args the arguments provided to initialize the object
3425///
3426/// \param NumArgs the number of arguments provided to initialize the object
3427///
3428/// \param Kind the type of initialization being performed
3429///
3430/// \returns the constructor used to initialize the object, if successful.
3431/// Otherwise, emits a diagnostic and returns NULL.
3432CXXConstructorDecl *
3433Sema::TryInitializationByConstructor(QualType ClassType,
3434 Expr **Args, unsigned NumArgs,
3435 SourceLocation Loc,
3436 InitializationKind Kind) {
3437 // Build the overload candidate set
3438 OverloadCandidateSet CandidateSet;
3439 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3440 CandidateSet);
3441
3442 // Determine whether we found a constructor we can use.
3443 OverloadCandidateSet::iterator Best;
3444 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3445 case OR_Success:
3446 case OR_Deleted:
3447 // We found a constructor. Return it.
3448 return cast<CXXConstructorDecl>(Best->Function);
3449
3450 case OR_No_Viable_Function:
3451 case OR_Ambiguous:
3452 // Overload resolution failed. Return nothing.
3453 return 0;
3454 }
3455
3456 // Silence GCC warning
3457 return 0;
3458}
3459
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003460/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3461/// may occur as part of direct-initialization or copy-initialization.
3462///
3463/// \param ClassType the type of the object being initialized, which must have
3464/// class type.
3465///
3466/// \param ArgsPtr the arguments provided to initialize the object
3467///
3468/// \param Loc the source location where the initialization occurs
3469///
3470/// \param Range the source range that covers the entire initialization
3471///
3472/// \param InitEntity the name of the entity being initialized, if known
3473///
3474/// \param Kind the type of initialization being performed
3475///
3476/// \param ConvertedArgs a vector that will be filled in with the
3477/// appropriately-converted arguments to the constructor (if initialization
3478/// succeeded).
3479///
3480/// \returns the constructor used to initialize the object, if successful.
3481/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003482CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003483Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003484 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003485 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003486 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003487 InitializationKind Kind,
3488 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003489
3490 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003491 Expr **Args = (Expr **)ArgsPtr.get();
3492 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003493 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003494 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3495 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00003496
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003497 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003498 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003499 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003500 // We found a constructor. Break out so that we can convert the arguments
3501 // appropriately.
3502 break;
Mike Stump11289f42009-09-09 15:08:12 +00003503
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003504 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003505 if (InitEntity)
3506 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003507 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003508 else
3509 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003510 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003511 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003512 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003513
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003514 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003515 if (InitEntity)
3516 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3517 else
3518 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003519 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3520 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003521
3522 case OR_Deleted:
3523 if (InitEntity)
3524 Diag(Loc, diag::err_ovl_deleted_init)
3525 << Best->Function->isDeleted()
3526 << InitEntity << Range;
3527 else
3528 Diag(Loc, diag::err_ovl_deleted_init)
3529 << Best->Function->isDeleted()
3530 << InitEntity << Range;
3531 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3532 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003533 }
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003535 // Convert the arguments, fill in default arguments, etc.
3536 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3537 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3538 return 0;
3539
3540 return Constructor;
3541}
3542
3543/// \brief Given a constructor and the set of arguments provided for the
3544/// constructor, convert the arguments and add any required default arguments
3545/// to form a proper call to this constructor.
3546///
3547/// \returns true if an error occurred, false otherwise.
3548bool
3549Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3550 MultiExprArg ArgsPtr,
3551 SourceLocation Loc,
3552 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3553 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3554 unsigned NumArgs = ArgsPtr.size();
3555 Expr **Args = (Expr **)ArgsPtr.get();
3556
3557 const FunctionProtoType *Proto
3558 = Constructor->getType()->getAs<FunctionProtoType>();
3559 assert(Proto && "Constructor without a prototype?");
3560 unsigned NumArgsInProto = Proto->getNumArgs();
3561 unsigned NumArgsToCheck = NumArgs;
3562
3563 // If too few arguments are available, we'll fill in the rest with defaults.
3564 if (NumArgs < NumArgsInProto) {
3565 NumArgsToCheck = NumArgsInProto;
3566 ConvertedArgs.reserve(NumArgsInProto);
3567 } else {
3568 ConvertedArgs.reserve(NumArgs);
3569 if (NumArgs > NumArgsInProto)
3570 NumArgsToCheck = NumArgsInProto;
3571 }
3572
3573 // Convert arguments
3574 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3575 QualType ProtoArgType = Proto->getArgType(i);
3576
3577 Expr *Arg;
3578 if (i < NumArgs) {
3579 Arg = Args[i];
Anders Carlssonc8bfc462009-09-15 21:14:33 +00003580
3581 // Pass the argument.
3582 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3583 return true;
3584
3585 Args[i] = 0;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003586 } else {
3587 ParmVarDecl *Param = Constructor->getParamDecl(i);
3588
3589 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3590 if (DefArg.isInvalid())
3591 return true;
3592
3593 Arg = DefArg.takeAs<Expr>();
3594 }
3595
3596 ConvertedArgs.push_back(Arg);
3597 }
3598
3599 // If this is a variadic call, handle args passed through "...".
3600 if (Proto->isVariadic()) {
3601 // Promote the arguments (C99 6.5.2.2p7).
3602 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3603 Expr *Arg = Args[i];
3604 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3605 return true;
3606
3607 ConvertedArgs.push_back(Arg);
3608 Args[i] = 0;
3609 }
3610 }
3611
3612 return false;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003613}
3614
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003615/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3616/// determine whether they are reference-related,
3617/// reference-compatible, reference-compatible with added
3618/// qualification, or incompatible, for use in C++ initialization by
3619/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3620/// type, and the first type (T1) is the pointee type of the reference
3621/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003622Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003623Sema::CompareReferenceRelationship(SourceLocation Loc,
3624 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003625 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003626 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003627 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003628 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003629
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003630 QualType T1 = Context.getCanonicalType(OrigT1);
3631 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003632 QualType UnqualT1 = T1.getUnqualifiedType();
3633 QualType UnqualT2 = T2.getUnqualifiedType();
3634
3635 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003636 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003637 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003638 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003639 if (UnqualT1 == UnqualT2)
3640 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003641 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3642 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3643 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003644 DerivedToBase = true;
3645 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003646 return Ref_Incompatible;
3647
3648 // At this point, we know that T1 and T2 are reference-related (at
3649 // least).
3650
3651 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003652 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003653 // reference-related to T2 and cv1 is the same cv-qualification
3654 // as, or greater cv-qualification than, cv2. For purposes of
3655 // overload resolution, cases for which cv1 is greater
3656 // cv-qualification than cv2 are identified as
3657 // reference-compatible with added qualification (see 13.3.3.2).
3658 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3659 return Ref_Compatible;
3660 else if (T1.isMoreQualifiedThan(T2))
3661 return Ref_Compatible_With_Added_Qualification;
3662 else
3663 return Ref_Related;
3664}
3665
3666/// CheckReferenceInit - Check the initialization of a reference
3667/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3668/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003669/// list), and DeclType is the type of the declaration. When ICS is
3670/// non-null, this routine will compute the implicit conversion
3671/// sequence according to C++ [over.ics.ref] and will not produce any
3672/// diagnostics; when ICS is null, it will emit diagnostics when any
3673/// errors are found. Either way, a return value of true indicates
3674/// that there was a failure, a return value of false indicates that
3675/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003676///
3677/// When @p SuppressUserConversions, user-defined conversions are
3678/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003679/// When @p AllowExplicit, we also permit explicit user-defined
3680/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003681/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00003682/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3683/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00003684bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003685Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003686 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003687 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003688 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00003689 ImplicitConversionSequence *ICS,
3690 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003691 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3692
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003693 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003694 QualType T2 = Init->getType();
3695
Douglas Gregorcd695e52008-11-10 20:40:00 +00003696 // If the initializer is the address of an overloaded function, try
3697 // to resolve the overloaded function. If all goes well, T2 is the
3698 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003699 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003700 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003701 ICS != 0);
3702 if (Fn) {
3703 // Since we're performing this reference-initialization for
3704 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003705 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003706 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003707 return true;
3708
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003709 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003710 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003711
3712 T2 = Fn->getType();
3713 }
3714 }
3715
Douglas Gregor786ab212008-10-29 02:00:59 +00003716 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003717 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003718 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003719 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3720 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003721 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003722 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003723
3724 // Most paths end in a failed conversion.
3725 if (ICS)
3726 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003727
3728 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003729 // A reference to type "cv1 T1" is initialized by an expression
3730 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003731
3732 // -- If the initializer expression
3733
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003734 // Rvalue references cannot bind to lvalues (N2812).
3735 // There is absolutely no situation where they can. In particular, note that
3736 // this is ill-formed, even if B has a user-defined conversion to A&&:
3737 // B b;
3738 // A&& r = b;
3739 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3740 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003741 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003742 << Init->getSourceRange();
3743 return true;
3744 }
3745
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003746 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003747 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3748 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003749 //
3750 // Note that the bit-field check is skipped if we are just computing
3751 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003752 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003753 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003754 BindsDirectly = true;
3755
Douglas Gregor786ab212008-10-29 02:00:59 +00003756 if (ICS) {
3757 // C++ [over.ics.ref]p1:
3758 // When a parameter of reference type binds directly (8.5.3)
3759 // to an argument expression, the implicit conversion sequence
3760 // is the identity conversion, unless the argument expression
3761 // has a type that is a derived class of the parameter type,
3762 // in which case the implicit conversion sequence is a
3763 // derived-to-base Conversion (13.3.3.1).
3764 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3765 ICS->Standard.First = ICK_Identity;
3766 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3767 ICS->Standard.Third = ICK_Identity;
3768 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3769 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003770 ICS->Standard.ReferenceBinding = true;
3771 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003772 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003773 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003774
3775 // Nothing more to do: the inaccessibility/ambiguity check for
3776 // derived-to-base conversions is suppressed when we're
3777 // computing the implicit conversion sequence (C++
3778 // [over.best.ics]p2).
3779 return false;
3780 } else {
3781 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003782 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3783 if (DerivedToBase)
3784 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003785 else if(CheckExceptionSpecCompatibility(Init, T1))
3786 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003787 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003788 }
3789 }
3790
3791 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003792 // implicitly converted to an lvalue of type "cv3 T3,"
3793 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003794 // 92) (this conversion is selected by enumerating the
3795 // applicable conversion functions (13.3.1.6) and choosing
3796 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003797 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003798 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003799 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003800 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003801
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003802 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003803 OverloadedFunctionDecl *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003804 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003805 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003806 = Conversions->function_begin();
3807 Func != Conversions->function_end(); ++Func) {
Mike Stump11289f42009-09-09 15:08:12 +00003808 FunctionTemplateDecl *ConvTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003809 = dyn_cast<FunctionTemplateDecl>(*Func);
3810 CXXConversionDecl *Conv;
3811 if (ConvTemplate)
3812 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3813 else
3814 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003815
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003816 // If the conversion function doesn't return a reference type,
3817 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003818 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003819 (AllowExplicit || !Conv->isExplicit())) {
3820 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003821 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003822 CandidateSet);
3823 else
3824 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3825 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003826 }
3827
3828 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003829 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003830 case OR_Success:
3831 // This is a direct binding.
3832 BindsDirectly = true;
3833
3834 if (ICS) {
3835 // C++ [over.ics.ref]p1:
3836 //
3837 // [...] If the parameter binds directly to the result of
3838 // applying a conversion function to the argument
3839 // expression, the implicit conversion sequence is a
3840 // user-defined conversion sequence (13.3.3.1.2), with the
3841 // second standard conversion sequence either an identity
3842 // conversion or, if the conversion function returns an
3843 // entity of a type that is a derived class of the parameter
3844 // type, a derived-to-base Conversion.
3845 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3846 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3847 ICS->UserDefined.After = Best->FinalConversion;
3848 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003849 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003850 assert(ICS->UserDefined.After.ReferenceBinding &&
3851 ICS->UserDefined.After.DirectBinding &&
3852 "Expected a direct reference binding!");
3853 return false;
3854 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003855 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003856 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003857 CastExpr::CK_UserDefinedConversion,
3858 cast<CXXMethodDecl>(Best->Function),
3859 Owned(Init));
3860 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003861
3862 if (CheckExceptionSpecCompatibility(Init, T1))
3863 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003864 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3865 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003866 }
3867 break;
3868
3869 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003870 if (ICS) {
3871 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3872 Cand != CandidateSet.end(); ++Cand)
3873 if (Cand->Viable)
3874 ICS->ConversionFunctionSet.push_back(Cand->Function);
3875 break;
3876 }
3877 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3878 << Init->getSourceRange();
3879 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003880 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003881
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003882 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003883 case OR_Deleted:
3884 // There was no suitable conversion, or we found a deleted
3885 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003886 break;
3887 }
3888 }
Mike Stump11289f42009-09-09 15:08:12 +00003889
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003890 if (BindsDirectly) {
3891 // C++ [dcl.init.ref]p4:
3892 // [...] In all cases where the reference-related or
3893 // reference-compatible relationship of two types is used to
3894 // establish the validity of a reference binding, and T1 is a
3895 // base class of T2, a program that necessitates such a binding
3896 // is ill-formed if T1 is an inaccessible (clause 11) or
3897 // ambiguous (10.2) base class of T2.
3898 //
3899 // Note that we only check this condition when we're allowed to
3900 // complain about errors, because we should not be checking for
3901 // ambiguity (or inaccessibility) unless the reference binding
3902 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003903 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003904 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00003905 Init->getSourceRange(),
3906 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00003907 else
3908 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003909 }
3910
3911 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003912 // type (i.e., cv1 shall be const), or the reference shall be an
3913 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00003914 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003915 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003916 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003917 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3918 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003919 return true;
3920 }
3921
3922 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003923 // class type, and "cv1 T1" is reference-compatible with
3924 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003925 // following ways (the choice is implementation-defined):
3926 //
3927 // -- The reference is bound to the object represented by
3928 // the rvalue (see 3.10) or to a sub-object within that
3929 // object.
3930 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00003931 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003932 // a constructor is called to copy the entire rvalue
3933 // object into the temporary. The reference is bound to
3934 // the temporary or to a sub-object within the
3935 // temporary.
3936 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003937 // The constructor that would be used to make the copy
3938 // shall be callable whether or not the copy is actually
3939 // done.
3940 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003941 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003942 // freedom, so we will always take the first option and never build
3943 // a temporary in this case. FIXME: We will, however, have to check
3944 // for the presence of a copy constructor in C++98/03 mode.
3945 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003946 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3947 if (ICS) {
3948 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3949 ICS->Standard.First = ICK_Identity;
3950 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3951 ICS->Standard.Third = ICK_Identity;
3952 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3953 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003954 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003955 ICS->Standard.DirectBinding = false;
3956 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003957 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003958 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003959 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3960 if (DerivedToBase)
3961 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003962 else if(CheckExceptionSpecCompatibility(Init, T1))
3963 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003964 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003965 }
3966 return false;
3967 }
3968
Eli Friedman44b83ee2009-08-05 19:21:58 +00003969 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003970 // initialized from the initializer expression using the
3971 // rules for a non-reference copy initialization (8.5). The
3972 // reference is then bound to the temporary. If T1 is
3973 // reference-related to T2, cv1 must be the same
3974 // cv-qualification as, or greater cv-qualification than,
3975 // cv2; otherwise, the program is ill-formed.
3976 if (RefRelationship == Ref_Related) {
3977 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3978 // we would be reference-compatible or reference-compatible with
3979 // added qualification. But that wasn't the case, so the reference
3980 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00003981 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003982 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003983 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3984 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003985 return true;
3986 }
3987
Douglas Gregor576e98c2009-01-30 23:27:23 +00003988 // If at least one of the types is a class type, the types are not
3989 // related, and we aren't allowed any user conversions, the
3990 // reference binding fails. This case is important for breaking
3991 // recursion, since TryImplicitConversion below will attempt to
3992 // create a temporary through the use of a copy constructor.
3993 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3994 (T1->isRecordType() || T2->isRecordType())) {
3995 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003996 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00003997 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3998 return true;
3999 }
4000
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004001 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004002 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004003 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004004 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004005 // When a parameter of reference type is not bound directly to
4006 // an argument expression, the conversion sequence is the one
4007 // required to convert the argument expression to the
4008 // underlying type of the reference according to
4009 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4010 // to copy-initializing a temporary of the underlying type with
4011 // the argument expression. Any difference in top-level
4012 // cv-qualification is subsumed by the initialization itself
4013 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004014 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4015 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004016 /*ForceRValue=*/false,
4017 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004018
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004019 // Of course, that's still a reference binding.
4020 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4021 ICS->Standard.ReferenceBinding = true;
4022 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004023 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004024 ImplicitConversionSequence::UserDefinedConversion) {
4025 ICS->UserDefined.After.ReferenceBinding = true;
4026 ICS->UserDefined.After.RRefBinding = isRValRef;
4027 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004028 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4029 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004030 ImplicitConversionSequence Conversions;
4031 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4032 false, false,
4033 Conversions);
4034 if (badConversion) {
4035 if ((Conversions.ConversionKind ==
4036 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004037 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004038 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004039 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4040 for (int j = Conversions.ConversionFunctionSet.size()-1;
4041 j >= 0; j--) {
4042 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4043 Diag(Func->getLocation(), diag::err_ovl_candidate);
4044 }
4045 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004046 else {
4047 if (isRValRef)
4048 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4049 << Init->getSourceRange();
4050 else
4051 Diag(DeclLoc, diag::err_invalid_initialization)
4052 << DeclType << Init->getType() << Init->getSourceRange();
4053 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004054 }
4055 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004056 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004057}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004058
4059/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4060/// of this overloaded operator is well-formed. If so, returns false;
4061/// otherwise, emits appropriate diagnostics and returns true.
4062bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004063 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004064 "Expected an overloaded operator declaration");
4065
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004066 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4067
Mike Stump11289f42009-09-09 15:08:12 +00004068 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004069 // The allocation and deallocation functions, operator new,
4070 // operator new[], operator delete and operator delete[], are
4071 // described completely in 3.7.3. The attributes and restrictions
4072 // found in the rest of this subclause do not apply to them unless
4073 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004074 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004075 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004076 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004077
4078 if (Op == OO_New || Op == OO_Array_New) {
4079 bool ret = false;
4080 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4081 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4082 QualType T = Context.getCanonicalType((*Param)->getType());
4083 if (!T->isDependentType() && SizeTy != T) {
4084 Diag(FnDecl->getLocation(),
4085 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4086 << SizeTy;
4087 ret = true;
4088 }
4089 }
4090 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4091 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4092 return Diag(FnDecl->getLocation(),
4093 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004094 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004095 return ret;
4096 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004097
4098 // C++ [over.oper]p6:
4099 // An operator function shall either be a non-static member
4100 // function or be a non-member function and have at least one
4101 // parameter whose type is a class, a reference to a class, an
4102 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004103 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4104 if (MethodDecl->isStatic())
4105 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004106 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004107 } else {
4108 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004109 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4110 ParamEnd = FnDecl->param_end();
4111 Param != ParamEnd; ++Param) {
4112 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004113 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4114 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004115 ClassOrEnumParam = true;
4116 break;
4117 }
4118 }
4119
Douglas Gregord69246b2008-11-17 16:14:12 +00004120 if (!ClassOrEnumParam)
4121 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004122 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004123 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004124 }
4125
4126 // C++ [over.oper]p8:
4127 // An operator function cannot have default arguments (8.3.6),
4128 // except where explicitly stated below.
4129 //
Mike Stump11289f42009-09-09 15:08:12 +00004130 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004131 // (C++ [over.call]p1).
4132 if (Op != OO_Call) {
4133 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4134 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004135 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004136 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004137 diag::err_operator_overload_default_arg)
4138 << FnDecl->getDeclName();
4139 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004140 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004141 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004142 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004143 }
4144 }
4145
Douglas Gregor6cf08062008-11-10 13:38:07 +00004146 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4147 { false, false, false }
4148#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4149 , { Unary, Binary, MemberOnly }
4150#include "clang/Basic/OperatorKinds.def"
4151 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004152
Douglas Gregor6cf08062008-11-10 13:38:07 +00004153 bool CanBeUnaryOperator = OperatorUses[Op][0];
4154 bool CanBeBinaryOperator = OperatorUses[Op][1];
4155 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004156
4157 // C++ [over.oper]p8:
4158 // [...] Operator functions cannot have more or fewer parameters
4159 // than the number required for the corresponding operator, as
4160 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004161 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004162 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004163 if (Op != OO_Call &&
4164 ((NumParams == 1 && !CanBeUnaryOperator) ||
4165 (NumParams == 2 && !CanBeBinaryOperator) ||
4166 (NumParams < 1) || (NumParams > 2))) {
4167 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004168 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004169 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004170 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004171 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004172 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004173 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004174 assert(CanBeBinaryOperator &&
4175 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004176 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004177 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004178
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004179 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004180 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004181 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004182
Douglas Gregord69246b2008-11-17 16:14:12 +00004183 // Overloaded operators other than operator() cannot be variadic.
4184 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004185 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004186 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004187 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004188 }
4189
4190 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004191 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4192 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004193 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004194 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004195 }
4196
4197 // C++ [over.inc]p1:
4198 // The user-defined function called operator++ implements the
4199 // prefix and postfix ++ operator. If this function is a member
4200 // function with no parameters, or a non-member function with one
4201 // parameter of class or enumeration type, it defines the prefix
4202 // increment operator ++ for objects of that type. If the function
4203 // is a member function with one parameter (which shall be of type
4204 // int) or a non-member function with two parameters (the second
4205 // of which shall be of type int), it defines the postfix
4206 // increment operator ++ for objects of that type.
4207 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4208 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4209 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004210 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004211 ParamIsInt = BT->getKind() == BuiltinType::Int;
4212
Chris Lattner2b786902008-11-21 07:50:02 +00004213 if (!ParamIsInt)
4214 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004215 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004216 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004217 }
4218
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004219 // Notify the class if it got an assignment operator.
4220 if (Op == OO_Equal) {
4221 // Would have returned earlier otherwise.
4222 assert(isa<CXXMethodDecl>(FnDecl) &&
4223 "Overloaded = not member, but not filtered.");
4224 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4225 Method->getParent()->addedAssignmentOperator(Context, Method);
4226 }
4227
Douglas Gregord69246b2008-11-17 16:14:12 +00004228 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004229}
Chris Lattner3b024a32008-12-17 07:09:26 +00004230
Douglas Gregor07665a62009-01-05 19:45:36 +00004231/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4232/// linkage specification, including the language and (if present)
4233/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4234/// the location of the language string literal, which is provided
4235/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4236/// the '{' brace. Otherwise, this linkage specification does not
4237/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004238Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4239 SourceLocation ExternLoc,
4240 SourceLocation LangLoc,
4241 const char *Lang,
4242 unsigned StrSize,
4243 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004244 LinkageSpecDecl::LanguageIDs Language;
4245 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4246 Language = LinkageSpecDecl::lang_c;
4247 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4248 Language = LinkageSpecDecl::lang_cxx;
4249 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004250 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004251 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004252 }
Mike Stump11289f42009-09-09 15:08:12 +00004253
Chris Lattner438e5012008-12-17 07:13:27 +00004254 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004255
Douglas Gregor07665a62009-01-05 19:45:36 +00004256 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004257 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004258 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004259 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004260 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004261 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004262}
4263
Douglas Gregor07665a62009-01-05 19:45:36 +00004264/// ActOnFinishLinkageSpecification - Completely the definition of
4265/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4266/// valid, it's the position of the closing '}' brace in a linkage
4267/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004268Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4269 DeclPtrTy LinkageSpec,
4270 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004271 if (LinkageSpec)
4272 PopDeclContext();
4273 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004274}
4275
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004276/// \brief Perform semantic analysis for the variable declaration that
4277/// occurs within a C++ catch clause, returning the newly-created
4278/// variable.
4279VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004280 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004281 IdentifierInfo *Name,
4282 SourceLocation Loc,
4283 SourceRange Range) {
4284 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004285
4286 // Arrays and functions decay.
4287 if (ExDeclType->isArrayType())
4288 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4289 else if (ExDeclType->isFunctionType())
4290 ExDeclType = Context.getPointerType(ExDeclType);
4291
4292 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4293 // The exception-declaration shall not denote a pointer or reference to an
4294 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004295 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004296 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004297 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004298 Invalid = true;
4299 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004300
Sebastian Redl54c04d42008-12-22 19:15:10 +00004301 QualType BaseType = ExDeclType;
4302 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004303 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004304 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004305 BaseType = Ptr->getPointeeType();
4306 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004307 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004308 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004309 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004310 BaseType = Ref->getPointeeType();
4311 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004312 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004313 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004314 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004315 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004316 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004317
Mike Stump11289f42009-09-09 15:08:12 +00004318 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004319 RequireNonAbstractType(Loc, ExDeclType,
4320 diag::err_abstract_type_in_decl,
4321 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004322 Invalid = true;
4323
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004324 // FIXME: Need to test for ability to copy-construct and destroy the
4325 // exception variable.
4326
Sebastian Redl9b244a82008-12-22 21:35:02 +00004327 // FIXME: Need to check for abstract classes.
4328
Mike Stump11289f42009-09-09 15:08:12 +00004329 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004330 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004331
4332 if (Invalid)
4333 ExDecl->setInvalidDecl();
4334
4335 return ExDecl;
4336}
4337
4338/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4339/// handler.
4340Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004341 DeclaratorInfo *DInfo = 0;
4342 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004343
4344 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004345 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004346 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004347 // The scope should be freshly made just for us. There is just no way
4348 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004349 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004350 if (PrevDecl->isTemplateParameter()) {
4351 // Maybe we will complain about the shadowed template parameter.
4352 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004353 }
4354 }
4355
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004356 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004357 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4358 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004359 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004360 }
4361
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004362 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004363 D.getIdentifier(),
4364 D.getIdentifierLoc(),
4365 D.getDeclSpec().getSourceRange());
4366
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004367 if (Invalid)
4368 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004369
Sebastian Redl54c04d42008-12-22 19:15:10 +00004370 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004371 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004372 PushOnScopeChains(ExDecl, S);
4373 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004374 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004375
Douglas Gregor758a8692009-06-17 21:51:59 +00004376 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004377 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004378}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004379
Mike Stump11289f42009-09-09 15:08:12 +00004380Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004381 ExprArg assertexpr,
4382 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004383 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004384 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004385 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4386
Anders Carlsson54b26982009-03-14 00:33:21 +00004387 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4388 llvm::APSInt Value(32);
4389 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4390 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4391 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004392 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004393 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004394
Anders Carlsson54b26982009-03-14 00:33:21 +00004395 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004396 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004397 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004398 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004399 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004400 }
4401 }
Mike Stump11289f42009-09-09 15:08:12 +00004402
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004403 assertexpr.release();
4404 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004405 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004406 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004407
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004408 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004409 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004410}
Sebastian Redlf769df52009-03-24 22:27:57 +00004411
John McCall11083da2009-09-16 22:47:08 +00004412/// Handle a friend type declaration. This works in tandem with
4413/// ActOnTag.
4414///
4415/// Notes on friend class templates:
4416///
4417/// We generally treat friend class declarations as if they were
4418/// declaring a class. So, for example, the elaborated type specifier
4419/// in a friend declaration is required to obey the restrictions of a
4420/// class-head (i.e. no typedefs in the scope chain), template
4421/// parameters are required to match up with simple template-ids, &c.
4422/// However, unlike when declaring a template specialization, it's
4423/// okay to refer to a template specialization without an empty
4424/// template parameter declaration, e.g.
4425/// friend class A<T>::B<unsigned>;
4426/// We permit this as a special case; if there are any template
4427/// parameters present at all, require proper matching, i.e.
4428/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004429Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004430 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004431 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004432
4433 assert(DS.isFriendSpecified());
4434 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4435
John McCall11083da2009-09-16 22:47:08 +00004436 // Try to convert the decl specifier to a type. This works for
4437 // friend templates because ActOnTag never produces a ClassTemplateDecl
4438 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004439 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004440 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4441 if (TheDeclarator.isInvalidType())
4442 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004443
John McCall11083da2009-09-16 22:47:08 +00004444 // This is definitely an error in C++98. It's probably meant to
4445 // be forbidden in C++0x, too, but the specification is just
4446 // poorly written.
4447 //
4448 // The problem is with declarations like the following:
4449 // template <T> friend A<T>::foo;
4450 // where deciding whether a class C is a friend or not now hinges
4451 // on whether there exists an instantiation of A that causes
4452 // 'foo' to equal C. There are restrictions on class-heads
4453 // (which we declare (by fiat) elaborated friend declarations to
4454 // be) that makes this tractable.
4455 //
4456 // FIXME: handle "template <> friend class A<T>;", which
4457 // is possibly well-formed? Who even knows?
4458 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4459 Diag(Loc, diag::err_tagless_friend_type_template)
4460 << DS.getSourceRange();
4461 return DeclPtrTy();
4462 }
4463
John McCallaa74a0c2009-08-28 07:59:38 +00004464 // C++ [class.friend]p2:
4465 // An elaborated-type-specifier shall be used in a friend declaration
4466 // for a class.*
4467 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004468 // This is one of the rare places in Clang where it's legitimate to
4469 // ask about the "spelling" of the type.
4470 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4471 // If we evaluated the type to a record type, suggest putting
4472 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004473 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004474 RecordDecl *RD = RT->getDecl();
4475
4476 std::string InsertionText = std::string(" ") + RD->getKindName();
4477
John McCallc3987482009-10-07 23:34:25 +00004478 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4479 << (unsigned) RD->getTagKind()
4480 << T
4481 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004482 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4483 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004484 return DeclPtrTy();
4485 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004486 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4487 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004488 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004489 }
4490 }
4491
John McCallc3987482009-10-07 23:34:25 +00004492 // Enum types cannot be friends.
4493 if (T->getAs<EnumType>()) {
4494 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4495 << SourceRange(DS.getFriendSpecLoc());
4496 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004497 }
John McCallaa74a0c2009-08-28 07:59:38 +00004498
John McCallaa74a0c2009-08-28 07:59:38 +00004499 // C++98 [class.friend]p1: A friend of a class is a function
4500 // or class that is not a member of the class . . .
4501 // But that's a silly restriction which nobody implements for
4502 // inner classes, and C++0x removes it anyway, so we only report
4503 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004504 if (!getLangOptions().CPlusPlus0x)
4505 if (const RecordType *RT = T->getAs<RecordType>())
4506 if (RT->getDecl()->getDeclContext() == CurContext)
4507 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004508
John McCall11083da2009-09-16 22:47:08 +00004509 Decl *D;
4510 if (TempParams.size())
4511 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4512 TempParams.size(),
4513 (TemplateParameterList**) TempParams.release(),
4514 T.getTypePtr(),
4515 DS.getFriendSpecLoc());
4516 else
4517 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4518 DS.getFriendSpecLoc());
4519 D->setAccess(AS_public);
4520 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004521
John McCall11083da2009-09-16 22:47:08 +00004522 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004523}
4524
John McCall2f212b32009-09-11 21:02:39 +00004525Sema::DeclPtrTy
4526Sema::ActOnFriendFunctionDecl(Scope *S,
4527 Declarator &D,
4528 bool IsDefinition,
4529 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004530 const DeclSpec &DS = D.getDeclSpec();
4531
4532 assert(DS.isFriendSpecified());
4533 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4534
4535 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004536 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004537 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004538
4539 // C++ [class.friend]p1
4540 // A friend of a class is a function or class....
4541 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004542 // It *doesn't* see through dependent types, which is correct
4543 // according to [temp.arg.type]p3:
4544 // If a declaration acquires a function type through a
4545 // type dependent on a template-parameter and this causes
4546 // a declaration that does not use the syntactic form of a
4547 // function declarator to have a function type, the program
4548 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004549 if (!T->isFunctionType()) {
4550 Diag(Loc, diag::err_unexpected_friend);
4551
4552 // It might be worthwhile to try to recover by creating an
4553 // appropriate declaration.
4554 return DeclPtrTy();
4555 }
4556
4557 // C++ [namespace.memdef]p3
4558 // - If a friend declaration in a non-local class first declares a
4559 // class or function, the friend class or function is a member
4560 // of the innermost enclosing namespace.
4561 // - The name of the friend is not found by simple name lookup
4562 // until a matching declaration is provided in that namespace
4563 // scope (either before or after the class declaration granting
4564 // friendship).
4565 // - If a friend function is called, its name may be found by the
4566 // name lookup that considers functions from namespaces and
4567 // classes associated with the types of the function arguments.
4568 // - When looking for a prior declaration of a class or a function
4569 // declared as a friend, scopes outside the innermost enclosing
4570 // namespace scope are not considered.
4571
John McCallaa74a0c2009-08-28 07:59:38 +00004572 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4573 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004574 assert(Name);
4575
John McCall07e91c02009-08-06 02:15:43 +00004576 // The context we found the declaration in, or in which we should
4577 // create the declaration.
4578 DeclContext *DC;
4579
4580 // FIXME: handle local classes
4581
4582 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004583 NamedDecl *PrevDecl = 0;
John McCall07e91c02009-08-06 02:15:43 +00004584 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004585 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004586 DC = computeDeclContext(ScopeQual);
4587
4588 // FIXME: handle dependent contexts
4589 if (!DC) return DeclPtrTy();
4590
John McCall9f3059a2009-10-09 21:13:30 +00004591 LookupResult R;
4592 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4593 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004594
4595 // If searching in that context implicitly found a declaration in
4596 // a different context, treat it like it wasn't found at all.
4597 // TODO: better diagnostics for this case. Suggesting the right
4598 // qualified scope would be nice...
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004599 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004600 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004601 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4602 return DeclPtrTy();
4603 }
4604
4605 // C++ [class.friend]p1: A friend of a class is a function or
4606 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004607 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004608 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4609
John McCall07e91c02009-08-06 02:15:43 +00004610 // Otherwise walk out to the nearest namespace scope looking for matches.
4611 } else {
4612 // TODO: handle local class contexts.
4613
4614 DC = CurContext;
4615 while (true) {
4616 // Skip class contexts. If someone can cite chapter and verse
4617 // for this behavior, that would be nice --- it's what GCC and
4618 // EDG do, and it seems like a reasonable intent, but the spec
4619 // really only says that checks for unqualified existing
4620 // declarations should stop at the nearest enclosing namespace,
4621 // not that they should only consider the nearest enclosing
4622 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004623 while (DC->isRecord())
4624 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004625
John McCall9f3059a2009-10-09 21:13:30 +00004626 LookupResult R;
4627 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4628 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004629
4630 // TODO: decide what we think about using declarations.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004631 if (PrevDecl)
John McCall07e91c02009-08-06 02:15:43 +00004632 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004633
John McCall07e91c02009-08-06 02:15:43 +00004634 if (DC->isFileContext()) break;
4635 DC = DC->getParent();
4636 }
4637
4638 // C++ [class.friend]p1: A friend of a class is a function or
4639 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004640 // C++0x changes this for both friend types and functions.
4641 // Most C++ 98 compilers do seem to give an error here, so
4642 // we do, too.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004643 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004644 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4645 }
4646
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004647 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004648 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004649 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4650 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4651 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004652 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004653 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4654 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004655 return DeclPtrTy();
4656 }
John McCall07e91c02009-08-06 02:15:43 +00004657 }
4658
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004659 bool Redeclaration = false;
4660 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004661 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004662 IsDefinition,
4663 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004664 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004665
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004666 assert(ND->getDeclContext() == DC);
4667 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004668
John McCall759e32b2009-08-31 22:39:49 +00004669 // Add the function declaration to the appropriate lookup tables,
4670 // adjusting the redeclarations list as necessary. We don't
4671 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004672 //
John McCall759e32b2009-08-31 22:39:49 +00004673 // Also update the scope-based lookup if the target context's
4674 // lookup context is in lexical scope.
4675 if (!CurContext->isDependentContext()) {
4676 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004677 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004678 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004679 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004680 }
John McCallaa74a0c2009-08-28 07:59:38 +00004681
4682 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004683 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004684 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004685 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004686 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004687
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004688 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004689}
4690
Chris Lattner83f095c2009-03-28 19:18:32 +00004691void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004692 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004693
Chris Lattner83f095c2009-03-28 19:18:32 +00004694 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004695 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4696 if (!Fn) {
4697 Diag(DelLoc, diag::err_deleted_non_function);
4698 return;
4699 }
4700 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4701 Diag(DelLoc, diag::err_deleted_decl_not_first);
4702 Diag(Prev->getLocation(), diag::note_previous_declaration);
4703 // If the declaration wasn't the first, we delete the function anyway for
4704 // recovery.
4705 }
4706 Fn->setDeleted();
4707}
Sebastian Redl4c018662009-04-27 21:33:24 +00004708
4709static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4710 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4711 ++CI) {
4712 Stmt *SubStmt = *CI;
4713 if (!SubStmt)
4714 continue;
4715 if (isa<ReturnStmt>(SubStmt))
4716 Self.Diag(SubStmt->getSourceRange().getBegin(),
4717 diag::err_return_in_constructor_handler);
4718 if (!isa<Expr>(SubStmt))
4719 SearchForReturnInStmt(Self, SubStmt);
4720 }
4721}
4722
4723void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4724 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4725 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4726 SearchForReturnInStmt(*this, Handler);
4727 }
4728}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004729
Mike Stump11289f42009-09-09 15:08:12 +00004730bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004731 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004732 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4733 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004734
4735 QualType CNewTy = Context.getCanonicalType(NewTy);
4736 QualType COldTy = Context.getCanonicalType(OldTy);
4737
Mike Stump11289f42009-09-09 15:08:12 +00004738 if (CNewTy == COldTy &&
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004739 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4740 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004741
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004742 // Check if the return types are covariant
4743 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004744
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004745 /// Both types must be pointers or references to classes.
4746 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4747 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4748 NewClassTy = NewPT->getPointeeType();
4749 OldClassTy = OldPT->getPointeeType();
4750 }
4751 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4752 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4753 NewClassTy = NewRT->getPointeeType();
4754 OldClassTy = OldRT->getPointeeType();
4755 }
4756 }
Mike Stump11289f42009-09-09 15:08:12 +00004757
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004758 // The return types aren't either both pointers or references to a class type.
4759 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004760 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004761 diag::err_different_return_type_for_overriding_virtual_function)
4762 << New->getDeclName() << NewTy << OldTy;
4763 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004764
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004765 return true;
4766 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004767
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004768 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4769 // Check if the new class derives from the old class.
4770 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4771 Diag(New->getLocation(),
4772 diag::err_covariant_return_not_derived)
4773 << New->getDeclName() << NewTy << OldTy;
4774 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4775 return true;
4776 }
Mike Stump11289f42009-09-09 15:08:12 +00004777
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004778 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004779 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004780 diag::err_covariant_return_inaccessible_base,
4781 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4782 // FIXME: Should this point to the return type?
4783 New->getLocation(), SourceRange(), New->getDeclName())) {
4784 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4785 return true;
4786 }
4787 }
Mike Stump11289f42009-09-09 15:08:12 +00004788
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004789 // The qualifiers of the return types must be the same.
4790 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4791 Diag(New->getLocation(),
4792 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004793 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004794 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4795 return true;
4796 };
Mike Stump11289f42009-09-09 15:08:12 +00004797
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004798
4799 // The new class type must have the same or less qualifiers as the old type.
4800 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4801 Diag(New->getLocation(),
4802 diag::err_covariant_return_type_class_type_more_qualified)
4803 << New->getDeclName() << NewTy << OldTy;
4804 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4805 return true;
4806 };
Mike Stump11289f42009-09-09 15:08:12 +00004807
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004808 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004809}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004810
4811/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4812/// initializer for the declaration 'Dcl'.
4813/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4814/// static data member of class X, names should be looked up in the scope of
4815/// class X.
4816void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004817 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004818
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004819 Decl *D = Dcl.getAs<Decl>();
4820 // If there is no declaration, there was an error parsing it.
4821 if (D == 0)
4822 return;
4823
4824 // Check whether it is a declaration with a nested name specifier like
4825 // int foo::bar;
4826 if (!D->isOutOfLine())
4827 return;
Mike Stump11289f42009-09-09 15:08:12 +00004828
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004829 // C++ [basic.lookup.unqual]p13
4830 //
4831 // A name used in the definition of a static data member of class X
4832 // (after the qualified-id of the static member) is looked up as if the name
4833 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004834
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004835 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004836 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004837}
4838
4839/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4840/// initializer for the declaration 'Dcl'.
4841void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004842 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004843
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004844 Decl *D = Dcl.getAs<Decl>();
4845 // If there is no declaration, there was an error parsing it.
4846 if (D == 0)
4847 return;
4848
4849 // Check whether it is a declaration with a nested name specifier like
4850 // int foo::bar;
4851 if (!D->isOutOfLine())
4852 return;
4853
4854 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004855 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004856}