blob: 1df11731215d417313c064c6ec3814f90e6d1c97 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000019#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000020#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000021#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000022#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000025#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000027#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000028#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000029#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000030#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000031
32using namespace clang;
33
Chris Lattner8123a952008-04-10 02:22:51 +000034//===----------------------------------------------------------------------===//
35// CheckDefaultArgumentVisitor
36//===----------------------------------------------------------------------===//
37
Chris Lattner9e979552008-04-12 23:52:44 +000038namespace {
39 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
40 /// the default argument of a parameter to determine whether it
41 /// contains any ill-formed subexpressions. For example, this will
42 /// diagnose the use of local variables or parameters within the
43 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000044 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000045 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000046 Expr *DefaultArg;
47 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000048
Chris Lattner9e979552008-04-12 23:52:44 +000049 public:
Mike Stump1eb44332009-09-09 15:08:12 +000050 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000051 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000052
Chris Lattner9e979552008-04-12 23:52:44 +000053 bool VisitExpr(Expr *Node);
54 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000055 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000056 };
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 /// VisitExpr - Visit all of the children of this expression.
59 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
60 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000061 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000062 E = Node->child_end(); I != E; ++I)
63 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000064 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000065 }
66
Chris Lattner9e979552008-04-12 23:52:44 +000067 /// VisitDeclRefExpr - Visit a reference to a declaration, to
68 /// determine whether this declaration can be used in the default
69 /// argument expression.
70 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000072 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
73 // C++ [dcl.fct.default]p9
74 // Default arguments are evaluated each time the function is
75 // called. The order of evaluation of function arguments is
76 // unspecified. Consequently, parameters of a function shall not
77 // be used in default argument expressions, even if they are not
78 // evaluated. Parameters of a function declared before a default
79 // argument expression are in scope and can hide namespace and
80 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000081 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000082 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000083 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000084 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000085 // C++ [dcl.fct.default]p7
86 // Local variables shall not be used in default argument
87 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000088 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000089 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000090 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000091 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000092 }
Chris Lattner8123a952008-04-10 02:22:51 +000093
Douglas Gregor3996f232008-11-04 13:41:56 +000094 return false;
95 }
Chris Lattner9e979552008-04-12 23:52:44 +000096
Douglas Gregor796da182008-11-04 14:32:21 +000097 /// VisitCXXThisExpr - Visit a C++ "this" expression.
98 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
99 // C++ [dcl.fct.default]p8:
100 // The keyword this shall not be used in a default argument of a
101 // member function.
102 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_this)
104 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000105 }
Chris Lattner8123a952008-04-10 02:22:51 +0000106}
107
Anders Carlssoned961f92009-08-25 02:29:20 +0000108bool
109Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000110 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000111 QualType ParamType = Param->getType();
112
Anders Carlsson5653ca52009-08-25 13:46:13 +0000113 if (RequireCompleteType(Param->getLocation(), Param->getType(),
114 diag::err_typecheck_decl_incomplete_type)) {
115 Param->setInvalidDecl();
116 return true;
117 }
118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Anders Carlssoned961f92009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000127 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000128 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000129 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000130
131 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Anders Carlssoned961f92009-08-25 02:29:20 +0000133 // Okay: add the default argument to the parameter
134 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Anders Carlssoned961f92009-08-25 02:29:20 +0000136 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlsson9351c172009-08-25 03:18:48 +0000138 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000139}
140
Chris Lattner8123a952008-04-10 02:22:51 +0000141/// ActOnParamDefaultArgument - Check whether the default argument
142/// provided for a function parameter is well-formed. If so, attach it
143/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000144void
Mike Stump1eb44332009-09-09 15:08:12 +0000145Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000146 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000147 if (!param || !defarg.get())
148 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Chris Lattnerb28317a2009-03-28 19:18:32 +0000150 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000151 UnparsedDefaultArgLocs.erase(Param);
152
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000153 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000154 QualType ParamType = Param->getType();
155
156 // Default arguments are only permitted in C++
157 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000158 Diag(EqualLoc, diag::err_param_default_argument)
159 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000160 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000161 return;
162 }
163
Anders Carlsson66e30672009-08-25 01:02:06 +0000164 // Check that the default argument is well-formed
165 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
166 if (DefaultArgChecker.Visit(DefaultArg.get())) {
167 Param->setInvalidDecl();
168 return;
169 }
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Anders Carlssoned961f92009-08-25 02:29:20 +0000171 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172}
173
Douglas Gregor61366e92008-12-24 00:01:03 +0000174/// ActOnParamUnparsedDefaultArgument - We've seen a default
175/// argument for a function parameter, but we can't parse it yet
176/// because we're inside a class definition. Note that this default
177/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000178void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000179 SourceLocation EqualLoc,
180 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000181 if (!param)
182 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattnerb28317a2009-03-28 19:18:32 +0000184 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000185 if (Param)
186 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Anders Carlsson5e300d12009-06-12 16:51:40 +0000188 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000189}
190
Douglas Gregor72b505b2008-12-16 21:30:33 +0000191/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
192/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000193void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000194 if (!param)
195 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Anders Carlsson5e300d12009-06-12 16:51:40 +0000197 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Anders Carlsson5e300d12009-06-12 16:51:40 +0000199 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000202}
203
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000204/// CheckExtraCXXDefaultArguments - Check for any extra default
205/// arguments in the declarator, which is not a function declaration
206/// or definition and therefore is not permitted to have default
207/// arguments. This routine should be invoked for every declarator
208/// that is not a function declaration or definition.
209void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
210 // C++ [dcl.fct.default]p3
211 // A default argument expression shall be specified only in the
212 // parameter-declaration-clause of a function declaration or in a
213 // template-parameter (14.1). It shall not be specified for a
214 // parameter pack. If it is specified in a
215 // parameter-declaration-clause, it shall not occur within a
216 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000217 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000218 DeclaratorChunk &chunk = D.getTypeObject(i);
219 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000220 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
221 ParmVarDecl *Param =
222 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000223 if (Param->hasUnparsedDefaultArg()) {
224 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000225 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
226 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
227 delete Toks;
228 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000229 } else if (Param->getDefaultArg()) {
230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231 << Param->getDefaultArg()->getSourceRange();
232 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000233 }
234 }
235 }
236 }
237}
238
Chris Lattner3d1cee32008-04-08 05:04:30 +0000239// MergeCXXFunctionDecl - Merge two declarations of the same C++
240// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000241// type. Subroutine of MergeFunctionDecl. Returns true if there was an
242// error, false otherwise.
243bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
244 bool Invalid = false;
245
Chris Lattner3d1cee32008-04-08 05:04:30 +0000246 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000247 // For non-template functions, default arguments can be added in
248 // later declarations of a function in the same
249 // scope. Declarations in different scopes have completely
250 // distinct sets of default arguments. That is, declarations in
251 // inner scopes do not acquire default arguments from
252 // declarations in outer scopes, and vice versa. In a given
253 // function declaration, all parameters subsequent to a
254 // parameter with a default argument shall have default
255 // arguments supplied in this or previous declarations. A
256 // default argument shall not be redefined by a later
257 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000258 //
259 // C++ [dcl.fct.default]p6:
260 // Except for member functions of class templates, the default arguments
261 // in a member function definition that appears outside of the class
262 // definition are added to the set of default arguments provided by the
263 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000264 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
265 ParmVarDecl *OldParam = Old->getParamDecl(p);
266 ParmVarDecl *NewParam = New->getParamDecl(p);
267
Douglas Gregor6cc15182009-09-11 18:44:32 +0000268 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000269 // FIXME: If the parameter doesn't have an identifier then the location
270 // points to the '=' which means that the fixit hint won't remove any
271 // extra spaces between the type and the '='.
272 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000273 if (NewParam->getIdentifier())
274 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000275
Mike Stump1eb44332009-09-09 15:08:12 +0000276 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000277 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000278 << NewParam->getDefaultArgRange()
279 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
280 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000281
282 // Look for the function declaration where the default argument was
283 // actually written, which may be a declaration prior to Old.
284 for (FunctionDecl *Older = Old->getPreviousDeclaration();
285 Older; Older = Older->getPreviousDeclaration()) {
286 if (!Older->getParamDecl(p)->hasDefaultArg())
287 break;
288
289 OldParam = Older->getParamDecl(p);
290 }
291
292 Diag(OldParam->getLocation(), diag::note_previous_definition)
293 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000294 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000295 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000296 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000297 if (OldParam->hasUninstantiatedDefaultArg())
298 NewParam->setUninstantiatedDefaultArg(
299 OldParam->getUninstantiatedDefaultArg());
300 else
301 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000302 } else if (NewParam->hasDefaultArg()) {
303 if (New->getDescribedFunctionTemplate()) {
304 // Paragraph 4, quoted above, only applies to non-template functions.
305 Diag(NewParam->getLocation(),
306 diag::err_param_default_argument_template_redecl)
307 << NewParam->getDefaultArgRange();
308 Diag(Old->getLocation(), diag::note_template_prev_declaration)
309 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000310 } else if (New->getTemplateSpecializationKind()
311 != TSK_ImplicitInstantiation &&
312 New->getTemplateSpecializationKind() != TSK_Undeclared) {
313 // C++ [temp.expr.spec]p21:
314 // Default function arguments shall not be specified in a declaration
315 // or a definition for one of the following explicit specializations:
316 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000317 // - the explicit specialization of a member function template;
318 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000319 // template where the class template specialization to which the
320 // member function specialization belongs is implicitly
321 // instantiated.
322 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
323 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
324 << New->getDeclName()
325 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000326 } else if (New->getDeclContext()->isDependentContext()) {
327 // C++ [dcl.fct.default]p6 (DR217):
328 // Default arguments for a member function of a class template shall
329 // be specified on the initial declaration of the member function
330 // within the class template.
331 //
332 // Reading the tea leaves a bit in DR217 and its reference to DR205
333 // leads me to the conclusion that one cannot add default function
334 // arguments for an out-of-line definition of a member function of a
335 // dependent type.
336 int WhichKind = 2;
337 if (CXXRecordDecl *Record
338 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
339 if (Record->getDescribedClassTemplate())
340 WhichKind = 0;
341 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
342 WhichKind = 1;
343 else
344 WhichKind = 2;
345 }
346
347 Diag(NewParam->getLocation(),
348 diag::err_param_default_argument_member_template_redecl)
349 << WhichKind
350 << NewParam->getDefaultArgRange();
351 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000352 }
353 }
354
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000355 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000356 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
357 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000358 Invalid = true;
359 }
360
Douglas Gregorcda9c672009-02-16 17:45:42 +0000361 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000362}
363
364/// CheckCXXDefaultArguments - Verify that the default arguments for a
365/// function declaration are well-formed according to C++
366/// [dcl.fct.default].
367void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
368 unsigned NumParams = FD->getNumParams();
369 unsigned p;
370
371 // Find first parameter with a default argument
372 for (p = 0; p < NumParams; ++p) {
373 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000374 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000375 break;
376 }
377
378 // C++ [dcl.fct.default]p4:
379 // In a given function declaration, all parameters
380 // subsequent to a parameter with a default argument shall
381 // have default arguments supplied in this or previous
382 // declarations. A default argument shall not be redefined
383 // by a later declaration (not even to the same value).
384 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000385 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000387 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000388 if (Param->isInvalidDecl())
389 /* We already complained about this parameter. */;
390 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000391 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000392 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000393 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000394 else
Mike Stump1eb44332009-09-09 15:08:12 +0000395 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 LastMissingDefaultArg = p;
399 }
400 }
401
402 if (LastMissingDefaultArg > 0) {
403 // Some default arguments were missing. Clear out all of the
404 // default arguments up to (and including) the last missing
405 // default argument, so that we leave the function parameters
406 // in a semantically valid state.
407 for (p = 0; p <= LastMissingDefaultArg; ++p) {
408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000409 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000410 if (!Param->hasUnparsedDefaultArg())
411 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000412 Param->setDefaultArg(0);
413 }
414 }
415 }
416}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000417
Douglas Gregorb48fe382008-10-31 09:07:45 +0000418/// isCurrentClassName - Determine whether the identifier II is the
419/// name of the class type currently being defined. In the case of
420/// nested classes, this will only return true if II is the name of
421/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000422bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
423 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000424 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000425 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000426 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000427 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
428 } else
429 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
430
431 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000432 return &II == CurDecl->getIdentifier();
433 else
434 return false;
435}
436
Mike Stump1eb44332009-09-09 15:08:12 +0000437/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000438///
439/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
440/// and returns NULL otherwise.
441CXXBaseSpecifier *
442Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
443 SourceRange SpecifierRange,
444 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000445 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000446 SourceLocation BaseLoc) {
447 // C++ [class.union]p1:
448 // A union shall not have base classes.
449 if (Class->isUnion()) {
450 Diag(Class->getLocation(), diag::err_base_clause_on_union)
451 << SpecifierRange;
452 return 0;
453 }
454
455 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000456 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000457 Class->getTagKind() == RecordDecl::TK_class,
458 Access, BaseType);
459
460 // Base specifiers must be record types.
461 if (!BaseType->isRecordType()) {
462 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
463 return 0;
464 }
465
466 // C++ [class.union]p1:
467 // A union shall not be used as a base class.
468 if (BaseType->isUnionType()) {
469 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
470 return 0;
471 }
472
473 // C++ [class.derived]p2:
474 // The class-name in a base-specifier shall not be an incompletely
475 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000476 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000477 PDiag(diag::err_incomplete_base_class)
478 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000479 return 0;
480
Eli Friedman1d954f62009-08-15 21:55:26 +0000481 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000482 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000483 assert(BaseDecl && "Record type has no declaration");
484 BaseDecl = BaseDecl->getDefinition(Context);
485 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000486 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
487 assert(CXXBaseDecl && "Base type is not a C++ type");
488 if (!CXXBaseDecl->isEmpty())
489 Class->setEmpty(false);
490 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000491 Class->setPolymorphic(true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000492 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
495 Diag(CXXBaseDecl->getLocation(), diag::note_previous_class_decl)
496 << BaseType.getAsString();
497 return 0;
498 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499
500 // C++ [dcl.init.aggr]p1:
501 // An aggregate is [...] a class with [...] no base classes [...].
502 Class->setAggregate(false);
503 Class->setPOD(false);
504
Anders Carlsson347ba892009-04-16 00:08:20 +0000505 if (Virtual) {
506 // C++ [class.ctor]p5:
507 // A constructor is trivial if its class has no virtual base classes.
508 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000509
510 // C++ [class.copy]p6:
511 // A copy constructor is trivial if its class has no virtual base classes.
512 Class->setHasTrivialCopyConstructor(false);
513
514 // C++ [class.copy]p11:
515 // A copy assignment operator is trivial if its class has no virtual
516 // base classes.
517 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000518
519 // C++0x [meta.unary.prop] is_empty:
520 // T is a class type, but not a union type, with ... no virtual base
521 // classes
522 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000523 } else {
524 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000525 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000526 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000527 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
528 Class->setHasTrivialConstructor(false);
529
530 // C++ [class.copy]p6:
531 // A copy constructor is trivial if all the direct base classes of its
532 // class have trivial copy constructors.
533 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
534 Class->setHasTrivialCopyConstructor(false);
535
536 // C++ [class.copy]p11:
537 // A copy assignment operator is trivial if all the direct base classes
538 // of its class have trivial copy assignment operators.
539 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
540 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000541 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000542
543 // C++ [class.ctor]p3:
544 // A destructor is trivial if all the direct base classes of its class
545 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000546 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
547 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Douglas Gregor2943aed2009-03-03 04:44:36 +0000549 // Create the base specifier.
550 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000551 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
552 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000553 Access, BaseType);
554}
555
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000556/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
557/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000558/// example:
559/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000560/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000561Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000562Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000563 bool Virtual, AccessSpecifier Access,
564 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000565 if (!classdecl)
566 return true;
567
Douglas Gregor40808ce2009-03-09 23:48:35 +0000568 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000569 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000570 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
572 Virtual, Access,
573 BaseType, BaseLoc))
574 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000577}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000578
Douglas Gregor2943aed2009-03-03 04:44:36 +0000579/// \brief Performs the actual work of attaching the given base class
580/// specifiers to a C++ class.
581bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
582 unsigned NumBases) {
583 if (NumBases == 0)
584 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000585
586 // Used to keep track of which base types we have already seen, so
587 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000588 // that the key is always the unqualified canonical type of the base
589 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000590 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
591
592 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000593 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000595 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000596 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000598 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000599
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000600 if (KnownBaseTypes[NewBaseType]) {
601 // C++ [class.mi]p3:
602 // A class shall not be specified as a direct base class of a
603 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000604 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000605 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000606 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000607 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000608
609 // Delete the duplicate base class specifier; we're going to
610 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000611 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000612
613 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000614 } else {
615 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 KnownBaseTypes[NewBaseType] = Bases[idx];
617 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000618 }
619 }
620
621 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000622 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000623
624 // Delete the remaining (good) base class specifiers, since their
625 // data has been copied into the CXXRecordDecl.
626 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000627 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000628
629 return Invalid;
630}
631
632/// ActOnBaseSpecifiers - Attach the given base specifiers to the
633/// class, after checking whether there are any duplicate base
634/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000635void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636 unsigned NumBases) {
637 if (!ClassDecl || !Bases || !NumBases)
638 return;
639
640 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000641 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000642 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000643}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000644
Douglas Gregora8f32e02009-10-06 17:59:45 +0000645/// \brief Determine whether the type \p Derived is a C++ class that is
646/// derived from the type \p Base.
647bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
648 if (!getLangOptions().CPlusPlus)
649 return false;
650
651 const RecordType *DerivedRT = Derived->getAs<RecordType>();
652 if (!DerivedRT)
653 return false;
654
655 const RecordType *BaseRT = Base->getAs<RecordType>();
656 if (!BaseRT)
657 return false;
658
659 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
660 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
661 return DerivedRD->isDerivedFrom(BaseRD);
662}
663
664/// \brief Determine whether the type \p Derived is a C++ class that is
665/// derived from the type \p Base.
666bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
667 if (!getLangOptions().CPlusPlus)
668 return false;
669
670 const RecordType *DerivedRT = Derived->getAs<RecordType>();
671 if (!DerivedRT)
672 return false;
673
674 const RecordType *BaseRT = Base->getAs<RecordType>();
675 if (!BaseRT)
676 return false;
677
678 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
679 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
680 return DerivedRD->isDerivedFrom(BaseRD, Paths);
681}
682
683/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
684/// conversion (where Derived and Base are class types) is
685/// well-formed, meaning that the conversion is unambiguous (and
686/// that all of the base classes are accessible). Returns true
687/// and emits a diagnostic if the code is ill-formed, returns false
688/// otherwise. Loc is the location where this routine should point to
689/// if there is an error, and Range is the source range to highlight
690/// if there is an error.
691bool
692Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
693 unsigned InaccessibleBaseID,
694 unsigned AmbigiousBaseConvID,
695 SourceLocation Loc, SourceRange Range,
696 DeclarationName Name) {
697 // First, determine whether the path from Derived to Base is
698 // ambiguous. This is slightly more expensive than checking whether
699 // the Derived to Base conversion exists, because here we need to
700 // explore multiple paths to determine if there is an ambiguity.
701 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
702 /*DetectVirtual=*/false);
703 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
704 assert(DerivationOkay &&
705 "Can only be used with a derived-to-base conversion");
706 (void)DerivationOkay;
707
708 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000709 if (InaccessibleBaseID == 0)
710 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000711 // Check that the base class can be accessed.
712 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
713 Name);
714 }
715
716 // We know that the derived-to-base conversion is ambiguous, and
717 // we're going to produce a diagnostic. Perform the derived-to-base
718 // search just one more time to compute all of the possible paths so
719 // that we can print them out. This is more expensive than any of
720 // the previous derived-to-base checks we've done, but at this point
721 // performance isn't as much of an issue.
722 Paths.clear();
723 Paths.setRecordingPaths(true);
724 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
725 assert(StillOkay && "Can only be used with a derived-to-base conversion");
726 (void)StillOkay;
727
728 // Build up a textual representation of the ambiguous paths, e.g.,
729 // D -> B -> A, that will be used to illustrate the ambiguous
730 // conversions in the diagnostic. We only print one of the paths
731 // to each base class subobject.
732 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
733
734 Diag(Loc, AmbigiousBaseConvID)
735 << Derived << Base << PathDisplayStr << Range << Name;
736 return true;
737}
738
739bool
740Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000741 SourceLocation Loc, SourceRange Range,
742 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000743 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000744 IgnoreAccess ? 0 :
745 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000746 diag::err_ambiguous_derived_to_base_conv,
747 Loc, Range, DeclarationName());
748}
749
750
751/// @brief Builds a string representing ambiguous paths from a
752/// specific derived class to different subobjects of the same base
753/// class.
754///
755/// This function builds a string that can be used in error messages
756/// to show the different paths that one can take through the
757/// inheritance hierarchy to go from the derived class to different
758/// subobjects of a base class. The result looks something like this:
759/// @code
760/// struct D -> struct B -> struct A
761/// struct D -> struct C -> struct A
762/// @endcode
763std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
764 std::string PathDisplayStr;
765 std::set<unsigned> DisplayedPaths;
766 for (CXXBasePaths::paths_iterator Path = Paths.begin();
767 Path != Paths.end(); ++Path) {
768 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
769 // We haven't displayed a path to this particular base
770 // class subobject yet.
771 PathDisplayStr += "\n ";
772 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
773 for (CXXBasePath::const_iterator Element = Path->begin();
774 Element != Path->end(); ++Element)
775 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
776 }
777 }
778
779 return PathDisplayStr;
780}
781
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000782//===----------------------------------------------------------------------===//
783// C++ class member Handling
784//===----------------------------------------------------------------------===//
785
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000786/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
787/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
788/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000789/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000790Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000791Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000792 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000793 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
794 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000795 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000796 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000797 Expr *BitWidth = static_cast<Expr*>(BW);
798 Expr *Init = static_cast<Expr*>(InitExpr);
799 SourceLocation Loc = D.getIdentifierLoc();
800
Sebastian Redl669d5d72008-11-14 23:42:31 +0000801 bool isFunc = D.isFunctionDeclarator();
802
John McCall67d1a672009-08-06 02:15:43 +0000803 assert(!DS.isFriendSpecified());
804
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000805 // C++ 9.2p6: A member shall not be declared to have automatic storage
806 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000807 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
808 // data members and cannot be applied to names declared const or static,
809 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000810 switch (DS.getStorageClassSpec()) {
811 case DeclSpec::SCS_unspecified:
812 case DeclSpec::SCS_typedef:
813 case DeclSpec::SCS_static:
814 // FALL THROUGH.
815 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000816 case DeclSpec::SCS_mutable:
817 if (isFunc) {
818 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000819 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000820 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000821 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Sebastian Redla11f42f2008-11-17 23:24:37 +0000823 // FIXME: It would be nicer if the keyword was ignored only for this
824 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000825 D.getMutableDeclSpec().ClearStorageClassSpecs();
826 } else {
827 QualType T = GetTypeForDeclarator(D, S);
828 diag::kind err = static_cast<diag::kind>(0);
829 if (T->isReferenceType())
830 err = diag::err_mutable_reference;
831 else if (T.isConstQualified())
832 err = diag::err_mutable_const;
833 if (err != 0) {
834 if (DS.getStorageClassSpecLoc().isValid())
835 Diag(DS.getStorageClassSpecLoc(), err);
836 else
837 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000838 // FIXME: It would be nicer if the keyword was ignored only for this
839 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000840 D.getMutableDeclSpec().ClearStorageClassSpecs();
841 }
842 }
843 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000844 default:
845 if (DS.getStorageClassSpecLoc().isValid())
846 Diag(DS.getStorageClassSpecLoc(),
847 diag::err_storageclass_invalid_for_member);
848 else
849 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
850 D.getMutableDeclSpec().ClearStorageClassSpecs();
851 }
852
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000853 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000854 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000855 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000856 // Check also for this case:
857 //
858 // typedef int f();
859 // f a;
860 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000861 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000862 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000863 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864
Sebastian Redl669d5d72008-11-14 23:42:31 +0000865 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
866 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000867 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000868
869 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000870 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000871 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000872 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
873 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000874 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000875 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000876 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000877 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000878 if (!Member) {
879 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000880 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000881 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000882
883 // Non-instance-fields can't have a bitfield.
884 if (BitWidth) {
885 if (Member->isInvalidDecl()) {
886 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000887 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000888 // C++ 9.6p3: A bit-field shall not be a static member.
889 // "static member 'A' cannot be a bit-field"
890 Diag(Loc, diag::err_static_not_bitfield)
891 << Name << BitWidth->getSourceRange();
892 } else if (isa<TypedefDecl>(Member)) {
893 // "typedef member 'x' cannot be a bit-field"
894 Diag(Loc, diag::err_typedef_not_bitfield)
895 << Name << BitWidth->getSourceRange();
896 } else {
897 // A function typedef ("typedef int f(); f a;").
898 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
899 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000900 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000901 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner8b963ef2009-03-05 23:01:03 +0000904 DeleteExpr(BitWidth);
905 BitWidth = 0;
906 Member->setInvalidDecl();
907 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000908
909 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Douglas Gregor37b372b2009-08-20 22:52:58 +0000911 // If we have declared a member function template, set the access of the
912 // templated declaration as well.
913 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
914 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000915 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000916
Douglas Gregor10bd3682008-11-17 22:58:34 +0000917 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000918
Douglas Gregor021c3b32009-03-11 23:00:04 +0000919 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000920 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000921 if (Deleted) // FIXME: Source location is not very good.
922 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000923
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000924 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000925 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000926 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000927 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000928 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000929}
930
Douglas Gregor7ad83902008-11-05 04:29:56 +0000931/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000932Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000933Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000934 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000935 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000936 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000937 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000938 SourceLocation IdLoc,
939 SourceLocation LParenLoc,
940 ExprTy **Args, unsigned NumArgs,
941 SourceLocation *CommaLocs,
942 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000943 if (!ConstructorD)
944 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000946 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
948 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000949 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000950 if (!Constructor) {
951 // The user wrote a constructor initializer on a function that is
952 // not a C++ constructor. Ignore the error for now, because we may
953 // have more member initializers coming; we'll diagnose it just
954 // once in ActOnMemInitializers.
955 return true;
956 }
957
958 CXXRecordDecl *ClassDecl = Constructor->getParent();
959
960 // C++ [class.base.init]p2:
961 // Names in a mem-initializer-id are looked up in the scope of the
962 // constructor’s class and, if not found in that scope, are looked
963 // up in the scope containing the constructor’s
964 // definition. [Note: if the constructor’s class contains a member
965 // with the same name as a direct or virtual base class of the
966 // class, a mem-initializer-id naming the member or base class and
967 // composed of a single identifier refers to the class member. A
968 // mem-initializer-id for the hidden base class may be specified
969 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000970 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000971 // Look for a member, first.
972 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000973 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000974 = ClassDecl->lookup(MemberOrBase);
975 if (Result.first != Result.second)
976 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000977
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000978 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000979
Eli Friedman59c04372009-07-29 19:44:27 +0000980 if (Member)
981 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
982 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000983 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000984 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000985 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000986 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000987 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000988 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
989 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000991 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000992
Eli Friedman59c04372009-07-29 19:44:27 +0000993 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
994 RParenLoc, ClassDecl);
995}
996
John McCallb4190042009-11-04 23:02:40 +0000997/// Checks an initializer expression for use of uninitialized fields, such as
998/// containing the field that is being initialized. Returns true if there is an
999/// uninitialized field was used an updates the SourceLocation parameter; false
1000/// otherwise.
1001static bool InitExprContainsUninitializedFields(const Stmt* S,
1002 const FieldDecl* LhsField,
1003 SourceLocation* L) {
1004 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1005 if (ME) {
1006 const NamedDecl* RhsField = ME->getMemberDecl();
1007 if (RhsField == LhsField) {
1008 // Initializing a field with itself. Throw a warning.
1009 // But wait; there are exceptions!
1010 // Exception #1: The field may not belong to this record.
1011 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1012 const Expr* base = ME->getBase();
1013 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1014 // Even though the field matches, it does not belong to this record.
1015 return false;
1016 }
1017 // None of the exceptions triggered; return true to indicate an
1018 // uninitialized field was used.
1019 *L = ME->getMemberLoc();
1020 return true;
1021 }
1022 }
1023 bool found = false;
1024 for (Stmt::const_child_iterator it = S->child_begin();
1025 it != S->child_end() && found == false;
1026 ++it) {
1027 if (isa<CallExpr>(S)) {
1028 // Do not descend into function calls or constructors, as the use
1029 // of an uninitialized field may be valid. One would have to inspect
1030 // the contents of the function/ctor to determine if it is safe or not.
1031 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1032 // may be safe, depending on what the function/ctor does.
1033 continue;
1034 }
1035 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1036 }
1037 return found;
1038}
1039
Eli Friedman59c04372009-07-29 19:44:27 +00001040Sema::MemInitResult
1041Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1042 unsigned NumArgs, SourceLocation IdLoc,
1043 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001044 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1045 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1046 ExprTemporaries.clear();
1047
John McCallb4190042009-11-04 23:02:40 +00001048 // Diagnose value-uses of fields to initialize themselves, e.g.
1049 // foo(foo)
1050 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001051 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001052 for (unsigned i = 0; i < NumArgs; ++i) {
1053 SourceLocation L;
1054 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1055 // FIXME: Return true in the case when other fields are used before being
1056 // uninitialized. For example, let this field be the i'th field. When
1057 // initializing the i'th field, throw a warning if any of the >= i'th
1058 // fields are used, as they are not yet initialized.
1059 // Right now we are only handling the case where the i'th field uses
1060 // itself in its initializer.
1061 Diag(L, diag::warn_field_is_uninit);
1062 }
1063 }
1064
Eli Friedman59c04372009-07-29 19:44:27 +00001065 bool HasDependentArg = false;
1066 for (unsigned i = 0; i < NumArgs; i++)
1067 HasDependentArg |= Args[i]->isTypeDependent();
1068
1069 CXXConstructorDecl *C = 0;
1070 QualType FieldType = Member->getType();
1071 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1072 FieldType = Array->getElementType();
1073 if (FieldType->isDependentType()) {
1074 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001075 } else if (FieldType->isRecordType()) {
1076 // Member is a record (struct/union/class), so pass the initializer
1077 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001078 if (!HasDependentArg) {
1079 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1080
1081 C = PerformInitializationByConstructor(FieldType,
1082 MultiExprArg(*this,
1083 (void**)Args,
1084 NumArgs),
1085 IdLoc,
1086 SourceRange(IdLoc, RParenLoc),
1087 Member->getDeclName(), IK_Direct,
1088 ConstructorArgs);
1089
1090 if (C) {
1091 // Take over the constructor arguments as our own.
1092 NumArgs = ConstructorArgs.size();
1093 Args = (Expr **)ConstructorArgs.take();
1094 }
1095 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001096 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001097 // The member type is not a record type (or an array of record
1098 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001099 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001100 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1101 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001102 Expr *NewExp;
1103 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001104 if (FieldType->isReferenceType()) {
1105 Diag(IdLoc, diag::err_null_intialized_reference_member)
1106 << Member->getDeclName();
1107 return Diag(Member->getLocation(), diag::note_declared_at);
1108 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001109 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1110 NumArgs = 1;
1111 }
1112 else
1113 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001114 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1115 return true;
1116 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001117 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001118
1119 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1120 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1121 ExprTemporaries.clear();
1122
Eli Friedman59c04372009-07-29 19:44:27 +00001123 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001124 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001125 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001126}
1127
1128Sema::MemInitResult
1129Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1130 unsigned NumArgs, SourceLocation IdLoc,
1131 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1132 bool HasDependentArg = false;
1133 for (unsigned i = 0; i < NumArgs; i++)
1134 HasDependentArg |= Args[i]->isTypeDependent();
1135
1136 if (!BaseType->isDependentType()) {
1137 if (!BaseType->isRecordType())
1138 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1139 << BaseType << SourceRange(IdLoc, RParenLoc);
1140
1141 // C++ [class.base.init]p2:
1142 // [...] Unless the mem-initializer-id names a nonstatic data
1143 // member of the constructor’s class or a direct or virtual base
1144 // of that class, the mem-initializer is ill-formed. A
1145 // mem-initializer-list can initialize a base class using any
1146 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Eli Friedman59c04372009-07-29 19:44:27 +00001148 // First, check for a direct base class.
1149 const CXXBaseSpecifier *DirectBaseSpec = 0;
1150 for (CXXRecordDecl::base_class_const_iterator Base =
1151 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001152 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001153 // We found a direct base of this type. That's what we're
1154 // initializing.
1155 DirectBaseSpec = &*Base;
1156 break;
1157 }
1158 }
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Eli Friedman59c04372009-07-29 19:44:27 +00001160 // Check for a virtual base class.
1161 // FIXME: We might be able to short-circuit this if we know in advance that
1162 // there are no virtual bases.
1163 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1164 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1165 // We haven't found a base yet; search the class hierarchy for a
1166 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001167 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1168 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001169 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001170 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001171 Path != Paths.end(); ++Path) {
1172 if (Path->back().Base->isVirtual()) {
1173 VirtualBaseSpec = Path->back().Base;
1174 break;
1175 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001176 }
1177 }
1178 }
Eli Friedman59c04372009-07-29 19:44:27 +00001179
1180 // C++ [base.class.init]p2:
1181 // If a mem-initializer-id is ambiguous because it designates both
1182 // a direct non-virtual base class and an inherited virtual base
1183 // class, the mem-initializer is ill-formed.
1184 if (DirectBaseSpec && VirtualBaseSpec)
1185 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1186 << BaseType << SourceRange(IdLoc, RParenLoc);
1187 // C++ [base.class.init]p2:
1188 // Unless the mem-initializer-id names a nonstatic data membeer of the
1189 // constructor's class ot a direst or virtual base of that class, the
1190 // mem-initializer is ill-formed.
1191 if (!DirectBaseSpec && !VirtualBaseSpec)
1192 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1193 << BaseType << ClassDecl->getNameAsCString()
1194 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001195 }
1196
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001197 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001198 if (!BaseType->isDependentType() && !HasDependentArg) {
1199 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001200 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001201 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1202
1203 C = PerformInitializationByConstructor(BaseType,
1204 MultiExprArg(*this,
1205 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001206 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001207 Name, IK_Direct,
1208 ConstructorArgs);
1209 if (C) {
1210 // Take over the constructor arguments as our own.
1211 NumArgs = ConstructorArgs.size();
1212 Args = (Expr **)ConstructorArgs.take();
1213 }
Eli Friedman59c04372009-07-29 19:44:27 +00001214 }
1215
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001216 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1217 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1218 ExprTemporaries.clear();
1219
Mike Stump1eb44332009-09-09 15:08:12 +00001220 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001221 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001222}
1223
Eli Friedman80c30da2009-11-09 19:20:36 +00001224bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001225Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001226 CXXBaseOrMemberInitializer **Initializers,
1227 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001228 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001229 // We need to build the initializer AST according to order of construction
1230 // and not what user specified in the Initializers list.
1231 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1232 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1233 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1234 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001235 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001237 for (unsigned i = 0; i < NumInitializers; i++) {
1238 CXXBaseOrMemberInitializer *Member = Initializers[i];
1239 if (Member->isBaseInitializer()) {
1240 if (Member->getBaseClass()->isDependentType())
1241 HasDependentBaseInit = true;
1242 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1243 } else {
1244 AllBaseFields[Member->getMember()] = Member;
1245 }
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001248 if (HasDependentBaseInit) {
1249 // FIXME. This does not preserve the ordering of the initializers.
1250 // Try (with -Wreorder)
1251 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001252 // template<class X> struct B : A<X> {
1253 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001254 // int x1;
1255 // };
1256 // B<int> x;
1257 // On seeing one dependent type, we should essentially exit this routine
1258 // while preserving user-declared initializer list. When this routine is
1259 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001260 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001262 // If we have a dependent base initialization, we can't determine the
1263 // association between initializers and bases; just dump the known
1264 // initializers into the list, and don't try to deal with other bases.
1265 for (unsigned i = 0; i < NumInitializers; i++) {
1266 CXXBaseOrMemberInitializer *Member = Initializers[i];
1267 if (Member->isBaseInitializer())
1268 AllToInit.push_back(Member);
1269 }
1270 } else {
1271 // Push virtual bases before others.
1272 for (CXXRecordDecl::base_class_iterator VBase =
1273 ClassDecl->vbases_begin(),
1274 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1275 if (VBase->getType()->isDependentType())
1276 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001277 if (CXXBaseOrMemberInitializer *Value
1278 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001279 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001280 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001281 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001282 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001283 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001284 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001285 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001286 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001287 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1288 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1289 << 0 << VBase->getType();
1290 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1291 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001292 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001293 continue;
1294 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001295
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001296 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1297 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1298 Constructor->getLocation(), CtorArgs))
1299 continue;
1300
1301 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1302
Anders Carlsson8db68da2009-11-13 20:11:49 +00001303 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1304 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1305 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001306 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001307 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1308 CtorArgs.takeAs<Expr>(),
1309 CtorArgs.size(), Ctor,
1310 SourceLocation(),
1311 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001312 AllToInit.push_back(Member);
1313 }
1314 }
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001316 for (CXXRecordDecl::base_class_iterator Base =
1317 ClassDecl->bases_begin(),
1318 E = ClassDecl->bases_end(); Base != E; ++Base) {
1319 // Virtuals are in the virtual base list and already constructed.
1320 if (Base->isVirtual())
1321 continue;
1322 // Skip dependent types.
1323 if (Base->getType()->isDependentType())
1324 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001325 if (CXXBaseOrMemberInitializer *Value
1326 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001327 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001328 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001329 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001330 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001331 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001332 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001333 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001334 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001335 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1336 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1337 << 0 << Base->getType();
1338 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1339 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001340 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001341 continue;
1342 }
1343
1344 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1345 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1346 Constructor->getLocation(), CtorArgs))
1347 continue;
1348
1349 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001350
Anders Carlsson8db68da2009-11-13 20:11:49 +00001351 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1352 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1353 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001354 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001355 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1356 CtorArgs.takeAs<Expr>(),
1357 CtorArgs.size(), Ctor,
1358 SourceLocation(),
1359 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001360 AllToInit.push_back(Member);
1361 }
1362 }
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001365 // non-static data members.
1366 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1367 E = ClassDecl->field_end(); Field != E; ++Field) {
1368 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001369 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001370 Field->getType()->getAs<RecordType>()) {
1371 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001372 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001373 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001374 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1375 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1376 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1377 // set to the anonymous union data member used in the initializer
1378 // list.
1379 Value->setMember(*Field);
1380 Value->setAnonUnionMember(*FA);
1381 AllToInit.push_back(Value);
1382 break;
1383 }
1384 }
1385 }
1386 continue;
1387 }
1388 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1389 AllToInit.push_back(Value);
1390 continue;
1391 }
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Eli Friedman49c16da2009-11-09 01:05:47 +00001393 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001394 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001395
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001396 QualType FT = Context.getBaseElementType((*Field)->getType());
1397 if (const RecordType* RT = FT->getAs<RecordType>()) {
1398 CXXConstructorDecl *Ctor =
1399 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001400 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001401 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1402 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1403 << 1 << (*Field)->getDeclName();
1404 Diag(Field->getLocation(), diag::note_field_decl);
1405 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1406 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001407 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001408 continue;
1409 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001410
1411 if (FT.isConstQualified() && Ctor->isTrivial()) {
1412 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1413 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1414 << 1 << (*Field)->getDeclName();
1415 Diag((*Field)->getLocation(), diag::note_declared_at);
1416 HadError = true;
1417 }
1418
1419 // Don't create initializers for trivial constructors, since they don't
1420 // actually need to be run.
1421 if (Ctor->isTrivial())
1422 continue;
1423
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001424 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1425 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1426 Constructor->getLocation(), CtorArgs))
1427 continue;
1428
Anders Carlsson8db68da2009-11-13 20:11:49 +00001429 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1430 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1431 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001432 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001433 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1434 CtorArgs.size(), Ctor,
1435 SourceLocation(),
1436 SourceLocation());
1437
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001438 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001439 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001440 }
1441 else if (FT->isReferenceType()) {
1442 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001443 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1444 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001445 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001446 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001447 }
1448 else if (FT.isConstQualified()) {
1449 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001450 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1451 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001452 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001453 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001454 }
1455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001457 NumInitializers = AllToInit.size();
1458 if (NumInitializers > 0) {
1459 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1460 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1461 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001463 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1464 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1465 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1466 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001467
1468 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001469}
1470
Eli Friedman6347f422009-07-21 19:28:10 +00001471static void *GetKeyForTopLevelField(FieldDecl *Field) {
1472 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001473 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001474 if (RT->getDecl()->isAnonymousStructOrUnion())
1475 return static_cast<void *>(RT->getDecl());
1476 }
1477 return static_cast<void *>(Field);
1478}
1479
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001480static void *GetKeyForBase(QualType BaseType) {
1481 if (const RecordType *RT = BaseType->getAs<RecordType>())
1482 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001484 assert(0 && "Unexpected base type!");
1485 return 0;
1486}
1487
Mike Stump1eb44332009-09-09 15:08:12 +00001488static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001489 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001490 // For fields injected into the class via declaration of an anonymous union,
1491 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001492 if (Member->isMemberInitializer()) {
1493 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Eli Friedman49c16da2009-11-09 01:05:47 +00001495 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001496 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001497 // in AnonUnionMember field.
1498 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1499 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001500 if (Field->getDeclContext()->isRecord()) {
1501 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1502 if (RD->isAnonymousStructOrUnion())
1503 return static_cast<void *>(RD);
1504 }
1505 return static_cast<void *>(Field);
1506 }
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001508 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001509}
1510
John McCall6aee6212009-11-04 23:13:52 +00001511/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001512void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001513 SourceLocation ColonLoc,
1514 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001515 if (!ConstructorDecl)
1516 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001517
1518 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001519
1520 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001521 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Anders Carlssona7b35212009-03-25 02:58:17 +00001523 if (!Constructor) {
1524 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1525 return;
1526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001528 if (!Constructor->isDependentContext()) {
1529 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1530 bool err = false;
1531 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001532 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001533 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1534 void *KeyToMember = GetKeyForMember(Member);
1535 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1536 if (!PrevMember) {
1537 PrevMember = Member;
1538 continue;
1539 }
1540 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001541 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001542 diag::error_multiple_mem_initialization)
1543 << Field->getNameAsString();
1544 else {
1545 Type *BaseClass = Member->getBaseClass();
1546 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001547 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001548 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001549 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001550 }
1551 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1552 << 0;
1553 err = true;
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001556 if (err)
1557 return;
1558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Eli Friedman49c16da2009-11-09 01:05:47 +00001560 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001561 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001562 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001564 if (Constructor->isDependentContext())
1565 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001566
1567 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001568 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001569 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001570 Diagnostic::Ignored)
1571 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001573 // Also issue warning if order of ctor-initializer list does not match order
1574 // of 1) base class declarations and 2) order of non-static data members.
1575 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001577 CXXRecordDecl *ClassDecl
1578 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1579 // Push virtual bases before others.
1580 for (CXXRecordDecl::base_class_iterator VBase =
1581 ClassDecl->vbases_begin(),
1582 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001583 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001585 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1586 E = ClassDecl->bases_end(); Base != E; ++Base) {
1587 // Virtuals are alread in the virtual base list and are constructed
1588 // first.
1589 if (Base->isVirtual())
1590 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001591 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001594 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1595 E = ClassDecl->field_end(); Field != E; ++Field)
1596 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001598 int Last = AllBaseOrMembers.size();
1599 int curIndex = 0;
1600 CXXBaseOrMemberInitializer *PrevMember = 0;
1601 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001602 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001603 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1604 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001605
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001606 for (; curIndex < Last; curIndex++)
1607 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1608 break;
1609 if (curIndex == Last) {
1610 assert(PrevMember && "Member not in member list?!");
1611 // Initializer as specified in ctor-initializer list is out of order.
1612 // Issue a warning diagnostic.
1613 if (PrevMember->isBaseInitializer()) {
1614 // Diagnostics is for an initialized base class.
1615 Type *BaseClass = PrevMember->getBaseClass();
1616 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001617 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001618 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001619 } else {
1620 FieldDecl *Field = PrevMember->getMember();
1621 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001622 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001623 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001624 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001625 // Also the note!
1626 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001627 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001628 diag::note_fieldorbase_initialized_here) << 0
1629 << Field->getNameAsString();
1630 else {
1631 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001632 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001633 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001634 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001635 }
1636 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001637 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001638 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001639 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001640 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001641 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001642}
1643
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001644void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001645Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1646 // Ignore dependent destructors.
1647 if (Destructor->isDependentContext())
1648 return;
1649
1650 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Anders Carlsson9f853df2009-11-17 04:44:12 +00001652 // Non-static data members.
1653 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1654 E = ClassDecl->field_end(); I != E; ++I) {
1655 FieldDecl *Field = *I;
1656
1657 QualType FieldType = Context.getBaseElementType(Field->getType());
1658
1659 const RecordType* RT = FieldType->getAs<RecordType>();
1660 if (!RT)
1661 continue;
1662
1663 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1664 if (FieldClassDecl->hasTrivialDestructor())
1665 continue;
1666
1667 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1668 MarkDeclarationReferenced(Destructor->getLocation(),
1669 const_cast<CXXDestructorDecl*>(Dtor));
1670 }
1671
1672 // Bases.
1673 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1674 E = ClassDecl->bases_end(); Base != E; ++Base) {
1675 // Ignore virtual bases.
1676 if (Base->isVirtual())
1677 continue;
1678
1679 // Ignore trivial destructors.
1680 CXXRecordDecl *BaseClassDecl
1681 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1682 if (BaseClassDecl->hasTrivialDestructor())
1683 continue;
1684
1685 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1686 MarkDeclarationReferenced(Destructor->getLocation(),
1687 const_cast<CXXDestructorDecl*>(Dtor));
1688 }
1689
1690 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001691 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1692 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001693 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001694 CXXRecordDecl *BaseClassDecl
1695 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1696 if (BaseClassDecl->hasTrivialDestructor())
1697 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001698
1699 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1700 MarkDeclarationReferenced(Destructor->getLocation(),
1701 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001702 }
1703}
1704
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001705void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001706 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001707 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001709 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001710
1711 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001712 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001713 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001714}
1715
Anders Carlsson67e4dd22009-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 Redldfe292d2009-03-22 21:28:55 +00001722 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001723 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001724
1725 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001726 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001728 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001730 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001731 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001732 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001734 MethodList List;
1735 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Anders Carlsson67e4dd22009-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 Stump1eb44332009-09-09 15:08:12 +00001742 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001743 }
Mike Stump1eb44332009-09-09 15:08:12 +00001744
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001745 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001747 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1748 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001749 };
Mike Stump1eb44332009-09-09 15:08:12 +00001750
1751 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-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 Kremenek6217b802009-07-29 21:53:49 +00001756 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001757 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001758 if (BaseDecl && BaseDecl->isAbstract())
1759 Collect(BaseDecl, Methods);
1760 }
1761 }
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001763 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001764 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001766 MethodSetTy OverriddenMethods;
1767 size_t MethodsSize = Methods.size();
1768
Mike Stump1eb44332009-09-09 15:08:12 +00001769 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-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 Redl23c7d062009-07-07 20:29:57 +00001773 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001774 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001775 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Anders Carlsson27823022009-10-18 19:34:08 +00001777 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-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 Carlsson67e4dd22009-03-22 01:52:17 +00001782 }
1783 }
1784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785
1786 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-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 Carlsson67e4dd22009-03-22 01:52:17 +00001791 }
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001793 }
1794}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001795
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001796
Mike Stump1eb44332009-09-09 15:08:12 +00001797bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001798 unsigned DiagID, AbstractDiagSelID SelID,
1799 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-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 Stump1eb44332009-09-09 15:08:12 +00001806}
1807
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001808bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1809 const PartialDiagnostic &PD,
1810 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001811 if (!getLangOptions().CPlusPlus)
1812 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Anders Carlsson11f21a02009-03-23 19:10:31 +00001814 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001815 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001816 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Ted Kremenek6217b802009-07-29 21:53:49 +00001818 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001819 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001820 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001821 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001823 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001824 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001825 }
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Ted Kremenek6217b802009-07-29 21:53:49 +00001827 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001828 if (!RT)
1829 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001831 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1832 if (!RD)
1833 return false;
1834
Anders Carlssone65a3c82009-03-24 17:23:42 +00001835 if (CurrentRD && CurrentRD != RD)
1836 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001838 if (!RD->isAbstract())
1839 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001841 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Anders Carlsson4681ebd2009-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 Stump1eb44332009-09-09 15:08:12 +00001847
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001848 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001849
1850 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001851 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1852 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001853
1854 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001855 MD->getDeclName();
1856 }
1857
1858 if (!PureVirtualClassDiagSet)
1859 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1860 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001862 return true;
1863}
1864
Anders Carlsson8211eff2009-03-24 01:19:16 +00001865namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001866 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001867 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1868 Sema &SemaRef;
1869 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Anders Carlssone65a3c82009-03-24 17:23:42 +00001871 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001872 bool Invalid = false;
1873
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001874 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1875 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001876 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001877
Anders Carlsson8211eff2009-03-24 01:19:16 +00001878 return Invalid;
1879 }
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Anders Carlssone65a3c82009-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 Carlsson8211eff2009-03-24 01:19:16 +00001886
Anders Carlssone65a3c82009-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 Stump1eb44332009-09-09 15:08:12 +00001891 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001892 return VisitDeclContext(FD);
1893 }
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Anders Carlssone65a3c82009-03-24 17:23:42 +00001895 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001896 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001897 bool Invalid =
Anders Carlssone65a3c82009-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 Stump1eb44332009-09-09 15:08:12 +00001903 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001904 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001905 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001906 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001907 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001908 VD->getOriginalType(),
1909 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001910 Sema::AbstractParamType,
1911 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001912 }
1913
1914 return Invalid;
1915 }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Anders Carlssone65a3c82009-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 Stump1eb44332009-09-09 15:08:12 +00001920
Anders Carlssone65a3c82009-03-24 17:23:42 +00001921 return false;
1922 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001923 };
1924}
1925
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001926void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001927 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001928 SourceLocation LBrac,
1929 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001930 if (!TagDecl)
1931 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Douglas Gregor42af25f2009-05-11 19:58:34 +00001933 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001934 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001935 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001936 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001937
Chris Lattnerb28317a2009-03-28 19:18:32 +00001938 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-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 Stump1eb44332009-09-09 15:08:12 +00001943 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001944 RD->setAbstract(true);
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
1947 if (RD->isAbstract())
Douglas Gregor6490ae52009-11-17 06:14:37 +00001948 (void)AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Douglas Gregor663b5a02009-10-14 20:14:33 +00001950 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001951 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001952}
1953
Douglas Gregor396b7cd2008-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 Stump1eb44332009-09-09 15:08:12 +00001960 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001961 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001962
Sebastian Redl465226e2009-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 Gregor396b7cd2008-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 Stump1eb44332009-09-09 15:08:12 +00001973 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001974 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001975 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001976 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001977 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001978 Context.getFunctionType(Context.VoidTy,
1979 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001980 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001981 /*isExplicit=*/false,
1982 /*isInline=*/true,
1983 /*isImplicitlyDeclared=*/true);
1984 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001985 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001986 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001987 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-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 Kremenek6217b802009-07-29 21:53:49 +00002010 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002011 HasConstCopyConstructor
Douglas Gregor396b7cd2008-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 Kyrtzidis17945a02009-06-30 02:36:12 +00002019 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2020 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002021 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002022 QualType FieldType = (*Field)->getType();
2023 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2024 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002025 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002026 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002027 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002028 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002029 = FieldClassDecl->hasConstCopyConstructor(Context);
2030 }
2031 }
2032
Sebastian Redl64b45f72009-01-05 20:52:13 +00002033 // Otherwise, the implicitly declared copy constructor will have
2034 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002035 //
2036 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002037 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002038 if (HasConstCopyConstructor)
2039 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002040 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002041
Sebastian Redl64b45f72009-01-05 20:52:13 +00002042 // An implicitly-declared copy constructor is an inline public
2043 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002044 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002045 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002046 CXXConstructorDecl *CopyConstructor
2047 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002048 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002049 Context.getFunctionType(Context.VoidTy,
2050 &ArgType, 1,
2051 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002052 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002053 /*isExplicit=*/false,
2054 /*isInline=*/true,
2055 /*isImplicitlyDeclared=*/true);
2056 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002057 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002058 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-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 Kyrtzidisa1d56622009-08-19 01:27:57 +00002064 ArgType, /*DInfo=*/0,
2065 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002066 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002067 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002068 }
2069
Sebastian Redl64b45f72009-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 Redl9994a342009-10-25 17:03:50 +00002092 assert(!Base->getType()->isDependentType() &&
2093 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002094 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002095 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002096 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002097 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002098 MD);
Sebastian Redl64b45f72009-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 Kyrtzidis17945a02009-06-30 02:36:12 +00002105 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2106 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002107 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002108 QualType FieldType = (*Field)->getType();
2109 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2110 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002111 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002112 const CXXRecordDecl *FieldClassDecl
2113 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002114 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002115 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002116 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-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 Redl7c80bd62009-03-16 23:22:08 +00002125 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002126 if (HasConstCopyAssignment)
2127 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002128 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-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 Kyrtzidisa1d56622009-08-19 01:27:57 +00002138 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002139 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002140 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002141 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002142 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-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 Kyrtzidisa1d56622009-08-19 01:27:57 +00002148 ArgType, /*DInfo=*/0,
2149 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002150 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-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 Kyrtzidis17945a02009-06-30 02:36:12 +00002154 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002155 }
2156
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002157 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-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 Stump1eb44332009-09-09 15:08:12 +00002162 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002163 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002164 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002165 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002166 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-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 Gregor6b3945f2009-01-07 19:46:03 +00002172 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002173 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002174 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002175 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002176}
2177
Douglas Gregor6569d682009-05-27 23:11:45 +00002178void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-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 Gregor6569d682009-05-27 23:11:45 +00002190 return;
2191
Douglas Gregor6569d682009-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 Gregor72b505b2008-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 Lattnerb28317a2009-03-28 19:18:32 +00002211void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002212 if (!MethodD)
2213 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002215 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Douglas Gregor72b505b2008-12-16 21:30:33 +00002217 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002218 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002219 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002220 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2221 SS.setScopeRep(
2222 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-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 Lattnerb28317a2009-03-28 19:18:32 +00002231void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002232 if (!ParamD)
2233 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Chris Lattnerb28317a2009-03-28 19:18:32 +00002235 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-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 Lattnerb28317a2009-03-28 19:18:32 +00002242 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-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 Lattnerb28317a2009-03-28 19:18:32 +00002253void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002254 if (!MethodD)
2255 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002257 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Chris Lattnerb28317a2009-03-28 19:18:32 +00002259 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002260 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002261 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002262 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2263 SS.setScopeRep(
2264 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-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 Lattner6e475012009-04-25 08:35:12 +00002271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2272 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-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 Gregor42a552f2008-11-05 20:51:48 +00002279/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002280/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002281/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-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 Gregor42a552f2008-11-05 20:51:48 +00002287 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-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 Lattner65401802009-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 Gregor42a552f2008-11-05 20:51:48 +00002300 }
2301 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-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 Gregor42a552f2008-11-05 20:51:48 +00002307 SC = FunctionDecl::None;
2308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Chris Lattner65401802009-04-25 08:28:21 +00002310 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2311 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002312 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2314 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002315 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002316 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2317 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002318 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002319 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2320 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002321 }
Mike Stump1eb44332009-09-09 15:08:12 +00002322
Douglas Gregor42a552f2008-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 McCall183700f2009-09-21 23:43:11 +00002328 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002329 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2330 Proto->getNumArgs(),
2331 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002332}
2333
Douglas Gregor72b505b2008-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 Lattner6e475012009-04-25 08:35:12 +00002337void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002338 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002339 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2340 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002341 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-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 Gregor33297562009-03-27 04:38:56 +00002348 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002349 ((Constructor->getNumParams() == 1) ||
2350 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002351 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2352 Constructor->getTemplateSpecializationKind()
2353 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-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 Gregora3a83512009-04-01 23:51:29 +00002357 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2358 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002359 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002360
2361 // FIXME: Rather that making the constructor invalid, we should endeavor
2362 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002363 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002364 }
2365 }
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Douglas Gregor72b505b2008-12-16 21:30:33 +00002367 // Notify the class that we've added a constructor.
2368 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002369}
2370
Anders Carlsson6d701392009-11-15 22:49:34 +00002371/// CheckDestructor - Checks a fully-formed destructor for
2372/// well-formedness, issuing any diagnostics required.
2373void Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2374 CXXRecordDecl *RD = Destructor->getParent();
2375
2376 if (Destructor->isVirtual()) {
2377 SourceLocation Loc;
2378
2379 if (!Destructor->isImplicit())
2380 Loc = Destructor->getLocation();
2381 else
2382 Loc = RD->getLocation();
2383
2384 // If we have a virtual destructor, look up the deallocation function
2385 FunctionDecl *OperatorDelete = 0;
2386 DeclarationName Name =
2387 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2388 if (!FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2389 Destructor->setOperatorDelete(OperatorDelete);
2390 }
2391}
2392
Mike Stump1eb44332009-09-09 15:08:12 +00002393static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002394FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2395 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2396 FTI.ArgInfo[0].Param &&
2397 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2398}
2399
Douglas Gregor42a552f2008-11-05 20:51:48 +00002400/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2401/// the well-formednes of the destructor declarator @p D with type @p
2402/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002403/// emit diagnostics and set the declarator to invalid. Even if this happens,
2404/// will be updated to reflect a well-formed type for the destructor and
2405/// returned.
2406QualType Sema::CheckDestructorDeclarator(Declarator &D,
2407 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002408 // C++ [class.dtor]p1:
2409 // [...] A typedef-name that names a class is a class-name
2410 // (7.1.3); however, a typedef-name that names a class shall not
2411 // be used as the identifier in the declarator for a destructor
2412 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002413 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002414 if (isa<TypedefType>(DeclaratorType)) {
2415 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002416 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002417 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002418 }
2419
2420 // C++ [class.dtor]p2:
2421 // A destructor is used to destroy objects of its class type. A
2422 // destructor takes no parameters, and no return type can be
2423 // specified for it (not even void). The address of a destructor
2424 // shall not be taken. A destructor shall not be static. A
2425 // destructor can be invoked for a const, volatile or const
2426 // volatile object. A destructor shall not be declared const,
2427 // volatile or const volatile (9.3.2).
2428 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002429 if (!D.isInvalidType())
2430 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2431 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2432 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002433 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002434 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002435 }
Chris Lattner65401802009-04-25 08:28:21 +00002436 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002437 // Destructors don't have return types, but the parser will
2438 // happily parse something like:
2439 //
2440 // class X {
2441 // float ~X();
2442 // };
2443 //
2444 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002445 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2446 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2447 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Chris Lattner65401802009-04-25 08:28:21 +00002450 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2451 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002452 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002453 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2454 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002455 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002456 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2457 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002458 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002459 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2460 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002461 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002462 }
2463
2464 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002465 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002466 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2467
2468 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002469 FTI.freeArgs();
2470 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002471 }
2472
Mike Stump1eb44332009-09-09 15:08:12 +00002473 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002474 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002475 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002476 D.setInvalidType();
2477 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002478
2479 // Rebuild the function type "R" without any type qualifiers or
2480 // parameters (in case any of the errors above fired) and with
2481 // "void" as the return type, since destructors don't have return
2482 // types. We *always* have to do this, because GetTypeForDeclarator
2483 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002484 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002485}
2486
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002487/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2488/// well-formednes of the conversion function declarator @p D with
2489/// type @p R. If there are any errors in the declarator, this routine
2490/// will emit diagnostics and return true. Otherwise, it will return
2491/// false. Either way, the type @p R will be updated to reflect a
2492/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002493void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002494 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002495 // C++ [class.conv.fct]p1:
2496 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002497 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002498 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002499 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002500 if (!D.isInvalidType())
2501 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2502 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2503 << SourceRange(D.getIdentifierLoc());
2504 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002505 SC = FunctionDecl::None;
2506 }
Chris Lattner6e475012009-04-25 08:35:12 +00002507 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002508 // Conversion functions don't have return types, but the parser will
2509 // happily parse something like:
2510 //
2511 // class X {
2512 // float operator bool();
2513 // };
2514 //
2515 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002516 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2517 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2518 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002519 }
2520
2521 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002522 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002523 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2524
2525 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002526 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002527 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002528 }
2529
Mike Stump1eb44332009-09-09 15:08:12 +00002530 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002531 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002532 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002533 D.setInvalidType();
2534 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002535
2536 // C++ [class.conv.fct]p4:
2537 // The conversion-type-id shall not represent a function type nor
2538 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002539 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002540 if (ConvType->isArrayType()) {
2541 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2542 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002543 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002544 } else if (ConvType->isFunctionType()) {
2545 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2546 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002547 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002548 }
2549
2550 // Rebuild the function type "R" without any parameters (in case any
2551 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002552 // return type.
2553 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002554 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002555
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002556 // C++0x explicit conversion operators.
2557 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002558 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002559 diag::warn_explicit_conversion_functions)
2560 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002561}
2562
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002563/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2564/// the declaration of the given C++ conversion function. This routine
2565/// is responsible for recording the conversion function in the C++
2566/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002567Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002568 assert(Conversion && "Expected to receive a conversion function declaration");
2569
Douglas Gregor9d350972008-12-12 08:25:50 +00002570 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002571
2572 // Make sure we aren't redeclaring the conversion function.
2573 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002574
2575 // C++ [class.conv.fct]p1:
2576 // [...] A conversion function is never used to convert a
2577 // (possibly cv-qualified) object to the (possibly cv-qualified)
2578 // same object type (or a reference to it), to a (possibly
2579 // cv-qualified) base class of that type (or a reference to it),
2580 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002581 // FIXME: Suppress this warning if the conversion function ends up being a
2582 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002583 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002584 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002585 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002586 ConvType = ConvTypeRef->getPointeeType();
2587 if (ConvType->isRecordType()) {
2588 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2589 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002590 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002591 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002592 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002593 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002594 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002595 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002596 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002597 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002598 }
2599
Douglas Gregor70316a02008-12-26 15:00:45 +00002600 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002601 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002602 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002603 = Conversion->getDescribedFunctionTemplate())
2604 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002605 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2606 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002607 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002608 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002609 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002610 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002611 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002612 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002613
Chris Lattnerb28317a2009-03-28 19:18:32 +00002614 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002615}
2616
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002617//===----------------------------------------------------------------------===//
2618// Namespace Handling
2619//===----------------------------------------------------------------------===//
2620
2621/// ActOnStartNamespaceDef - This is called at the start of a namespace
2622/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002623Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2624 SourceLocation IdentLoc,
2625 IdentifierInfo *II,
2626 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002627 NamespaceDecl *Namespc =
2628 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2629 Namespc->setLBracLoc(LBrace);
2630
2631 Scope *DeclRegionScope = NamespcScope->getParent();
2632
2633 if (II) {
2634 // C++ [namespace.def]p2:
2635 // The identifier in an original-namespace-definition shall not have been
2636 // previously defined in the declarative region in which the
2637 // original-namespace-definition appears. The identifier in an
2638 // original-namespace-definition is the name of the namespace. Subsequently
2639 // in that declarative region, it is treated as an original-namespace-name.
2640
John McCallf36e02d2009-10-09 21:13:30 +00002641 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002642 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002643 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Douglas Gregor44b43212008-12-11 16:49:14 +00002645 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2646 // This is an extended namespace definition.
2647 // Attach this namespace decl to the chain of extended namespace
2648 // definitions.
2649 OrigNS->setNextNamespace(Namespc);
2650 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002651
Mike Stump1eb44332009-09-09 15:08:12 +00002652 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002653 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002654 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002655 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002656 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002657 } else if (PrevDecl) {
2658 // This is an invalid name redefinition.
2659 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2660 << Namespc->getDeclName();
2661 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2662 Namespc->setInvalidDecl();
2663 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002664 } else if (II->isStr("std") &&
2665 CurContext->getLookupContext()->isTranslationUnit()) {
2666 // This is the first "real" definition of the namespace "std", so update
2667 // our cache of the "std" namespace to point at this definition.
2668 if (StdNamespace) {
2669 // We had already defined a dummy namespace "std". Link this new
2670 // namespace definition to the dummy namespace "std".
2671 StdNamespace->setNextNamespace(Namespc);
2672 StdNamespace->setLocation(IdentLoc);
2673 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2674 }
2675
2676 // Make our StdNamespace cache point at the first real definition of the
2677 // "std" namespace.
2678 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002679 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002680
2681 PushOnScopeChains(Namespc, DeclRegionScope);
2682 } else {
John McCall9aeed322009-10-01 00:25:31 +00002683 // Anonymous namespaces.
2684
2685 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2686 // behaves as if it were replaced by
2687 // namespace unique { /* empty body */ }
2688 // using namespace unique;
2689 // namespace unique { namespace-body }
2690 // where all occurrences of 'unique' in a translation unit are
2691 // replaced by the same identifier and this identifier differs
2692 // from all other identifiers in the entire program.
2693
2694 // We just create the namespace with an empty name and then add an
2695 // implicit using declaration, just like the standard suggests.
2696 //
2697 // CodeGen enforces the "universally unique" aspect by giving all
2698 // declarations semantically contained within an anonymous
2699 // namespace internal linkage.
2700
2701 assert(Namespc->isAnonymousNamespace());
2702 CurContext->addDecl(Namespc);
2703
2704 UsingDirectiveDecl* UD
2705 = UsingDirectiveDecl::Create(Context, CurContext,
2706 /* 'using' */ LBrace,
2707 /* 'namespace' */ SourceLocation(),
2708 /* qualifier */ SourceRange(),
2709 /* NNS */ NULL,
2710 /* identifier */ SourceLocation(),
2711 Namespc,
2712 /* Ancestor */ CurContext);
2713 UD->setImplicit();
2714 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002715 }
2716
2717 // Although we could have an invalid decl (i.e. the namespace name is a
2718 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002719 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2720 // for the namespace has the declarations that showed up in that particular
2721 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002722 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002723 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002724}
2725
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002726/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2727/// is a namespace alias, returns the namespace it points to.
2728static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2729 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2730 return AD->getNamespace();
2731 return dyn_cast_or_null<NamespaceDecl>(D);
2732}
2733
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002734/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2735/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002736void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2737 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002738 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2739 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2740 Namespc->setRBracLoc(RBrace);
2741 PopDeclContext();
2742}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002743
Chris Lattnerb28317a2009-03-28 19:18:32 +00002744Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2745 SourceLocation UsingLoc,
2746 SourceLocation NamespcLoc,
2747 const CXXScopeSpec &SS,
2748 SourceLocation IdentLoc,
2749 IdentifierInfo *NamespcName,
2750 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002751 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2752 assert(NamespcName && "Invalid NamespcName.");
2753 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002754 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002755
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002756 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002757
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002758 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002759 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2760 LookupParsedName(R, S, &SS);
2761 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002762 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002763
John McCallf36e02d2009-10-09 21:13:30 +00002764 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002765 NamedDecl *Named = R.getFoundDecl();
2766 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2767 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002768 // C++ [namespace.udir]p1:
2769 // A using-directive specifies that the names in the nominated
2770 // namespace can be used in the scope in which the
2771 // using-directive appears after the using-directive. During
2772 // unqualified name lookup (3.4.1), the names appear as if they
2773 // were declared in the nearest enclosing namespace which
2774 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002775 // namespace. [Note: in this context, "contains" means "contains
2776 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002777
2778 // Find enclosing context containing both using-directive and
2779 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002780 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002781 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2782 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2783 CommonAncestor = CommonAncestor->getParent();
2784
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002785 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002786 SS.getRange(),
2787 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002788 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002789 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002790 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002791 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002792 }
2793
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002794 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002795 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002796 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002797}
2798
2799void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2800 // If scope has associated entity, then using directive is at namespace
2801 // or translation unit scope. We add UsingDirectiveDecls, into
2802 // it's lookup structure.
2803 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002804 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002805 else
2806 // Otherwise it is block-sope. using-directives will affect lookup
2807 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002808 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002809}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002810
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002811
2812Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002813 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002814 SourceLocation UsingLoc,
2815 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002816 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002817 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002818 bool IsTypeName,
2819 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002820 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Douglas Gregor12c118a2009-11-04 16:30:06 +00002822 switch (Name.getKind()) {
2823 case UnqualifiedId::IK_Identifier:
2824 case UnqualifiedId::IK_OperatorFunctionId:
2825 case UnqualifiedId::IK_ConversionFunctionId:
2826 break;
2827
2828 case UnqualifiedId::IK_ConstructorName:
2829 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2830 << SS.getRange();
2831 return DeclPtrTy();
2832
2833 case UnqualifiedId::IK_DestructorName:
2834 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2835 << SS.getRange();
2836 return DeclPtrTy();
2837
2838 case UnqualifiedId::IK_TemplateId:
2839 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2840 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2841 return DeclPtrTy();
2842 }
2843
2844 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall9488ea12009-11-17 05:59:44 +00002845 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002846 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002847 TargetName, AttrList,
2848 /* IsInstantiation */ false,
2849 IsTypeName, TypenameLoc);
Anders Carlsson595adc12009-08-29 19:54:19 +00002850 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002851 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002852 UD->setAccess(AS);
2853 }
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Anders Carlssonc72160b2009-08-28 05:40:36 +00002855 return DeclPtrTy::make(UD);
2856}
2857
John McCall9488ea12009-11-17 05:59:44 +00002858/// Builds a shadow declaration corresponding to a 'using' declaration.
2859static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2860 AccessSpecifier AS,
2861 UsingDecl *UD, NamedDecl *Orig) {
2862 // FIXME: diagnose hiding, collisions
2863
2864 // If we resolved to another shadow declaration, just coalesce them.
2865 if (isa<UsingShadowDecl>(Orig)) {
2866 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2867 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2868 }
2869
2870 UsingShadowDecl *Shadow
2871 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2872 UD->getLocation(), UD, Orig);
2873 UD->addShadowDecl(Shadow);
2874
2875 if (S)
2876 SemaRef.PushOnScopeChains(Shadow, S);
2877 else
2878 SemaRef.CurContext->addDecl(Shadow);
2879 Shadow->setAccess(AS);
2880
2881 return Shadow;
2882}
2883
John McCall7ba107a2009-11-18 02:36:19 +00002884/// Builds a using declaration.
2885///
2886/// \param IsInstantiation - Whether this call arises from an
2887/// instantiation of an unresolved using declaration. We treat
2888/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00002889NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2890 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002891 const CXXScopeSpec &SS,
2892 SourceLocation IdentLoc,
2893 DeclarationName Name,
2894 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002895 bool IsInstantiation,
2896 bool IsTypeName,
2897 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002898 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2899 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002900
Anders Carlsson550b14b2009-08-28 05:49:21 +00002901 // FIXME: We ignore attributes for now.
2902 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002903
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002904 if (SS.isEmpty()) {
2905 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002906 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002907 }
Mike Stump1eb44332009-09-09 15:08:12 +00002908
2909 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002910 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2911
John McCallaf8e6ed2009-11-12 03:15:40 +00002912 DeclContext *LookupContext = computeDeclContext(SS);
2913 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00002914 if (IsTypeName) {
2915 return UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2916 UsingLoc, TypenameLoc,
2917 SS.getRange(), NNS,
2918 IdentLoc, Name);
2919 } else {
2920 return UnresolvedUsingValueDecl::Create(Context, CurContext,
2921 UsingLoc, SS.getRange(), NNS,
2922 IdentLoc, Name);
2923 }
Anders Carlsson550b14b2009-08-28 05:49:21 +00002924 }
Mike Stump1eb44332009-09-09 15:08:12 +00002925
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002926 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2927 // C++0x N2914 [namespace.udecl]p3:
2928 // A using-declaration used as a member-declaration shall refer to a member
2929 // of a base class of the class being defined, shall refer to a member of an
2930 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002931 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002932 // a member of a base class of the class being defined.
John McCall9488ea12009-11-17 05:59:44 +00002933
John McCallaf8e6ed2009-11-12 03:15:40 +00002934 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2935 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002936 Diag(SS.getRange().getBegin(),
2937 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2938 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002939 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002940 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002941 } else {
2942 // C++0x N2914 [namespace.udecl]p8:
2943 // A using-declaration for a class member shall be a member-declaration.
John McCallaf8e6ed2009-11-12 03:15:40 +00002944 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002945 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002946 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002947 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002948 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002949 }
2950
John McCall9488ea12009-11-17 05:59:44 +00002951 // Look up the target name. Unlike most lookups, we do not want to
2952 // hide tag declarations: tag names are visible through the using
2953 // declaration even if hidden by ordinary names.
John McCalla24dc2e2009-11-17 02:14:36 +00002954 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00002955
2956 // We don't hide tags behind ordinary decls if we're in a
2957 // non-dependent context, but in a dependent context, this is
2958 // important for the stability of two-phase lookup.
2959 if (!IsInstantiation)
2960 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00002961
John McCalla24dc2e2009-11-17 02:14:36 +00002962 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002963
John McCallf36e02d2009-10-09 21:13:30 +00002964 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002965 Diag(IdentLoc, diag::err_no_member)
2966 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002967 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002968 }
2969
John McCall9488ea12009-11-17 05:59:44 +00002970 if (R.isAmbiguous())
2971 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002972
John McCall7ba107a2009-11-18 02:36:19 +00002973 if (IsTypeName) {
2974 // If we asked for a typename and got a non-type decl, error out.
2975 if (R.getResultKind() != LookupResult::Found
2976 || !isa<TypeDecl>(R.getFoundDecl())) {
2977 Diag(IdentLoc, diag::err_using_typename_non_type);
2978 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2979 Diag((*I)->getUnderlyingDecl()->getLocation(),
2980 diag::note_using_decl_target);
2981 return 0;
2982 }
2983 } else {
2984 // If we asked for a non-typename and we got a type, error out,
2985 // but only if this is an instantiation of an unresolved using
2986 // decl. Otherwise just silently find the type name.
2987 if (IsInstantiation &&
2988 R.getResultKind() == LookupResult::Found &&
2989 isa<TypeDecl>(R.getFoundDecl())) {
2990 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
2991 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
2992 return 0;
2993 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002994 }
2995
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002996 // C++0x N2914 [namespace.udecl]p6:
2997 // A using-declaration shall not name a namespace.
John McCall9488ea12009-11-17 05:59:44 +00002998 if (R.getResultKind() == LookupResult::Found
2999 && isa<NamespaceDecl>(R.getFoundDecl())) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003000 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3001 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003002 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003003 }
Mike Stump1eb44332009-09-09 15:08:12 +00003004
John McCall9488ea12009-11-17 05:59:44 +00003005 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc,
3006 SS.getRange(), UsingLoc, NNS, Name,
3007 IsTypeName);
3008
3009 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3010 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3011
3012 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003013}
3014
Mike Stump1eb44332009-09-09 15:08:12 +00003015Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003016 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003017 SourceLocation AliasLoc,
3018 IdentifierInfo *Alias,
3019 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003020 SourceLocation IdentLoc,
3021 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Anders Carlsson81c85c42009-03-28 23:53:49 +00003023 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003024 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3025 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003026
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003027 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003028 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003029 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003030 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003031 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003032 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003033 if (!R.isAmbiguous() && !R.empty() &&
3034 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003035 return DeclPtrTy();
3036 }
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003038 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3039 diag::err_redefinition_different_kind;
3040 Diag(AliasLoc, DiagID) << Alias;
3041 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003042 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003043 }
3044
John McCalla24dc2e2009-11-17 02:14:36 +00003045 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003046 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003047
John McCallf36e02d2009-10-09 21:13:30 +00003048 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003049 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003050 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003051 }
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003053 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003054 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3055 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003056 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003057 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003059 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003060 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003061}
3062
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003063void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3064 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003065 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3066 !Constructor->isUsed()) &&
3067 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Eli Friedman80c30da2009-11-09 19:20:36 +00003069 CXXRecordDecl *ClassDecl
3070 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3071 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003072
Eli Friedman80c30da2009-11-09 19:20:36 +00003073 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
3074 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
3075 << Context.getTagDeclType(ClassDecl);
3076 Constructor->setInvalidDecl();
3077 } else {
3078 Constructor->setUsed();
3079 }
Eli Friedman49c16da2009-11-09 01:05:47 +00003080 return;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003081}
3082
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003083void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003084 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003085 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3086 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003087 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003088 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3089 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003090 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003091 // implicitly defined, all the implicitly-declared default destructors
3092 // for its base class and its non-static data members shall have been
3093 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003094 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3095 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003096 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003097 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003098 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003099 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003100 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3101 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3102 else
Mike Stump1eb44332009-09-09 15:08:12 +00003103 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003104 "DefineImplicitDestructor - missing dtor in a base class");
3105 }
3106 }
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003108 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3109 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003110 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3111 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3112 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003113 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003114 CXXRecordDecl *FieldClassDecl
3115 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3116 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003117 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003118 const_cast<CXXDestructorDecl*>(
3119 FieldClassDecl->getDestructor(Context)))
3120 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3121 else
Mike Stump1eb44332009-09-09 15:08:12 +00003122 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003123 "DefineImplicitDestructor - missing dtor in class of a data member");
3124 }
3125 }
3126 }
3127 Destructor->setUsed();
3128}
3129
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003130void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3131 CXXMethodDecl *MethodDecl) {
3132 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3133 MethodDecl->getOverloadedOperator() == OO_Equal &&
3134 !MethodDecl->isUsed()) &&
3135 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003137 CXXRecordDecl *ClassDecl
3138 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003140 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003141 // Before the implicitly-declared copy assignment operator for a class is
3142 // implicitly defined, all implicitly-declared copy assignment operators
3143 // for its direct base classes and its nonstatic data members shall have
3144 // been implicitly defined.
3145 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003146 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3147 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003148 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003149 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003150 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003151 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3152 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3153 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003154 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3155 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003156 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3157 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3158 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003159 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003160 CXXRecordDecl *FieldClassDecl
3161 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003162 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003163 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3164 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003165 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003166 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003167 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3168 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003169 Diag(CurrentLocation, diag::note_first_required_here);
3170 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003171 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003172 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003173 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3174 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003175 Diag(CurrentLocation, diag::note_first_required_here);
3176 err = true;
3177 }
3178 }
3179 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003180 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003181}
3182
3183CXXMethodDecl *
3184Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3185 CXXRecordDecl *ClassDecl) {
3186 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3187 QualType RHSType(LHSType);
3188 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003189 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003190 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003191 RHSType = Context.getCVRQualifiedType(RHSType,
3192 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003193 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3194 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003195 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003196 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3197 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003198 SourceLocation()));
3199 Expr *Args[2] = { &*LHS, &*RHS };
3200 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003201 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003202 CandidateSet);
3203 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003204 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003205 ClassDecl->getLocation(), Best) == OR_Success)
3206 return cast<CXXMethodDecl>(Best->Function);
3207 assert(false &&
3208 "getAssignOperatorMethod - copy assignment operator method not found");
3209 return 0;
3210}
3211
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003212void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3213 CXXConstructorDecl *CopyConstructor,
3214 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003215 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003216 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3217 !CopyConstructor->isUsed()) &&
3218 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003220 CXXRecordDecl *ClassDecl
3221 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3222 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003223 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003224 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003225 // implicitly defined, all the implicitly-declared copy constructors
3226 // for its base class and its non-static data members shall have been
3227 // implicitly defined.
3228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3229 Base != ClassDecl->bases_end(); ++Base) {
3230 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003231 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003232 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003233 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003234 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003235 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003236 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3237 FieldEnd = ClassDecl->field_end();
3238 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003239 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3240 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3241 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003242 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003243 CXXRecordDecl *FieldClassDecl
3244 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003245 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003246 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003247 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003248 }
3249 }
3250 CopyConstructor->setUsed();
3251}
3252
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003253Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003254Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003255 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003256 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003257 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003258
Douglas Gregor39da0b82009-09-09 23:08:42 +00003259 // C++ [class.copy]p15:
3260 // Whenever a temporary class object is copied using a copy constructor, and
3261 // this object and the copy have the same cv-unqualified type, an
3262 // implementation is permitted to treat the original and the copy as two
3263 // different ways of referring to the same object and not perform a copy at
3264 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003265
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003266 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003267 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003268 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003269 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3270 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003271 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3272 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3273 E = ICE->getSubExpr();
3274
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003275 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3276 Elidable = true;
3277 }
Mike Stump1eb44332009-09-09 15:08:12 +00003278
3279 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003280 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003281}
3282
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003283/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3284/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003285Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003286Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3287 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003288 MultiExprArg ExprArgs) {
3289 unsigned NumExprs = ExprArgs.size();
3290 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Douglas Gregor7edfb692009-11-23 12:27:39 +00003292 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003293 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3294 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003295}
3296
Anders Carlssone7624a72009-08-27 05:08:22 +00003297Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003298Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3299 QualType Ty,
3300 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003301 MultiExprArg Args,
3302 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003303 unsigned NumExprs = Args.size();
3304 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Douglas Gregor7edfb692009-11-23 12:27:39 +00003306 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003307 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3308 TyBeginLoc, Exprs,
3309 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003310}
3311
3312
Mike Stump1eb44332009-09-09 15:08:12 +00003313bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003314 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003315 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003316 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003317 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003318 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003319 if (TempResult.isInvalid())
3320 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003322 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003323 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003324 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003325 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Anders Carlssonfe2de492009-08-25 05:18:00 +00003327 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003328}
3329
Mike Stump1eb44332009-09-09 15:08:12 +00003330void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003331 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003332 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003333 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003334 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003335 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003336 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003337}
3338
Mike Stump1eb44332009-09-09 15:08:12 +00003339/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003340/// ActOnDeclarator, when a C++ direct initializer is present.
3341/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003342void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3343 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003344 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003345 SourceLocation *CommaLocs,
3346 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003347 unsigned NumExprs = Exprs.size();
3348 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003349 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003350
3351 // If there is no declaration, there was an error parsing it. Just ignore
3352 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003353 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003354 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003356 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3357 if (!VDecl) {
3358 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3359 RealDecl->setInvalidDecl();
3360 return;
3361 }
3362
Douglas Gregor83ddad32009-08-26 21:14:46 +00003363 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003364 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003365 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3366 //
3367 // Clients that want to distinguish between the two forms, can check for
3368 // direct initializer using VarDecl::hasCXXDirectInitializer().
3369 // A major benefit is that clients that don't particularly care about which
3370 // exactly form was it (like the CodeGen) can handle both cases without
3371 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003372
Douglas Gregor83ddad32009-08-26 21:14:46 +00003373 // If either the declaration has a dependent type or if any of the expressions
3374 // is type-dependent, we represent the initialization via a ParenListExpr for
3375 // later use during template instantiation.
3376 if (VDecl->getType()->isDependentType() ||
3377 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3378 // Let clients know that initialization was done with a direct initializer.
3379 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Douglas Gregor83ddad32009-08-26 21:14:46 +00003381 // Store the initialization expressions as a ParenListExpr.
3382 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003383 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003384 new (Context) ParenListExpr(Context, LParenLoc,
3385 (Expr **)Exprs.release(),
3386 NumExprs, RParenLoc));
3387 return;
3388 }
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Douglas Gregor83ddad32009-08-26 21:14:46 +00003390
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003391 // C++ 8.5p11:
3392 // The form of initialization (using parentheses or '=') is generally
3393 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003394 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003395 QualType DeclInitType = VDecl->getType();
3396 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003397 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003398
Douglas Gregor615c5d42009-03-24 16:43:20 +00003399 // FIXME: This isn't the right place to complete the type.
3400 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3401 diag::err_typecheck_decl_incomplete_type)) {
3402 VDecl->setInvalidDecl();
3403 return;
3404 }
3405
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003406 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003407 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3408
Douglas Gregor18fe5682008-11-03 20:45:27 +00003409 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003410 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003411 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003412 VDecl->getLocation(),
3413 SourceRange(VDecl->getLocation(),
3414 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003415 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003416 IK_Direct,
3417 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003418 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003419 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003420 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003421 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003422 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003423 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003424 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003425 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003426 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003427 return;
3428 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003429
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003430 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003431 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3432 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003433 RealDecl->setInvalidDecl();
3434 return;
3435 }
3436
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003437 // Let clients know that initialization was done with a direct initializer.
3438 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003439
3440 assert(NumExprs == 1 && "Expected 1 expression");
3441 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003442 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3443 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003444}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003445
Douglas Gregor19aeac62009-11-14 03:27:21 +00003446/// \brief Add the applicable constructor candidates for an initialization
3447/// by constructor.
3448static void AddConstructorInitializationCandidates(Sema &SemaRef,
3449 QualType ClassType,
3450 Expr **Args,
3451 unsigned NumArgs,
3452 Sema::InitializationKind Kind,
3453 OverloadCandidateSet &CandidateSet) {
3454 // C++ [dcl.init]p14:
3455 // If the initialization is direct-initialization, or if it is
3456 // copy-initialization where the cv-unqualified version of the
3457 // source type is the same class as, or a derived class of, the
3458 // class of the destination, constructors are considered. The
3459 // applicable constructors are enumerated (13.3.1.3), and the
3460 // best one is chosen through overload resolution (13.3). The
3461 // constructor so selected is called to initialize the object,
3462 // with the initializer expression(s) as its argument(s). If no
3463 // constructor applies, or the overload resolution is ambiguous,
3464 // the initialization is ill-formed.
3465 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3466 assert(ClassRec && "Can only initialize a class type here");
3467
3468 // FIXME: When we decide not to synthesize the implicitly-declared
3469 // constructors, we'll need to make them appear here.
3470
3471 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3472 DeclarationName ConstructorName
3473 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3474 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3475 DeclContext::lookup_const_iterator Con, ConEnd;
3476 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3477 Con != ConEnd; ++Con) {
3478 // Find the constructor (which may be a template).
3479 CXXConstructorDecl *Constructor = 0;
3480 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3481 if (ConstructorTmpl)
3482 Constructor
3483 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3484 else
3485 Constructor = cast<CXXConstructorDecl>(*Con);
3486
3487 if ((Kind == Sema::IK_Direct) ||
3488 (Kind == Sema::IK_Copy &&
3489 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3490 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3491 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00003492 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3493 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003494 Args, NumArgs, CandidateSet);
3495 else
3496 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3497 }
3498 }
3499}
3500
3501/// \brief Attempt to perform initialization by constructor
3502/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3503/// copy-initialization.
3504///
3505/// This routine determines whether initialization by constructor is possible,
3506/// but it does not emit any diagnostics in the case where the initialization
3507/// is ill-formed.
3508///
3509/// \param ClassType the type of the object being initialized, which must have
3510/// class type.
3511///
3512/// \param Args the arguments provided to initialize the object
3513///
3514/// \param NumArgs the number of arguments provided to initialize the object
3515///
3516/// \param Kind the type of initialization being performed
3517///
3518/// \returns the constructor used to initialize the object, if successful.
3519/// Otherwise, emits a diagnostic and returns NULL.
3520CXXConstructorDecl *
3521Sema::TryInitializationByConstructor(QualType ClassType,
3522 Expr **Args, unsigned NumArgs,
3523 SourceLocation Loc,
3524 InitializationKind Kind) {
3525 // Build the overload candidate set
3526 OverloadCandidateSet CandidateSet;
3527 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3528 CandidateSet);
3529
3530 // Determine whether we found a constructor we can use.
3531 OverloadCandidateSet::iterator Best;
3532 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3533 case OR_Success:
3534 case OR_Deleted:
3535 // We found a constructor. Return it.
3536 return cast<CXXConstructorDecl>(Best->Function);
3537
3538 case OR_No_Viable_Function:
3539 case OR_Ambiguous:
3540 // Overload resolution failed. Return nothing.
3541 return 0;
3542 }
3543
3544 // Silence GCC warning
3545 return 0;
3546}
3547
Douglas Gregor39da0b82009-09-09 23:08:42 +00003548/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3549/// may occur as part of direct-initialization or copy-initialization.
3550///
3551/// \param ClassType the type of the object being initialized, which must have
3552/// class type.
3553///
3554/// \param ArgsPtr the arguments provided to initialize the object
3555///
3556/// \param Loc the source location where the initialization occurs
3557///
3558/// \param Range the source range that covers the entire initialization
3559///
3560/// \param InitEntity the name of the entity being initialized, if known
3561///
3562/// \param Kind the type of initialization being performed
3563///
3564/// \param ConvertedArgs a vector that will be filled in with the
3565/// appropriately-converted arguments to the constructor (if initialization
3566/// succeeded).
3567///
3568/// \returns the constructor used to initialize the object, if successful.
3569/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003570CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003571Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003572 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003573 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003574 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003575 InitializationKind Kind,
3576 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00003577
3578 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00003579 Expr **Args = (Expr **)ArgsPtr.get();
3580 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003581 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00003582 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3583 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003584
Douglas Gregor18fe5682008-11-03 20:45:27 +00003585 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003586 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003587 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003588 // We found a constructor. Break out so that we can convert the arguments
3589 // appropriately.
3590 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Douglas Gregor18fe5682008-11-03 20:45:27 +00003592 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003593 if (InitEntity)
3594 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003595 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003596 else
3597 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003598 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003599 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003600 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Douglas Gregor18fe5682008-11-03 20:45:27 +00003602 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003603 if (InitEntity)
3604 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3605 else
3606 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003607 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3608 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003609
3610 case OR_Deleted:
3611 if (InitEntity)
3612 Diag(Loc, diag::err_ovl_deleted_init)
3613 << Best->Function->isDeleted()
3614 << InitEntity << Range;
3615 else
3616 Diag(Loc, diag::err_ovl_deleted_init)
3617 << Best->Function->isDeleted()
3618 << InitEntity << Range;
3619 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3620 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003621 }
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor39da0b82009-09-09 23:08:42 +00003623 // Convert the arguments, fill in default arguments, etc.
3624 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3625 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3626 return 0;
3627
3628 return Constructor;
3629}
3630
3631/// \brief Given a constructor and the set of arguments provided for the
3632/// constructor, convert the arguments and add any required default arguments
3633/// to form a proper call to this constructor.
3634///
3635/// \returns true if an error occurred, false otherwise.
3636bool
3637Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3638 MultiExprArg ArgsPtr,
3639 SourceLocation Loc,
3640 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3641 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3642 unsigned NumArgs = ArgsPtr.size();
3643 Expr **Args = (Expr **)ArgsPtr.get();
3644
3645 const FunctionProtoType *Proto
3646 = Constructor->getType()->getAs<FunctionProtoType>();
3647 assert(Proto && "Constructor without a prototype?");
3648 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003649
3650 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003651 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00003652 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003653 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00003654 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003655
3656 VariadicCallType CallType =
3657 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3658 llvm::SmallVector<Expr *, 8> AllArgs;
3659 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3660 Proto, 0, Args, NumArgs, AllArgs,
3661 CallType);
3662 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3663 ConvertedArgs.push_back(AllArgs[i]);
3664 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003665}
3666
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003667/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3668/// determine whether they are reference-related,
3669/// reference-compatible, reference-compatible with added
3670/// qualification, or incompatible, for use in C++ initialization by
3671/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3672/// type, and the first type (T1) is the pointee type of the reference
3673/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003674Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00003675Sema::CompareReferenceRelationship(SourceLocation Loc,
3676 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003677 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003678 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003679 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00003680 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003681
Douglas Gregor393896f2009-11-05 13:06:35 +00003682 QualType T1 = Context.getCanonicalType(OrigT1);
3683 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003684 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3685 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003686
3687 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003688 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003689 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003690 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003691 if (UnqualT1 == UnqualT2)
3692 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00003693 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3694 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3695 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00003696 DerivedToBase = true;
3697 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003698 return Ref_Incompatible;
3699
3700 // At this point, we know that T1 and T2 are reference-related (at
3701 // least).
3702
3703 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003704 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003705 // reference-related to T2 and cv1 is the same cv-qualification
3706 // as, or greater cv-qualification than, cv2. For purposes of
3707 // overload resolution, cases for which cv1 is greater
3708 // cv-qualification than cv2 are identified as
3709 // reference-compatible with added qualification (see 13.3.3.2).
3710 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3711 return Ref_Compatible;
3712 else if (T1.isMoreQualifiedThan(T2))
3713 return Ref_Compatible_With_Added_Qualification;
3714 else
3715 return Ref_Related;
3716}
3717
3718/// CheckReferenceInit - Check the initialization of a reference
3719/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3720/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003721/// list), and DeclType is the type of the declaration. When ICS is
3722/// non-null, this routine will compute the implicit conversion
3723/// sequence according to C++ [over.ics.ref] and will not produce any
3724/// diagnostics; when ICS is null, it will emit diagnostics when any
3725/// errors are found. Either way, a return value of true indicates
3726/// that there was a failure, a return value of false indicates that
3727/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003728///
3729/// When @p SuppressUserConversions, user-defined conversions are
3730/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003731/// When @p AllowExplicit, we also permit explicit user-defined
3732/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003733/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003734/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3735/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003736bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003737Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003738 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003739 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003740 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003741 ImplicitConversionSequence *ICS,
3742 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003743 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3744
Ted Kremenek6217b802009-07-29 21:53:49 +00003745 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003746 QualType T2 = Init->getType();
3747
Douglas Gregor904eed32008-11-10 20:40:00 +00003748 // If the initializer is the address of an overloaded function, try
3749 // to resolve the overloaded function. If all goes well, T2 is the
3750 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003751 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003752 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003753 ICS != 0);
3754 if (Fn) {
3755 // Since we're performing this reference-initialization for
3756 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003757 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003758 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003759 return true;
3760
Anders Carlsson96ad5332009-10-21 17:16:23 +00003761 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003762 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003763
3764 T2 = Fn->getType();
3765 }
3766 }
3767
Douglas Gregor15da57e2008-10-29 02:00:59 +00003768 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003769 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003770 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003771 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3772 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003773 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00003774 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003775
3776 // Most paths end in a failed conversion.
3777 if (ICS)
3778 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003779
3780 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003781 // A reference to type "cv1 T1" is initialized by an expression
3782 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003783
3784 // -- If the initializer expression
3785
Sebastian Redla9845802009-03-29 15:27:50 +00003786 // Rvalue references cannot bind to lvalues (N2812).
3787 // There is absolutely no situation where they can. In particular, note that
3788 // this is ill-formed, even if B has a user-defined conversion to A&&:
3789 // B b;
3790 // A&& r = b;
3791 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3792 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003793 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003794 << Init->getSourceRange();
3795 return true;
3796 }
3797
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003798 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003799 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3800 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003801 //
3802 // Note that the bit-field check is skipped if we are just computing
3803 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003804 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003805 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003806 BindsDirectly = true;
3807
Douglas Gregor15da57e2008-10-29 02:00:59 +00003808 if (ICS) {
3809 // C++ [over.ics.ref]p1:
3810 // When a parameter of reference type binds directly (8.5.3)
3811 // to an argument expression, the implicit conversion sequence
3812 // is the identity conversion, unless the argument expression
3813 // has a type that is a derived class of the parameter type,
3814 // in which case the implicit conversion sequence is a
3815 // derived-to-base Conversion (13.3.3.1).
3816 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3817 ICS->Standard.First = ICK_Identity;
3818 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3819 ICS->Standard.Third = ICK_Identity;
3820 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3821 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003822 ICS->Standard.ReferenceBinding = true;
3823 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003824 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003825 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003826
3827 // Nothing more to do: the inaccessibility/ambiguity check for
3828 // derived-to-base conversions is suppressed when we're
3829 // computing the implicit conversion sequence (C++
3830 // [over.best.ics]p2).
3831 return false;
3832 } else {
3833 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003834 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3835 if (DerivedToBase)
3836 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003837 else if(CheckExceptionSpecCompatibility(Init, T1))
3838 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003839 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003840 }
3841 }
3842
3843 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003844 // implicitly converted to an lvalue of type "cv3 T3,"
3845 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003846 // 92) (this conversion is selected by enumerating the
3847 // applicable conversion functions (13.3.1.6) and choosing
3848 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003849 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003850 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003851 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003852 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003853
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003854 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00003855 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003856 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003857 for (UnresolvedSet::iterator I = Conversions->begin(),
3858 E = Conversions->end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00003859 FunctionTemplateDecl *ConvTemplate
John McCallba135432009-11-21 08:51:07 +00003860 = dyn_cast<FunctionTemplateDecl>(*I);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003861 CXXConversionDecl *Conv;
3862 if (ConvTemplate)
3863 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3864 else
John McCallba135432009-11-21 08:51:07 +00003865 Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003866
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003867 // If the conversion function doesn't return a reference type,
3868 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003869 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003870 (AllowExplicit || !Conv->isExplicit())) {
3871 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003872 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003873 CandidateSet);
3874 else
3875 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3876 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003877 }
3878
3879 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003880 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003881 case OR_Success:
3882 // This is a direct binding.
3883 BindsDirectly = true;
3884
3885 if (ICS) {
3886 // C++ [over.ics.ref]p1:
3887 //
3888 // [...] If the parameter binds directly to the result of
3889 // applying a conversion function to the argument
3890 // expression, the implicit conversion sequence is a
3891 // user-defined conversion sequence (13.3.3.1.2), with the
3892 // second standard conversion sequence either an identity
3893 // conversion or, if the conversion function returns an
3894 // entity of a type that is a derived class of the parameter
3895 // type, a derived-to-base Conversion.
3896 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3897 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3898 ICS->UserDefined.After = Best->FinalConversion;
3899 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003900 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003901 assert(ICS->UserDefined.After.ReferenceBinding &&
3902 ICS->UserDefined.After.DirectBinding &&
3903 "Expected a direct reference binding!");
3904 return false;
3905 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003906 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003907 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003908 CastExpr::CK_UserDefinedConversion,
3909 cast<CXXMethodDecl>(Best->Function),
3910 Owned(Init));
3911 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003912
3913 if (CheckExceptionSpecCompatibility(Init, T1))
3914 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003915 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3916 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003917 }
3918 break;
3919
3920 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003921 if (ICS) {
3922 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3923 Cand != CandidateSet.end(); ++Cand)
3924 if (Cand->Viable)
3925 ICS->ConversionFunctionSet.push_back(Cand->Function);
3926 break;
3927 }
3928 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3929 << Init->getSourceRange();
3930 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003931 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003932
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003933 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003934 case OR_Deleted:
3935 // There was no suitable conversion, or we found a deleted
3936 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003937 break;
3938 }
3939 }
Mike Stump1eb44332009-09-09 15:08:12 +00003940
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003941 if (BindsDirectly) {
3942 // C++ [dcl.init.ref]p4:
3943 // [...] In all cases where the reference-related or
3944 // reference-compatible relationship of two types is used to
3945 // establish the validity of a reference binding, and T1 is a
3946 // base class of T2, a program that necessitates such a binding
3947 // is ill-formed if T1 is an inaccessible (clause 11) or
3948 // ambiguous (10.2) base class of T2.
3949 //
3950 // Note that we only check this condition when we're allowed to
3951 // complain about errors, because we should not be checking for
3952 // ambiguity (or inaccessibility) unless the reference binding
3953 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003954 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003955 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003956 Init->getSourceRange(),
3957 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003958 else
3959 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003960 }
3961
3962 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003963 // type (i.e., cv1 shall be const), or the reference shall be an
3964 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003965 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003966 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003967 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003968 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3969 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003970 return true;
3971 }
3972
3973 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003974 // class type, and "cv1 T1" is reference-compatible with
3975 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003976 // following ways (the choice is implementation-defined):
3977 //
3978 // -- The reference is bound to the object represented by
3979 // the rvalue (see 3.10) or to a sub-object within that
3980 // object.
3981 //
Eli Friedman33a31382009-08-05 19:21:58 +00003982 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003983 // a constructor is called to copy the entire rvalue
3984 // object into the temporary. The reference is bound to
3985 // the temporary or to a sub-object within the
3986 // temporary.
3987 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003988 // The constructor that would be used to make the copy
3989 // shall be callable whether or not the copy is actually
3990 // done.
3991 //
Sebastian Redla9845802009-03-29 15:27:50 +00003992 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003993 // freedom, so we will always take the first option and never build
3994 // a temporary in this case. FIXME: We will, however, have to check
3995 // for the presence of a copy constructor in C++98/03 mode.
3996 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003997 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3998 if (ICS) {
3999 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4000 ICS->Standard.First = ICK_Identity;
4001 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4002 ICS->Standard.Third = ICK_Identity;
4003 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4004 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004005 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004006 ICS->Standard.DirectBinding = false;
4007 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004008 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004009 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004010 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4011 if (DerivedToBase)
4012 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004013 else if(CheckExceptionSpecCompatibility(Init, T1))
4014 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004015 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004016 }
4017 return false;
4018 }
4019
Eli Friedman33a31382009-08-05 19:21:58 +00004020 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004021 // initialized from the initializer expression using the
4022 // rules for a non-reference copy initialization (8.5). The
4023 // reference is then bound to the temporary. If T1 is
4024 // reference-related to T2, cv1 must be the same
4025 // cv-qualification as, or greater cv-qualification than,
4026 // cv2; otherwise, the program is ill-formed.
4027 if (RefRelationship == Ref_Related) {
4028 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4029 // we would be reference-compatible or reference-compatible with
4030 // added qualification. But that wasn't the case, so the reference
4031 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004032 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004033 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00004034 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4035 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004036 return true;
4037 }
4038
Douglas Gregor734d9862009-01-30 23:27:23 +00004039 // If at least one of the types is a class type, the types are not
4040 // related, and we aren't allowed any user conversions, the
4041 // reference binding fails. This case is important for breaking
4042 // recursion, since TryImplicitConversion below will attempt to
4043 // create a temporary through the use of a copy constructor.
4044 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4045 (T1->isRecordType() || T2->isRecordType())) {
4046 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004047 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00004048 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4049 return true;
4050 }
4051
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004052 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004053 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004054 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004055 //
Sebastian Redla9845802009-03-29 15:27:50 +00004056 // When a parameter of reference type is not bound directly to
4057 // an argument expression, the conversion sequence is the one
4058 // required to convert the argument expression to the
4059 // underlying type of the reference according to
4060 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4061 // to copy-initializing a temporary of the underlying type with
4062 // the argument expression. Any difference in top-level
4063 // cv-qualification is subsumed by the initialization itself
4064 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004065 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4066 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004067 /*ForceRValue=*/false,
4068 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004069
Sebastian Redla9845802009-03-29 15:27:50 +00004070 // Of course, that's still a reference binding.
4071 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4072 ICS->Standard.ReferenceBinding = true;
4073 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004074 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004075 ImplicitConversionSequence::UserDefinedConversion) {
4076 ICS->UserDefined.After.ReferenceBinding = true;
4077 ICS->UserDefined.After.RRefBinding = isRValRef;
4078 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004079 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4080 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004081 ImplicitConversionSequence Conversions;
4082 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4083 false, false,
4084 Conversions);
4085 if (badConversion) {
4086 if ((Conversions.ConversionKind ==
4087 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004088 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004089 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004090 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4091 for (int j = Conversions.ConversionFunctionSet.size()-1;
4092 j >= 0; j--) {
4093 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4094 Diag(Func->getLocation(), diag::err_ovl_candidate);
4095 }
4096 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004097 else {
4098 if (isRValRef)
4099 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4100 << Init->getSourceRange();
4101 else
4102 Diag(DeclLoc, diag::err_invalid_initialization)
4103 << DeclType << Init->getType() << Init->getSourceRange();
4104 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004105 }
4106 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004107 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004108}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004109
4110/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4111/// of this overloaded operator is well-formed. If so, returns false;
4112/// otherwise, emits appropriate diagnostics and returns true.
4113bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004114 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004115 "Expected an overloaded operator declaration");
4116
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004117 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4118
Mike Stump1eb44332009-09-09 15:08:12 +00004119 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004120 // The allocation and deallocation functions, operator new,
4121 // operator new[], operator delete and operator delete[], are
4122 // described completely in 3.7.3. The attributes and restrictions
4123 // found in the rest of this subclause do not apply to them unless
4124 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00004125 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004126 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004127 return false;
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004128
4129 if (Op == OO_New || Op == OO_Array_New) {
4130 bool ret = false;
4131 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4132 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4133 QualType T = Context.getCanonicalType((*Param)->getType());
4134 if (!T->isDependentType() && SizeTy != T) {
4135 Diag(FnDecl->getLocation(),
4136 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4137 << SizeTy;
4138 ret = true;
4139 }
4140 }
4141 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4142 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4143 return Diag(FnDecl->getLocation(),
4144 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregorcffecd02009-11-12 16:49:45 +00004145 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004146 return ret;
4147 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004148
4149 // C++ [over.oper]p6:
4150 // An operator function shall either be a non-static member
4151 // function or be a non-member function and have at least one
4152 // parameter whose type is a class, a reference to a class, an
4153 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004154 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4155 if (MethodDecl->isStatic())
4156 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004157 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004158 } else {
4159 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004160 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4161 ParamEnd = FnDecl->param_end();
4162 Param != ParamEnd; ++Param) {
4163 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004164 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4165 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004166 ClassOrEnumParam = true;
4167 break;
4168 }
4169 }
4170
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004171 if (!ClassOrEnumParam)
4172 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004173 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004174 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004175 }
4176
4177 // C++ [over.oper]p8:
4178 // An operator function cannot have default arguments (8.3.6),
4179 // except where explicitly stated below.
4180 //
Mike Stump1eb44332009-09-09 15:08:12 +00004181 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004182 // (C++ [over.call]p1).
4183 if (Op != OO_Call) {
4184 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4185 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004186 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004187 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004188 diag::err_operator_overload_default_arg)
4189 << FnDecl->getDeclName();
4190 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004191 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004192 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004193 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004194 }
4195 }
4196
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004197 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4198 { false, false, false }
4199#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4200 , { Unary, Binary, MemberOnly }
4201#include "clang/Basic/OperatorKinds.def"
4202 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004203
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004204 bool CanBeUnaryOperator = OperatorUses[Op][0];
4205 bool CanBeBinaryOperator = OperatorUses[Op][1];
4206 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004207
4208 // C++ [over.oper]p8:
4209 // [...] Operator functions cannot have more or fewer parameters
4210 // than the number required for the corresponding operator, as
4211 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004212 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004213 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004214 if (Op != OO_Call &&
4215 ((NumParams == 1 && !CanBeUnaryOperator) ||
4216 (NumParams == 2 && !CanBeBinaryOperator) ||
4217 (NumParams < 1) || (NumParams > 2))) {
4218 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004219 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004220 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004221 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004222 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004223 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004224 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004225 assert(CanBeBinaryOperator &&
4226 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004227 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004228 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004229
Chris Lattner416e46f2008-11-21 07:57:12 +00004230 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004231 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004232 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004233
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004234 // Overloaded operators other than operator() cannot be variadic.
4235 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004236 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004237 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004238 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004239 }
4240
4241 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004242 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4243 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004244 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004245 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004246 }
4247
4248 // C++ [over.inc]p1:
4249 // The user-defined function called operator++ implements the
4250 // prefix and postfix ++ operator. If this function is a member
4251 // function with no parameters, or a non-member function with one
4252 // parameter of class or enumeration type, it defines the prefix
4253 // increment operator ++ for objects of that type. If the function
4254 // is a member function with one parameter (which shall be of type
4255 // int) or a non-member function with two parameters (the second
4256 // of which shall be of type int), it defines the postfix
4257 // increment operator ++ for objects of that type.
4258 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4259 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4260 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004261 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004262 ParamIsInt = BT->getKind() == BuiltinType::Int;
4263
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004264 if (!ParamIsInt)
4265 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004266 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004267 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004268 }
4269
Sebastian Redl64b45f72009-01-05 20:52:13 +00004270 // Notify the class if it got an assignment operator.
4271 if (Op == OO_Equal) {
4272 // Would have returned earlier otherwise.
4273 assert(isa<CXXMethodDecl>(FnDecl) &&
4274 "Overloaded = not member, but not filtered.");
4275 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4276 Method->getParent()->addedAssignmentOperator(Context, Method);
4277 }
4278
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004279 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004280}
Chris Lattner5a003a42008-12-17 07:09:26 +00004281
Douglas Gregor074149e2009-01-05 19:45:36 +00004282/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4283/// linkage specification, including the language and (if present)
4284/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4285/// the location of the language string literal, which is provided
4286/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4287/// the '{' brace. Otherwise, this linkage specification does not
4288/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004289Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4290 SourceLocation ExternLoc,
4291 SourceLocation LangLoc,
4292 const char *Lang,
4293 unsigned StrSize,
4294 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004295 LinkageSpecDecl::LanguageIDs Language;
4296 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4297 Language = LinkageSpecDecl::lang_c;
4298 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4299 Language = LinkageSpecDecl::lang_cxx;
4300 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004301 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004302 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004303 }
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Chris Lattnercc98eac2008-12-17 07:13:27 +00004305 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Douglas Gregor074149e2009-01-05 19:45:36 +00004307 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004308 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004309 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004310 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004311 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004312 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004313}
4314
Douglas Gregor074149e2009-01-05 19:45:36 +00004315/// ActOnFinishLinkageSpecification - Completely the definition of
4316/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4317/// valid, it's the position of the closing '}' brace in a linkage
4318/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004319Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4320 DeclPtrTy LinkageSpec,
4321 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004322 if (LinkageSpec)
4323 PopDeclContext();
4324 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004325}
4326
Douglas Gregord308e622009-05-18 20:51:54 +00004327/// \brief Perform semantic analysis for the variable declaration that
4328/// occurs within a C++ catch clause, returning the newly-created
4329/// variable.
4330VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004331 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004332 IdentifierInfo *Name,
4333 SourceLocation Loc,
4334 SourceRange Range) {
4335 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004336
4337 // Arrays and functions decay.
4338 if (ExDeclType->isArrayType())
4339 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4340 else if (ExDeclType->isFunctionType())
4341 ExDeclType = Context.getPointerType(ExDeclType);
4342
4343 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4344 // The exception-declaration shall not denote a pointer or reference to an
4345 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004346 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004347 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004348 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004349 Invalid = true;
4350 }
Douglas Gregord308e622009-05-18 20:51:54 +00004351
Sebastian Redl4b07b292008-12-22 19:15:10 +00004352 QualType BaseType = ExDeclType;
4353 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004354 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004355 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004356 BaseType = Ptr->getPointeeType();
4357 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004358 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004359 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004360 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004361 BaseType = Ref->getPointeeType();
4362 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004363 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004364 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004365 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004366 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004367 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004368
Mike Stump1eb44332009-09-09 15:08:12 +00004369 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004370 RequireNonAbstractType(Loc, ExDeclType,
4371 diag::err_abstract_type_in_decl,
4372 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004373 Invalid = true;
4374
Douglas Gregord308e622009-05-18 20:51:54 +00004375 // FIXME: Need to test for ability to copy-construct and destroy the
4376 // exception variable.
4377
Sebastian Redl8351da02008-12-22 21:35:02 +00004378 // FIXME: Need to check for abstract classes.
4379
Mike Stump1eb44332009-09-09 15:08:12 +00004380 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004381 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004382
4383 if (Invalid)
4384 ExDecl->setInvalidDecl();
4385
4386 return ExDecl;
4387}
4388
4389/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4390/// handler.
4391Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004392 DeclaratorInfo *DInfo = 0;
4393 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004394
4395 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004396 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004397 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004398 // The scope should be freshly made just for us. There is just no way
4399 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004400 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004401 if (PrevDecl->isTemplateParameter()) {
4402 // Maybe we will complain about the shadowed template parameter.
4403 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004404 }
4405 }
4406
Chris Lattnereaaebc72009-04-25 08:06:05 +00004407 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004408 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4409 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004410 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004411 }
4412
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004413 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004414 D.getIdentifier(),
4415 D.getIdentifierLoc(),
4416 D.getDeclSpec().getSourceRange());
4417
Chris Lattnereaaebc72009-04-25 08:06:05 +00004418 if (Invalid)
4419 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004420
Sebastian Redl4b07b292008-12-22 19:15:10 +00004421 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004422 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004423 PushOnScopeChains(ExDecl, S);
4424 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004425 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004426
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004427 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004428 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004429}
Anders Carlssonfb311762009-03-14 00:25:26 +00004430
Mike Stump1eb44332009-09-09 15:08:12 +00004431Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004432 ExprArg assertexpr,
4433 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004434 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004435 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004436 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4437
Anders Carlssonc3082412009-03-14 00:33:21 +00004438 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4439 llvm::APSInt Value(32);
4440 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4441 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4442 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004443 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004444 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004445
Anders Carlssonc3082412009-03-14 00:33:21 +00004446 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004447 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004448 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004449 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004450 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004451 }
4452 }
Mike Stump1eb44332009-09-09 15:08:12 +00004453
Anders Carlsson77d81422009-03-15 17:35:16 +00004454 assertexpr.release();
4455 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004456 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004457 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004458
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004459 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004460 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004461}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004462
John McCalldd4a3b02009-09-16 22:47:08 +00004463/// Handle a friend type declaration. This works in tandem with
4464/// ActOnTag.
4465///
4466/// Notes on friend class templates:
4467///
4468/// We generally treat friend class declarations as if they were
4469/// declaring a class. So, for example, the elaborated type specifier
4470/// in a friend declaration is required to obey the restrictions of a
4471/// class-head (i.e. no typedefs in the scope chain), template
4472/// parameters are required to match up with simple template-ids, &c.
4473/// However, unlike when declaring a template specialization, it's
4474/// okay to refer to a template specialization without an empty
4475/// template parameter declaration, e.g.
4476/// friend class A<T>::B<unsigned>;
4477/// We permit this as a special case; if there are any template
4478/// parameters present at all, require proper matching, i.e.
4479/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004480Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004481 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004482 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004483
4484 assert(DS.isFriendSpecified());
4485 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4486
John McCalldd4a3b02009-09-16 22:47:08 +00004487 // Try to convert the decl specifier to a type. This works for
4488 // friend templates because ActOnTag never produces a ClassTemplateDecl
4489 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004490 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004491 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4492 if (TheDeclarator.isInvalidType())
4493 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004494
John McCalldd4a3b02009-09-16 22:47:08 +00004495 // This is definitely an error in C++98. It's probably meant to
4496 // be forbidden in C++0x, too, but the specification is just
4497 // poorly written.
4498 //
4499 // The problem is with declarations like the following:
4500 // template <T> friend A<T>::foo;
4501 // where deciding whether a class C is a friend or not now hinges
4502 // on whether there exists an instantiation of A that causes
4503 // 'foo' to equal C. There are restrictions on class-heads
4504 // (which we declare (by fiat) elaborated friend declarations to
4505 // be) that makes this tractable.
4506 //
4507 // FIXME: handle "template <> friend class A<T>;", which
4508 // is possibly well-formed? Who even knows?
4509 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4510 Diag(Loc, diag::err_tagless_friend_type_template)
4511 << DS.getSourceRange();
4512 return DeclPtrTy();
4513 }
4514
John McCall02cace72009-08-28 07:59:38 +00004515 // C++ [class.friend]p2:
4516 // An elaborated-type-specifier shall be used in a friend declaration
4517 // for a class.*
4518 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004519 // This is one of the rare places in Clang where it's legitimate to
4520 // ask about the "spelling" of the type.
4521 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4522 // If we evaluated the type to a record type, suggest putting
4523 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004524 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004525 RecordDecl *RD = RT->getDecl();
4526
4527 std::string InsertionText = std::string(" ") + RD->getKindName();
4528
John McCalle3af0232009-10-07 23:34:25 +00004529 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4530 << (unsigned) RD->getTagKind()
4531 << T
4532 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004533 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4534 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004535 return DeclPtrTy();
4536 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004537 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4538 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004539 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004540 }
4541 }
4542
John McCalle3af0232009-10-07 23:34:25 +00004543 // Enum types cannot be friends.
4544 if (T->getAs<EnumType>()) {
4545 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4546 << SourceRange(DS.getFriendSpecLoc());
4547 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004548 }
John McCall02cace72009-08-28 07:59:38 +00004549
John McCall02cace72009-08-28 07:59:38 +00004550 // C++98 [class.friend]p1: A friend of a class is a function
4551 // or class that is not a member of the class . . .
4552 // But that's a silly restriction which nobody implements for
4553 // inner classes, and C++0x removes it anyway, so we only report
4554 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004555 if (!getLangOptions().CPlusPlus0x)
4556 if (const RecordType *RT = T->getAs<RecordType>())
4557 if (RT->getDecl()->getDeclContext() == CurContext)
4558 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004559
John McCalldd4a3b02009-09-16 22:47:08 +00004560 Decl *D;
4561 if (TempParams.size())
4562 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4563 TempParams.size(),
4564 (TemplateParameterList**) TempParams.release(),
4565 T.getTypePtr(),
4566 DS.getFriendSpecLoc());
4567 else
4568 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4569 DS.getFriendSpecLoc());
4570 D->setAccess(AS_public);
4571 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004572
John McCalldd4a3b02009-09-16 22:47:08 +00004573 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004574}
4575
John McCallbbbcdd92009-09-11 21:02:39 +00004576Sema::DeclPtrTy
4577Sema::ActOnFriendFunctionDecl(Scope *S,
4578 Declarator &D,
4579 bool IsDefinition,
4580 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004581 const DeclSpec &DS = D.getDeclSpec();
4582
4583 assert(DS.isFriendSpecified());
4584 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4585
4586 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004587 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004588 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004589
4590 // C++ [class.friend]p1
4591 // A friend of a class is a function or class....
4592 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004593 // It *doesn't* see through dependent types, which is correct
4594 // according to [temp.arg.type]p3:
4595 // If a declaration acquires a function type through a
4596 // type dependent on a template-parameter and this causes
4597 // a declaration that does not use the syntactic form of a
4598 // function declarator to have a function type, the program
4599 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004600 if (!T->isFunctionType()) {
4601 Diag(Loc, diag::err_unexpected_friend);
4602
4603 // It might be worthwhile to try to recover by creating an
4604 // appropriate declaration.
4605 return DeclPtrTy();
4606 }
4607
4608 // C++ [namespace.memdef]p3
4609 // - If a friend declaration in a non-local class first declares a
4610 // class or function, the friend class or function is a member
4611 // of the innermost enclosing namespace.
4612 // - The name of the friend is not found by simple name lookup
4613 // until a matching declaration is provided in that namespace
4614 // scope (either before or after the class declaration granting
4615 // friendship).
4616 // - If a friend function is called, its name may be found by the
4617 // name lookup that considers functions from namespaces and
4618 // classes associated with the types of the function arguments.
4619 // - When looking for a prior declaration of a class or a function
4620 // declared as a friend, scopes outside the innermost enclosing
4621 // namespace scope are not considered.
4622
John McCall02cace72009-08-28 07:59:38 +00004623 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4624 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004625 assert(Name);
4626
John McCall67d1a672009-08-06 02:15:43 +00004627 // The context we found the declaration in, or in which we should
4628 // create the declaration.
4629 DeclContext *DC;
4630
4631 // FIXME: handle local classes
4632
4633 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00004634 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4635 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00004636 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004637 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004638 DC = computeDeclContext(ScopeQual);
4639
4640 // FIXME: handle dependent contexts
4641 if (!DC) return DeclPtrTy();
4642
John McCall68263142009-11-18 22:49:29 +00004643 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00004644
4645 // If searching in that context implicitly found a declaration in
4646 // a different context, treat it like it wasn't found at all.
4647 // TODO: better diagnostics for this case. Suggesting the right
4648 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00004649 // FIXME: getRepresentativeDecl() is not right here at all
4650 if (Previous.empty() ||
4651 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004652 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004653 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4654 return DeclPtrTy();
4655 }
4656
4657 // C++ [class.friend]p1: A friend of a class is a function or
4658 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004659 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004660 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4661
John McCall67d1a672009-08-06 02:15:43 +00004662 // Otherwise walk out to the nearest namespace scope looking for matches.
4663 } else {
4664 // TODO: handle local class contexts.
4665
4666 DC = CurContext;
4667 while (true) {
4668 // Skip class contexts. If someone can cite chapter and verse
4669 // for this behavior, that would be nice --- it's what GCC and
4670 // EDG do, and it seems like a reasonable intent, but the spec
4671 // really only says that checks for unqualified existing
4672 // declarations should stop at the nearest enclosing namespace,
4673 // not that they should only consider the nearest enclosing
4674 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004675 while (DC->isRecord())
4676 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004677
John McCall68263142009-11-18 22:49:29 +00004678 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00004679
4680 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00004681 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00004682 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004683
John McCall67d1a672009-08-06 02:15:43 +00004684 if (DC->isFileContext()) break;
4685 DC = DC->getParent();
4686 }
4687
4688 // C++ [class.friend]p1: A friend of a class is a function or
4689 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004690 // C++0x changes this for both friend types and functions.
4691 // Most C++ 98 compilers do seem to give an error here, so
4692 // we do, too.
John McCall68263142009-11-18 22:49:29 +00004693 if (!Previous.empty() && DC->Equals(CurContext)
4694 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004695 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4696 }
4697
Douglas Gregor182ddf02009-09-28 00:08:27 +00004698 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004699 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004700 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4701 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4702 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00004703 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004704 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4705 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004706 return DeclPtrTy();
4707 }
John McCall67d1a672009-08-06 02:15:43 +00004708 }
4709
Douglas Gregor182ddf02009-09-28 00:08:27 +00004710 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +00004711 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00004712 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004713 IsDefinition,
4714 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004715 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004716
Douglas Gregor182ddf02009-09-28 00:08:27 +00004717 assert(ND->getDeclContext() == DC);
4718 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004719
John McCallab88d972009-08-31 22:39:49 +00004720 // Add the function declaration to the appropriate lookup tables,
4721 // adjusting the redeclarations list as necessary. We don't
4722 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004723 //
John McCallab88d972009-08-31 22:39:49 +00004724 // Also update the scope-based lookup if the target context's
4725 // lookup context is in lexical scope.
4726 if (!CurContext->isDependentContext()) {
4727 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004728 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004729 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004730 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004731 }
John McCall02cace72009-08-28 07:59:38 +00004732
4733 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004734 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004735 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004736 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004737 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004738
Douglas Gregor182ddf02009-09-28 00:08:27 +00004739 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004740}
4741
Chris Lattnerb28317a2009-03-28 19:18:32 +00004742void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004743 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Chris Lattnerb28317a2009-03-28 19:18:32 +00004745 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004746 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4747 if (!Fn) {
4748 Diag(DelLoc, diag::err_deleted_non_function);
4749 return;
4750 }
4751 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4752 Diag(DelLoc, diag::err_deleted_decl_not_first);
4753 Diag(Prev->getLocation(), diag::note_previous_declaration);
4754 // If the declaration wasn't the first, we delete the function anyway for
4755 // recovery.
4756 }
4757 Fn->setDeleted();
4758}
Sebastian Redl13e88542009-04-27 21:33:24 +00004759
4760static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4761 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4762 ++CI) {
4763 Stmt *SubStmt = *CI;
4764 if (!SubStmt)
4765 continue;
4766 if (isa<ReturnStmt>(SubStmt))
4767 Self.Diag(SubStmt->getSourceRange().getBegin(),
4768 diag::err_return_in_constructor_handler);
4769 if (!isa<Expr>(SubStmt))
4770 SearchForReturnInStmt(Self, SubStmt);
4771 }
4772}
4773
4774void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4775 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4776 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4777 SearchForReturnInStmt(*this, Handler);
4778 }
4779}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004780
Mike Stump1eb44332009-09-09 15:08:12 +00004781bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004782 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004783 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4784 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004785
4786 QualType CNewTy = Context.getCanonicalType(NewTy);
4787 QualType COldTy = Context.getCanonicalType(OldTy);
4788
Mike Stump1eb44332009-09-09 15:08:12 +00004789 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00004790 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004791 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004792
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004793 // Check if the return types are covariant
4794 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004795
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004796 /// Both types must be pointers or references to classes.
4797 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4798 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4799 NewClassTy = NewPT->getPointeeType();
4800 OldClassTy = OldPT->getPointeeType();
4801 }
4802 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4803 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4804 NewClassTy = NewRT->getPointeeType();
4805 OldClassTy = OldRT->getPointeeType();
4806 }
4807 }
Mike Stump1eb44332009-09-09 15:08:12 +00004808
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004809 // The return types aren't either both pointers or references to a class type.
4810 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004811 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004812 diag::err_different_return_type_for_overriding_virtual_function)
4813 << New->getDeclName() << NewTy << OldTy;
4814 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004815
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004816 return true;
4817 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004818
Douglas Gregora4923eb2009-11-16 21:35:15 +00004819 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004820 // Check if the new class derives from the old class.
4821 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4822 Diag(New->getLocation(),
4823 diag::err_covariant_return_not_derived)
4824 << New->getDeclName() << NewTy << OldTy;
4825 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4826 return true;
4827 }
Mike Stump1eb44332009-09-09 15:08:12 +00004828
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004829 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004830 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004831 diag::err_covariant_return_inaccessible_base,
4832 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4833 // FIXME: Should this point to the return type?
4834 New->getLocation(), SourceRange(), New->getDeclName())) {
4835 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4836 return true;
4837 }
4838 }
Mike Stump1eb44332009-09-09 15:08:12 +00004839
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004840 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004841 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004842 Diag(New->getLocation(),
4843 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004844 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004845 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4846 return true;
4847 };
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004849
4850 // The new class type must have the same or less qualifiers as the old type.
4851 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4852 Diag(New->getLocation(),
4853 diag::err_covariant_return_type_class_type_more_qualified)
4854 << New->getDeclName() << NewTy << OldTy;
4855 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4856 return true;
4857 };
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004859 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004860}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004861
Sean Huntbbd37c62009-11-21 08:43:09 +00004862bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4863 const CXXMethodDecl *Old)
4864{
4865 if (Old->hasAttr<FinalAttr>()) {
4866 Diag(New->getLocation(), diag::err_final_function_overridden)
4867 << New->getDeclName();
4868 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4869 return true;
4870 }
4871
4872 return false;
4873}
4874
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004875/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4876/// initializer for the declaration 'Dcl'.
4877/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4878/// static data member of class X, names should be looked up in the scope of
4879/// class X.
4880void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004881 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004882
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004883 Decl *D = Dcl.getAs<Decl>();
4884 // If there is no declaration, there was an error parsing it.
4885 if (D == 0)
4886 return;
4887
4888 // Check whether it is a declaration with a nested name specifier like
4889 // int foo::bar;
4890 if (!D->isOutOfLine())
4891 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004892
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004893 // C++ [basic.lookup.unqual]p13
4894 //
4895 // A name used in the definition of a static data member of class X
4896 // (after the qualified-id of the static member) is looked up as if the name
4897 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004898
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004899 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004900 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004901}
4902
4903/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4904/// initializer for the declaration 'Dcl'.
4905void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004906 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004908 Decl *D = Dcl.getAs<Decl>();
4909 // If there is no declaration, there was an error parsing it.
4910 if (D == 0)
4911 return;
4912
4913 // Check whether it is a declaration with a nested name specifier like
4914 // int foo::bar;
4915 if (!D->isOutOfLine())
4916 return;
4917
4918 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004919 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004920}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00004921
4922/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
4923/// C++ if/switch/while/for statement.
4924/// e.g: "if (int x = f()) {...}"
4925Action::DeclResult
4926Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
4927 // C++ 6.4p2:
4928 // The declarator shall not specify a function or an array.
4929 // The type-specifier-seq shall not contain typedef and shall not declare a
4930 // new class or enumeration.
4931 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4932 "Parser allowed 'typedef' as storage class of condition decl.");
4933
4934 DeclaratorInfo *DInfo = 0;
4935 TagDecl *OwnedTag = 0;
4936 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
4937
4938 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
4939 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
4940 // would be created and CXXConditionDeclExpr wants a VarDecl.
4941 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
4942 << D.getSourceRange();
4943 return DeclResult();
4944 } else if (OwnedTag && OwnedTag->isDefinition()) {
4945 // The type-specifier-seq shall not declare a new class or enumeration.
4946 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
4947 }
4948
4949 DeclPtrTy Dcl = ActOnDeclarator(S, D);
4950 if (!Dcl)
4951 return DeclResult();
4952
4953 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
4954 VD->setDeclaredInCondition(true);
4955 return Dcl;
4956}