blob: ef59ff9d730d497349becb576a24fd89720d8d1e [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000019#include "clang/AST/DeclVisitor.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000020#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000021#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000022#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000025#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Chris Lattner58258242008-04-10 02:22:51 +000027#include "llvm/Support/Compiler.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000028#include <algorithm> // for std::equal
Douglas Gregor29a92472008-10-22 17:49:05 +000029#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000030#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000031
32using namespace clang;
33
Chris Lattner58258242008-04-10 02:22:51 +000034//===----------------------------------------------------------------------===//
35// CheckDefaultArgumentVisitor
36//===----------------------------------------------------------------------===//
37
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000044 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000045 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000046 Expr *DefaultArg;
47 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000048
Chris Lattnerb0d38442008-04-12 23:52:44 +000049 public:
Mike Stump11289f42009-09-09 15:08:12 +000050 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000052
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 bool VisitExpr(Expr *Node);
54 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000055 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 };
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000061 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000062 E = Node->child_end(); I != E; ++I)
63 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000065 }
66
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000071 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000081 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000082 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000083 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000084 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000085 // C++ [dcl.fct.default]p7
86 // Local variables shall not be used in default argument
87 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000088 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000089 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000090 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000091 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000092 }
Chris Lattner58258242008-04-10 02:22:51 +000093
Douglas Gregor8e12c382008-11-04 13:41:56 +000094 return false;
95 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000096
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_this)
104 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105 }
Chris Lattner58258242008-04-10 02:22:51 +0000106}
107
Anders Carlssonc80a1272009-08-25 02:29:20 +0000108bool
109Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000110 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000111 QualType ParamType = Param->getType();
112
Anders Carlsson114056f2009-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 Carlssonc80a1272009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000120
Anders Carlssonc80a1272009-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 Stump11289f42009-09-09 15:08:12 +0000127 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000128 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000129 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000130
131 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000132
Anders Carlssonc80a1272009-08-25 02:29:20 +0000133 // Okay: add the default argument to the parameter
134 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000135
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000137
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000138 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000139}
140
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000144void
Mike Stump11289f42009-09-09 15:08:12 +0000145Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000146 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000147 if (!param || !defarg.get())
148 return;
Mike Stump11289f42009-09-09 15:08:12 +0000149
Chris Lattner83f095c2009-03-28 19:18:32 +0000150 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000151 UnparsedDefaultArgLocs.erase(Param);
152
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000153 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000154 QualType ParamType = Param->getType();
155
156 // Default arguments are only permitted in C++
157 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000158 Diag(EqualLoc, diag::err_param_default_argument)
159 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000160 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000161 return;
162 }
163
Anders Carlssonf1c26952009-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 Stump11289f42009-09-09 15:08:12 +0000170
Anders Carlssonc80a1272009-08-25 02:29:20 +0000171 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000172}
173
Douglas Gregor58354032008-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 Stump11289f42009-09-09 15:08:12 +0000178void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000179 SourceLocation EqualLoc,
180 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000181 if (!param)
182 return;
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattner83f095c2009-03-28 19:18:32 +0000184 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000185 if (Param)
186 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000187
Anders Carlsson84613c42009-06-12 16:51:40 +0000188 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000189}
190
Douglas Gregor4d87df52008-12-16 21:30:33 +0000191/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
192/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000193void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000194 if (!param)
195 return;
Mike Stump11289f42009-09-09 15:08:12 +0000196
Anders Carlsson84613c42009-06-12 16:51:40 +0000197 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000198
Anders Carlsson84613c42009-06-12 16:51:40 +0000199 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000200
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000202}
203
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000217 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000218 DeclaratorChunk &chunk = D.getTypeObject(i);
219 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-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 Gregor58354032008-12-24 00:01:03 +0000223 if (Param->hasUnparsedDefaultArg()) {
224 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000233 }
234 }
235 }
236 }
237}
238
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000246 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000268 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlsson0b8ea552009-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 Carlsson1566eb52009-11-10 03:32:44 +0000273 if (NewParam->getIdentifier())
274 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000275
Mike Stump11289f42009-09-09 15:08:12 +0000276 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000277 diag::err_param_default_argument_redefinition)
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000278 << NewParam->getDefaultArgRange()
279 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
280 NewParam->getLocEnd()));
Douglas Gregorc732aba2009-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 Gregor75a45ba2009-02-16 17:45:42 +0000294 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000295 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000296 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000297 if (OldParam->hasUninstantiatedDefaultArg())
298 NewParam->setUninstantiatedDefaultArg(
299 OldParam->getUninstantiatedDefaultArg());
300 else
301 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000352 }
353 }
354
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000355 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000356 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +0000357 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000358 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000359
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000360 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000361}
362
363/// CheckCXXDefaultArguments - Verify that the default arguments for a
364/// function declaration are well-formed according to C++
365/// [dcl.fct.default].
366void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
367 unsigned NumParams = FD->getNumParams();
368 unsigned p;
369
370 // Find first parameter with a default argument
371 for (p = 0; p < NumParams; ++p) {
372 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000373 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000374 break;
375 }
376
377 // C++ [dcl.fct.default]p4:
378 // In a given function declaration, all parameters
379 // subsequent to a parameter with a default argument shall
380 // have default arguments supplied in this or previous
381 // declarations. A default argument shall not be redefined
382 // by a later declaration (not even to the same value).
383 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000384 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000385 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000386 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000387 if (Param->isInvalidDecl())
388 /* We already complained about this parameter. */;
389 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000390 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000391 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000392 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000393 else
Mike Stump11289f42009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000395 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 LastMissingDefaultArg = p;
398 }
399 }
400
401 if (LastMissingDefaultArg > 0) {
402 // Some default arguments were missing. Clear out all of the
403 // default arguments up to (and including) the last missing
404 // default argument, so that we leave the function parameters
405 // in a semantically valid state.
406 for (p = 0; p <= LastMissingDefaultArg; ++p) {
407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000408 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000409 if (!Param->hasUnparsedDefaultArg())
410 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000411 Param->setDefaultArg(0);
412 }
413 }
414 }
415}
Douglas Gregor556877c2008-04-13 21:30:24 +0000416
Douglas Gregor61956c42008-10-31 09:07:45 +0000417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000423 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000424 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000425 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
427 } else
428 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
429
430 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000431 return &II == CurDecl->getIdentifier();
432 else
433 return false;
434}
435
Mike Stump11289f42009-09-09 15:08:12 +0000436/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000437///
438/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
439/// and returns NULL otherwise.
440CXXBaseSpecifier *
441Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
442 SourceRange SpecifierRange,
443 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000444 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000445 SourceLocation BaseLoc) {
446 // C++ [class.union]p1:
447 // A union shall not have base classes.
448 if (Class->isUnion()) {
449 Diag(Class->getLocation(), diag::err_base_clause_on_union)
450 << SpecifierRange;
451 return 0;
452 }
453
454 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000455 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000456 Class->getTagKind() == RecordDecl::TK_class,
457 Access, BaseType);
458
459 // Base specifiers must be record types.
460 if (!BaseType->isRecordType()) {
461 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
462 return 0;
463 }
464
465 // C++ [class.union]p1:
466 // A union shall not be used as a base class.
467 if (BaseType->isUnionType()) {
468 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.derived]p2:
473 // The class-name in a base-specifier shall not be an incompletely
474 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000475 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000476 PDiag(diag::err_incomplete_base_class)
477 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000478 return 0;
479
Eli Friedmanc96d4962009-08-15 21:55:26 +0000480 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000481 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000482 assert(BaseDecl && "Record type has no declaration");
483 BaseDecl = BaseDecl->getDefinition(Context);
484 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000485 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
486 assert(CXXBaseDecl && "Base type is not a C++ type");
487 if (!CXXBaseDecl->isEmpty())
488 Class->setEmpty(false);
489 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 Class->setPolymorphic(true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000491 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
492 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
493 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
494 Diag(CXXBaseDecl->getLocation(), diag::note_previous_class_decl)
495 << BaseType.getAsString();
496 return 0;
497 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000498
499 // C++ [dcl.init.aggr]p1:
500 // An aggregate is [...] a class with [...] no base classes [...].
501 Class->setAggregate(false);
502 Class->setPOD(false);
503
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000504 if (Virtual) {
505 // C++ [class.ctor]p5:
506 // A constructor is trivial if its class has no virtual base classes.
507 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000508
509 // C++ [class.copy]p6:
510 // A copy constructor is trivial if its class has no virtual base classes.
511 Class->setHasTrivialCopyConstructor(false);
512
513 // C++ [class.copy]p11:
514 // A copy assignment operator is trivial if its class has no virtual
515 // base classes.
516 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000517
518 // C++0x [meta.unary.prop] is_empty:
519 // T is a class type, but not a union type, with ... no virtual base
520 // classes
521 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000522 } else {
523 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000524 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000525 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000526 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
527 Class->setHasTrivialConstructor(false);
528
529 // C++ [class.copy]p6:
530 // A copy constructor is trivial if all the direct base classes of its
531 // class have trivial copy constructors.
532 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
533 Class->setHasTrivialCopyConstructor(false);
534
535 // C++ [class.copy]p11:
536 // A copy assignment operator is trivial if all the direct base classes
537 // of its class have trivial copy assignment operators.
538 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
539 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000540 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000541
542 // C++ [class.ctor]p3:
543 // A destructor is trivial if all the direct base classes of its class
544 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000545 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
546 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000547
Douglas Gregor463421d2009-03-03 04:44:36 +0000548 // Create the base specifier.
549 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000550 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
551 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000552 Access, BaseType);
553}
554
Douglas Gregor556877c2008-04-13 21:30:24 +0000555/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
556/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000557/// example:
558/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000559/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000560Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000561Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000562 bool Virtual, AccessSpecifier Access,
563 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000564 if (!classdecl)
565 return true;
566
Douglas Gregorc40290e2009-03-09 23:48:35 +0000567 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000568 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000569 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
571 Virtual, Access,
572 BaseType, BaseLoc))
573 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000576}
Douglas Gregor556877c2008-04-13 21:30:24 +0000577
Douglas Gregor463421d2009-03-03 04:44:36 +0000578/// \brief Performs the actual work of attaching the given base class
579/// specifiers to a C++ class.
580bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
581 unsigned NumBases) {
582 if (NumBases == 0)
583 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000584
585 // Used to keep track of which base types we have already seen, so
586 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000587 // that the key is always the unqualified canonical type of the base
588 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000589 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
590
591 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000592 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000594 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000595 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000597 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000598
Douglas Gregor29a92472008-10-22 17:49:05 +0000599 if (KnownBaseTypes[NewBaseType]) {
600 // C++ [class.mi]p3:
601 // A class shall not be specified as a direct base class of a
602 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000604 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000605 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000607
608 // Delete the duplicate base class specifier; we're going to
609 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000610 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000611
612 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000613 } else {
614 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000615 KnownBaseTypes[NewBaseType] = Bases[idx];
616 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000617 }
618 }
619
620 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000621 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000622
623 // Delete the remaining (good) base class specifiers, since their
624 // data has been copied into the CXXRecordDecl.
625 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000626 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000627
628 return Invalid;
629}
630
631/// ActOnBaseSpecifiers - Attach the given base specifiers to the
632/// class, after checking whether there are any duplicate base
633/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000634void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000635 unsigned NumBases) {
636 if (!ClassDecl || !Bases || !NumBases)
637 return;
638
639 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000640 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000642}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000643
Douglas Gregor36d1b142009-10-06 17:59:45 +0000644/// \brief Determine whether the type \p Derived is a C++ class that is
645/// derived from the type \p Base.
646bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
647 if (!getLangOptions().CPlusPlus)
648 return false;
649
650 const RecordType *DerivedRT = Derived->getAs<RecordType>();
651 if (!DerivedRT)
652 return false;
653
654 const RecordType *BaseRT = Base->getAs<RecordType>();
655 if (!BaseRT)
656 return false;
657
658 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
659 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
660 return DerivedRD->isDerivedFrom(BaseRD);
661}
662
663/// \brief Determine whether the type \p Derived is a C++ class that is
664/// derived from the type \p Base.
665bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
666 if (!getLangOptions().CPlusPlus)
667 return false;
668
669 const RecordType *DerivedRT = Derived->getAs<RecordType>();
670 if (!DerivedRT)
671 return false;
672
673 const RecordType *BaseRT = Base->getAs<RecordType>();
674 if (!BaseRT)
675 return false;
676
677 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
678 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
679 return DerivedRD->isDerivedFrom(BaseRD, Paths);
680}
681
682/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
683/// conversion (where Derived and Base are class types) is
684/// well-formed, meaning that the conversion is unambiguous (and
685/// that all of the base classes are accessible). Returns true
686/// and emits a diagnostic if the code is ill-formed, returns false
687/// otherwise. Loc is the location where this routine should point to
688/// if there is an error, and Range is the source range to highlight
689/// if there is an error.
690bool
691Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
692 unsigned InaccessibleBaseID,
693 unsigned AmbigiousBaseConvID,
694 SourceLocation Loc, SourceRange Range,
695 DeclarationName Name) {
696 // First, determine whether the path from Derived to Base is
697 // ambiguous. This is slightly more expensive than checking whether
698 // the Derived to Base conversion exists, because here we need to
699 // explore multiple paths to determine if there is an ambiguity.
700 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
701 /*DetectVirtual=*/false);
702 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
703 assert(DerivationOkay &&
704 "Can only be used with a derived-to-base conversion");
705 (void)DerivationOkay;
706
707 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000708 if (InaccessibleBaseID == 0)
709 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000710 // Check that the base class can be accessed.
711 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
712 Name);
713 }
714
715 // We know that the derived-to-base conversion is ambiguous, and
716 // we're going to produce a diagnostic. Perform the derived-to-base
717 // search just one more time to compute all of the possible paths so
718 // that we can print them out. This is more expensive than any of
719 // the previous derived-to-base checks we've done, but at this point
720 // performance isn't as much of an issue.
721 Paths.clear();
722 Paths.setRecordingPaths(true);
723 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
724 assert(StillOkay && "Can only be used with a derived-to-base conversion");
725 (void)StillOkay;
726
727 // Build up a textual representation of the ambiguous paths, e.g.,
728 // D -> B -> A, that will be used to illustrate the ambiguous
729 // conversions in the diagnostic. We only print one of the paths
730 // to each base class subobject.
731 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
732
733 Diag(Loc, AmbigiousBaseConvID)
734 << Derived << Base << PathDisplayStr << Range << Name;
735 return true;
736}
737
738bool
739Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000740 SourceLocation Loc, SourceRange Range,
741 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000742 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000743 IgnoreAccess ? 0 :
744 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000745 diag::err_ambiguous_derived_to_base_conv,
746 Loc, Range, DeclarationName());
747}
748
749
750/// @brief Builds a string representing ambiguous paths from a
751/// specific derived class to different subobjects of the same base
752/// class.
753///
754/// This function builds a string that can be used in error messages
755/// to show the different paths that one can take through the
756/// inheritance hierarchy to go from the derived class to different
757/// subobjects of a base class. The result looks something like this:
758/// @code
759/// struct D -> struct B -> struct A
760/// struct D -> struct C -> struct A
761/// @endcode
762std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
763 std::string PathDisplayStr;
764 std::set<unsigned> DisplayedPaths;
765 for (CXXBasePaths::paths_iterator Path = Paths.begin();
766 Path != Paths.end(); ++Path) {
767 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
768 // We haven't displayed a path to this particular base
769 // class subobject yet.
770 PathDisplayStr += "\n ";
771 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
772 for (CXXBasePath::const_iterator Element = Path->begin();
773 Element != Path->end(); ++Element)
774 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
775 }
776 }
777
778 return PathDisplayStr;
779}
780
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000781//===----------------------------------------------------------------------===//
782// C++ class member Handling
783//===----------------------------------------------------------------------===//
784
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000785/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
786/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
787/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000788/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000789Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000790Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000791 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000792 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
793 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000794 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000795 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000796 Expr *BitWidth = static_cast<Expr*>(BW);
797 Expr *Init = static_cast<Expr*>(InitExpr);
798 SourceLocation Loc = D.getIdentifierLoc();
799
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000800 bool isFunc = D.isFunctionDeclarator();
801
John McCall07e91c02009-08-06 02:15:43 +0000802 assert(!DS.isFriendSpecified());
803
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000804 // C++ 9.2p6: A member shall not be declared to have automatic storage
805 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000806 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
807 // data members and cannot be applied to names declared const or static,
808 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000809 switch (DS.getStorageClassSpec()) {
810 case DeclSpec::SCS_unspecified:
811 case DeclSpec::SCS_typedef:
812 case DeclSpec::SCS_static:
813 // FALL THROUGH.
814 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000815 case DeclSpec::SCS_mutable:
816 if (isFunc) {
817 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000818 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000819 else
Chris Lattner3b054132008-11-19 05:08:23 +0000820 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000821
Sebastian Redl8071edb2008-11-17 23:24:37 +0000822 // FIXME: It would be nicer if the keyword was ignored only for this
823 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000824 D.getMutableDeclSpec().ClearStorageClassSpecs();
825 } else {
826 QualType T = GetTypeForDeclarator(D, S);
827 diag::kind err = static_cast<diag::kind>(0);
828 if (T->isReferenceType())
829 err = diag::err_mutable_reference;
830 else if (T.isConstQualified())
831 err = diag::err_mutable_const;
832 if (err != 0) {
833 if (DS.getStorageClassSpecLoc().isValid())
834 Diag(DS.getStorageClassSpecLoc(), err);
835 else
836 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000837 // FIXME: It would be nicer if the keyword was ignored only for this
838 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000839 D.getMutableDeclSpec().ClearStorageClassSpecs();
840 }
841 }
842 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000843 default:
844 if (DS.getStorageClassSpecLoc().isValid())
845 Diag(DS.getStorageClassSpecLoc(),
846 diag::err_storageclass_invalid_for_member);
847 else
848 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
849 D.getMutableDeclSpec().ClearStorageClassSpecs();
850 }
851
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000852 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000853 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000854 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000855 // Check also for this case:
856 //
857 // typedef int f();
858 // f a;
859 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000860 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000861 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000862 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000863
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000864 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
865 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000866 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000867
868 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000869 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000870 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000871 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
872 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000873 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000874 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000875 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000876 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000877 if (!Member) {
878 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000879 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000880 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000881
882 // Non-instance-fields can't have a bitfield.
883 if (BitWidth) {
884 if (Member->isInvalidDecl()) {
885 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000886 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000887 // C++ 9.6p3: A bit-field shall not be a static member.
888 // "static member 'A' cannot be a bit-field"
889 Diag(Loc, diag::err_static_not_bitfield)
890 << Name << BitWidth->getSourceRange();
891 } else if (isa<TypedefDecl>(Member)) {
892 // "typedef member 'x' cannot be a bit-field"
893 Diag(Loc, diag::err_typedef_not_bitfield)
894 << Name << BitWidth->getSourceRange();
895 } else {
896 // A function typedef ("typedef int f(); f a;").
897 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
898 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000899 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000900 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000901 }
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattnerd26760a2009-03-05 23:01:03 +0000903 DeleteExpr(BitWidth);
904 BitWidth = 0;
905 Member->setInvalidDecl();
906 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000907
908 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000909
Douglas Gregor3447e762009-08-20 22:52:58 +0000910 // If we have declared a member function template, set the access of the
911 // templated declaration as well.
912 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
913 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000914 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915
Douglas Gregor92751d42008-11-17 22:58:34 +0000916 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000917
Douglas Gregor0c880302009-03-11 23:00:04 +0000918 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000919 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000920 if (Deleted) // FIXME: Source location is not very good.
921 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000922
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000923 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000924 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000925 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000926 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000927 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000928}
929
Douglas Gregore8381c02008-11-05 04:29:56 +0000930/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000931Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000932Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000933 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000934 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000935 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000936 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000937 SourceLocation IdLoc,
938 SourceLocation LParenLoc,
939 ExprTy **Args, unsigned NumArgs,
940 SourceLocation *CommaLocs,
941 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000942 if (!ConstructorD)
943 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000944
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000945 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000946
947 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000948 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000949 if (!Constructor) {
950 // The user wrote a constructor initializer on a function that is
951 // not a C++ constructor. Ignore the error for now, because we may
952 // have more member initializers coming; we'll diagnose it just
953 // once in ActOnMemInitializers.
954 return true;
955 }
956
957 CXXRecordDecl *ClassDecl = Constructor->getParent();
958
959 // C++ [class.base.init]p2:
960 // Names in a mem-initializer-id are looked up in the scope of the
961 // constructor’s class and, if not found in that scope, are looked
962 // up in the scope containing the constructor’s
963 // definition. [Note: if the constructor’s class contains a member
964 // with the same name as a direct or virtual base class of the
965 // class, a mem-initializer-id naming the member or base class and
966 // composed of a single identifier refers to the class member. A
967 // mem-initializer-id for the hidden base class may be specified
968 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000969 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000970 // Look for a member, first.
971 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000972 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000973 = ClassDecl->lookup(MemberOrBase);
974 if (Result.first != Result.second)
975 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000976
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000977 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000978
Eli Friedman8e1433b2009-07-29 19:44:27 +0000979 if (Member)
980 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
981 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000982 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000983 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000984 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000985 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000986 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000987 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
988 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000989
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000990 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000991
Eli Friedman8e1433b2009-07-29 19:44:27 +0000992 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
993 RParenLoc, ClassDecl);
994}
995
John McCalle22a04a2009-11-04 23:02:40 +0000996/// Checks an initializer expression for use of uninitialized fields, such as
997/// containing the field that is being initialized. Returns true if there is an
998/// uninitialized field was used an updates the SourceLocation parameter; false
999/// otherwise.
1000static bool InitExprContainsUninitializedFields(const Stmt* S,
1001 const FieldDecl* LhsField,
1002 SourceLocation* L) {
1003 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1004 if (ME) {
1005 const NamedDecl* RhsField = ME->getMemberDecl();
1006 if (RhsField == LhsField) {
1007 // Initializing a field with itself. Throw a warning.
1008 // But wait; there are exceptions!
1009 // Exception #1: The field may not belong to this record.
1010 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1011 const Expr* base = ME->getBase();
1012 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1013 // Even though the field matches, it does not belong to this record.
1014 return false;
1015 }
1016 // None of the exceptions triggered; return true to indicate an
1017 // uninitialized field was used.
1018 *L = ME->getMemberLoc();
1019 return true;
1020 }
1021 }
1022 bool found = false;
1023 for (Stmt::const_child_iterator it = S->child_begin();
1024 it != S->child_end() && found == false;
1025 ++it) {
1026 if (isa<CallExpr>(S)) {
1027 // Do not descend into function calls or constructors, as the use
1028 // of an uninitialized field may be valid. One would have to inspect
1029 // the contents of the function/ctor to determine if it is safe or not.
1030 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1031 // may be safe, depending on what the function/ctor does.
1032 continue;
1033 }
1034 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1035 }
1036 return found;
1037}
1038
Eli Friedman8e1433b2009-07-29 19:44:27 +00001039Sema::MemInitResult
1040Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1041 unsigned NumArgs, SourceLocation IdLoc,
1042 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001043 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1044 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1045 ExprTemporaries.clear();
1046
John McCalle22a04a2009-11-04 23:02:40 +00001047 // Diagnose value-uses of fields to initialize themselves, e.g.
1048 // foo(foo)
1049 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001050 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001051 for (unsigned i = 0; i < NumArgs; ++i) {
1052 SourceLocation L;
1053 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1054 // FIXME: Return true in the case when other fields are used before being
1055 // uninitialized. For example, let this field be the i'th field. When
1056 // initializing the i'th field, throw a warning if any of the >= i'th
1057 // fields are used, as they are not yet initialized.
1058 // Right now we are only handling the case where the i'th field uses
1059 // itself in its initializer.
1060 Diag(L, diag::warn_field_is_uninit);
1061 }
1062 }
1063
Eli Friedman8e1433b2009-07-29 19:44:27 +00001064 bool HasDependentArg = false;
1065 for (unsigned i = 0; i < NumArgs; i++)
1066 HasDependentArg |= Args[i]->isTypeDependent();
1067
1068 CXXConstructorDecl *C = 0;
1069 QualType FieldType = Member->getType();
1070 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1071 FieldType = Array->getElementType();
1072 if (FieldType->isDependentType()) {
1073 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001074 } else if (FieldType->isRecordType()) {
1075 // Member is a record (struct/union/class), so pass the initializer
1076 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001077 if (!HasDependentArg) {
1078 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1079
1080 C = PerformInitializationByConstructor(FieldType,
1081 MultiExprArg(*this,
1082 (void**)Args,
1083 NumArgs),
1084 IdLoc,
1085 SourceRange(IdLoc, RParenLoc),
1086 Member->getDeclName(), IK_Direct,
1087 ConstructorArgs);
1088
1089 if (C) {
1090 // Take over the constructor arguments as our own.
1091 NumArgs = ConstructorArgs.size();
1092 Args = (Expr **)ConstructorArgs.take();
1093 }
1094 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001095 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001096 // The member type is not a record type (or an array of record
1097 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001098 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001099 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1100 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001101 Expr *NewExp;
1102 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001103 if (FieldType->isReferenceType()) {
1104 Diag(IdLoc, diag::err_null_intialized_reference_member)
1105 << Member->getDeclName();
1106 return Diag(Member->getLocation(), diag::note_declared_at);
1107 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001108 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1109 NumArgs = 1;
1110 }
1111 else
1112 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001113 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1114 return true;
1115 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001116 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001117
1118 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1119 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1120 ExprTemporaries.clear();
1121
Eli Friedman8e1433b2009-07-29 19:44:27 +00001122 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +00001123 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001124 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001125}
1126
1127Sema::MemInitResult
1128Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1129 unsigned NumArgs, SourceLocation IdLoc,
1130 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1131 bool HasDependentArg = false;
1132 for (unsigned i = 0; i < NumArgs; i++)
1133 HasDependentArg |= Args[i]->isTypeDependent();
1134
1135 if (!BaseType->isDependentType()) {
1136 if (!BaseType->isRecordType())
1137 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1138 << BaseType << SourceRange(IdLoc, RParenLoc);
1139
1140 // C++ [class.base.init]p2:
1141 // [...] Unless the mem-initializer-id names a nonstatic data
1142 // member of the constructor’s class or a direct or virtual base
1143 // of that class, the mem-initializer is ill-formed. A
1144 // mem-initializer-list can initialize a base class using any
1145 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001146
Eli Friedman8e1433b2009-07-29 19:44:27 +00001147 // First, check for a direct base class.
1148 const CXXBaseSpecifier *DirectBaseSpec = 0;
1149 for (CXXRecordDecl::base_class_const_iterator Base =
1150 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001151 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001152 // We found a direct base of this type. That's what we're
1153 // initializing.
1154 DirectBaseSpec = &*Base;
1155 break;
1156 }
1157 }
Mike Stump11289f42009-09-09 15:08:12 +00001158
Eli Friedman8e1433b2009-07-29 19:44:27 +00001159 // Check for a virtual base class.
1160 // FIXME: We might be able to short-circuit this if we know in advance that
1161 // there are no virtual bases.
1162 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1163 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1164 // We haven't found a base yet; search the class hierarchy for a
1165 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001166 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1167 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001168 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001169 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001170 Path != Paths.end(); ++Path) {
1171 if (Path->back().Base->isVirtual()) {
1172 VirtualBaseSpec = Path->back().Base;
1173 break;
1174 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001175 }
1176 }
1177 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001178
1179 // C++ [base.class.init]p2:
1180 // If a mem-initializer-id is ambiguous because it designates both
1181 // a direct non-virtual base class and an inherited virtual base
1182 // class, the mem-initializer is ill-formed.
1183 if (DirectBaseSpec && VirtualBaseSpec)
1184 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1185 << BaseType << SourceRange(IdLoc, RParenLoc);
1186 // C++ [base.class.init]p2:
1187 // Unless the mem-initializer-id names a nonstatic data membeer of the
1188 // constructor's class ot a direst or virtual base of that class, the
1189 // mem-initializer is ill-formed.
1190 if (!DirectBaseSpec && !VirtualBaseSpec)
1191 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1192 << BaseType << ClassDecl->getNameAsCString()
1193 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001194 }
1195
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001196 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001197 if (!BaseType->isDependentType() && !HasDependentArg) {
1198 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001199 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001200 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1201
1202 C = PerformInitializationByConstructor(BaseType,
1203 MultiExprArg(*this,
1204 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +00001205 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001206 Name, IK_Direct,
1207 ConstructorArgs);
1208 if (C) {
1209 // Take over the constructor arguments as our own.
1210 NumArgs = ConstructorArgs.size();
1211 Args = (Expr **)ConstructorArgs.take();
1212 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001213 }
1214
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001215 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1216 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1217 ExprTemporaries.clear();
1218
Mike Stump11289f42009-09-09 15:08:12 +00001219 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001220 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001221}
1222
Eli Friedman9cf6b592009-11-09 19:20:36 +00001223bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001224Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001225 CXXBaseOrMemberInitializer **Initializers,
1226 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001227 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001228 // We need to build the initializer AST according to order of construction
1229 // and not what user specified in the Initializers list.
1230 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1231 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1232 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1233 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001234 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001235
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001236 for (unsigned i = 0; i < NumInitializers; i++) {
1237 CXXBaseOrMemberInitializer *Member = Initializers[i];
1238 if (Member->isBaseInitializer()) {
1239 if (Member->getBaseClass()->isDependentType())
1240 HasDependentBaseInit = true;
1241 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1242 } else {
1243 AllBaseFields[Member->getMember()] = Member;
1244 }
1245 }
Mike Stump11289f42009-09-09 15:08:12 +00001246
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001247 if (HasDependentBaseInit) {
1248 // FIXME. This does not preserve the ordering of the initializers.
1249 // Try (with -Wreorder)
1250 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001251 // template<class X> struct B : A<X> {
1252 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001253 // int x1;
1254 // };
1255 // B<int> x;
1256 // On seeing one dependent type, we should essentially exit this routine
1257 // while preserving user-declared initializer list. When this routine is
1258 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001259 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001260
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001261 // If we have a dependent base initialization, we can't determine the
1262 // association between initializers and bases; just dump the known
1263 // initializers into the list, and don't try to deal with other bases.
1264 for (unsigned i = 0; i < NumInitializers; i++) {
1265 CXXBaseOrMemberInitializer *Member = Initializers[i];
1266 if (Member->isBaseInitializer())
1267 AllToInit.push_back(Member);
1268 }
1269 } else {
1270 // Push virtual bases before others.
1271 for (CXXRecordDecl::base_class_iterator VBase =
1272 ClassDecl->vbases_begin(),
1273 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1274 if (VBase->getType()->isDependentType())
1275 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001276 if (CXXBaseOrMemberInitializer *Value
1277 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001278 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001279 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001280 else {
Mike Stump11289f42009-09-09 15:08:12 +00001281 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001282 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001283 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001284 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001285 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001286 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1287 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1288 << 0 << VBase->getType();
1289 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1290 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001291 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001292 continue;
1293 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001294
Anders Carlsson561f7932009-10-29 15:46:07 +00001295 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1296 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1297 Constructor->getLocation(), CtorArgs))
1298 continue;
1299
1300 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1301
Anders Carlssonbdd12402009-11-13 20:11:49 +00001302 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1303 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1304 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001305 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001306 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1307 CtorArgs.takeAs<Expr>(),
1308 CtorArgs.size(), Ctor,
1309 SourceLocation(),
1310 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001311 AllToInit.push_back(Member);
1312 }
1313 }
Mike Stump11289f42009-09-09 15:08:12 +00001314
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001315 for (CXXRecordDecl::base_class_iterator Base =
1316 ClassDecl->bases_begin(),
1317 E = ClassDecl->bases_end(); Base != E; ++Base) {
1318 // Virtuals are in the virtual base list and already constructed.
1319 if (Base->isVirtual())
1320 continue;
1321 // Skip dependent types.
1322 if (Base->getType()->isDependentType())
1323 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001324 if (CXXBaseOrMemberInitializer *Value
1325 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001326 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001327 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001328 else {
Mike Stump11289f42009-09-09 15:08:12 +00001329 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001330 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001331 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001332 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001333 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001334 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1335 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1336 << 0 << Base->getType();
1337 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1338 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001339 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001340 continue;
1341 }
1342
1343 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1344 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1345 Constructor->getLocation(), CtorArgs))
1346 continue;
1347
1348 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001349
Anders Carlssonbdd12402009-11-13 20:11:49 +00001350 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1351 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1352 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001353 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001354 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1355 CtorArgs.takeAs<Expr>(),
1356 CtorArgs.size(), Ctor,
1357 SourceLocation(),
1358 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001359 AllToInit.push_back(Member);
1360 }
1361 }
1362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001364 // non-static data members.
1365 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1366 E = ClassDecl->field_end(); Field != E; ++Field) {
1367 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001368 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001369 Field->getType()->getAs<RecordType>()) {
1370 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001371 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001372 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001373 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1374 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1375 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1376 // set to the anonymous union data member used in the initializer
1377 // list.
1378 Value->setMember(*Field);
1379 Value->setAnonUnionMember(*FA);
1380 AllToInit.push_back(Value);
1381 break;
1382 }
1383 }
1384 }
1385 continue;
1386 }
1387 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1388 AllToInit.push_back(Value);
1389 continue;
1390 }
Mike Stump11289f42009-09-09 15:08:12 +00001391
Eli Friedmand7686ef2009-11-09 01:05:47 +00001392 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001393 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001394
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001395 QualType FT = Context.getBaseElementType((*Field)->getType());
1396 if (const RecordType* RT = FT->getAs<RecordType>()) {
1397 CXXConstructorDecl *Ctor =
1398 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001399 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001400 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1401 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1402 << 1 << (*Field)->getDeclName();
1403 Diag(Field->getLocation(), diag::note_field_decl);
1404 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1405 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001406 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001407 continue;
1408 }
Eli Friedman22683fe2009-11-16 23:07:59 +00001409
1410 if (FT.isConstQualified() && Ctor->isTrivial()) {
1411 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1412 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1413 << 1 << (*Field)->getDeclName();
1414 Diag((*Field)->getLocation(), diag::note_declared_at);
1415 HadError = true;
1416 }
1417
1418 // Don't create initializers for trivial constructors, since they don't
1419 // actually need to be run.
1420 if (Ctor->isTrivial())
1421 continue;
1422
Anders Carlsson561f7932009-10-29 15:46:07 +00001423 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1424 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1425 Constructor->getLocation(), CtorArgs))
1426 continue;
1427
Anders Carlssonbdd12402009-11-13 20:11:49 +00001428 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1429 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1430 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001431 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001432 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1433 CtorArgs.size(), Ctor,
1434 SourceLocation(),
1435 SourceLocation());
1436
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001437 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001438 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001439 }
1440 else if (FT->isReferenceType()) {
1441 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001442 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1443 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001444 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001445 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001446 }
1447 else if (FT.isConstQualified()) {
1448 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001449 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1450 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001451 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001452 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001453 }
1454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001456 NumInitializers = AllToInit.size();
1457 if (NumInitializers > 0) {
1458 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1459 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1460 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001461
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001462 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1463 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1464 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1465 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001466
1467 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001468}
1469
Eli Friedman952c15d2009-07-21 19:28:10 +00001470static void *GetKeyForTopLevelField(FieldDecl *Field) {
1471 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001472 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001473 if (RT->getDecl()->isAnonymousStructOrUnion())
1474 return static_cast<void *>(RT->getDecl());
1475 }
1476 return static_cast<void *>(Field);
1477}
1478
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001479static void *GetKeyForBase(QualType BaseType) {
1480 if (const RecordType *RT = BaseType->getAs<RecordType>())
1481 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001482
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001483 assert(0 && "Unexpected base type!");
1484 return 0;
1485}
1486
Mike Stump11289f42009-09-09 15:08:12 +00001487static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001488 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001489 // For fields injected into the class via declaration of an anonymous union,
1490 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001491 if (Member->isMemberInitializer()) {
1492 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001493
Eli Friedmand7686ef2009-11-09 01:05:47 +00001494 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001495 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001496 // in AnonUnionMember field.
1497 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1498 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001499 if (Field->getDeclContext()->isRecord()) {
1500 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1501 if (RD->isAnonymousStructOrUnion())
1502 return static_cast<void *>(RD);
1503 }
1504 return static_cast<void *>(Field);
1505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001507 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001508}
1509
John McCallc90f6d72009-11-04 23:13:52 +00001510/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001511void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001512 SourceLocation ColonLoc,
1513 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001514 if (!ConstructorDecl)
1515 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001516
1517 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001518
1519 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001520 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001521
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001522 if (!Constructor) {
1523 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1524 return;
1525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001527 if (!Constructor->isDependentContext()) {
1528 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1529 bool err = false;
1530 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001531 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001532 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1533 void *KeyToMember = GetKeyForMember(Member);
1534 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1535 if (!PrevMember) {
1536 PrevMember = Member;
1537 continue;
1538 }
1539 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001540 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001541 diag::error_multiple_mem_initialization)
1542 << Field->getNameAsString();
1543 else {
1544 Type *BaseClass = Member->getBaseClass();
1545 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001546 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001547 diag::error_multiple_base_initialization)
John McCalla1925362009-09-29 23:03:30 +00001548 << QualType(BaseClass, 0);
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001549 }
1550 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1551 << 0;
1552 err = true;
1553 }
Mike Stump11289f42009-09-09 15:08:12 +00001554
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001555 if (err)
1556 return;
1557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
Eli Friedmand7686ef2009-11-09 01:05:47 +00001559 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001560 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001561 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001563 if (Constructor->isDependentContext())
1564 return;
Mike Stump11289f42009-09-09 15:08:12 +00001565
1566 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001567 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001568 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001569 Diagnostic::Ignored)
1570 return;
Mike Stump11289f42009-09-09 15:08:12 +00001571
Anders Carlssone0eebb32009-08-27 05:45:01 +00001572 // Also issue warning if order of ctor-initializer list does not match order
1573 // of 1) base class declarations and 2) order of non-static data members.
1574 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001575
Anders Carlssone0eebb32009-08-27 05:45:01 +00001576 CXXRecordDecl *ClassDecl
1577 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1578 // Push virtual bases before others.
1579 for (CXXRecordDecl::base_class_iterator VBase =
1580 ClassDecl->vbases_begin(),
1581 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001582 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001583
Anders Carlssone0eebb32009-08-27 05:45:01 +00001584 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1585 E = ClassDecl->bases_end(); Base != E; ++Base) {
1586 // Virtuals are alread in the virtual base list and are constructed
1587 // first.
1588 if (Base->isVirtual())
1589 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001590 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001591 }
Mike Stump11289f42009-09-09 15:08:12 +00001592
Anders Carlssone0eebb32009-08-27 05:45:01 +00001593 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1594 E = ClassDecl->field_end(); Field != E; ++Field)
1595 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001596
Anders Carlssone0eebb32009-08-27 05:45:01 +00001597 int Last = AllBaseOrMembers.size();
1598 int curIndex = 0;
1599 CXXBaseOrMemberInitializer *PrevMember = 0;
1600 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001601 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001602 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1603 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001604
Anders Carlssone0eebb32009-08-27 05:45:01 +00001605 for (; curIndex < Last; curIndex++)
1606 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1607 break;
1608 if (curIndex == Last) {
1609 assert(PrevMember && "Member not in member list?!");
1610 // Initializer as specified in ctor-initializer list is out of order.
1611 // Issue a warning diagnostic.
1612 if (PrevMember->isBaseInitializer()) {
1613 // Diagnostics is for an initialized base class.
1614 Type *BaseClass = PrevMember->getBaseClass();
1615 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001616 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001617 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001618 } else {
1619 FieldDecl *Field = PrevMember->getMember();
1620 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001621 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001622 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001623 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001624 // Also the note!
1625 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001626 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001627 diag::note_fieldorbase_initialized_here) << 0
1628 << Field->getNameAsString();
1629 else {
1630 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001631 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001632 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001633 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001634 }
1635 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001636 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001637 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001638 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001639 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001640 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001641}
1642
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001643void
Anders Carlssondee9a302009-11-17 04:44:12 +00001644Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1645 // Ignore dependent destructors.
1646 if (Destructor->isDependentContext())
1647 return;
1648
1649 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001650
Anders Carlssondee9a302009-11-17 04:44:12 +00001651 // Non-static data members.
1652 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1653 E = ClassDecl->field_end(); I != E; ++I) {
1654 FieldDecl *Field = *I;
1655
1656 QualType FieldType = Context.getBaseElementType(Field->getType());
1657
1658 const RecordType* RT = FieldType->getAs<RecordType>();
1659 if (!RT)
1660 continue;
1661
1662 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1663 if (FieldClassDecl->hasTrivialDestructor())
1664 continue;
1665
1666 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1667 MarkDeclarationReferenced(Destructor->getLocation(),
1668 const_cast<CXXDestructorDecl*>(Dtor));
1669 }
1670
1671 // Bases.
1672 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1673 E = ClassDecl->bases_end(); Base != E; ++Base) {
1674 // Ignore virtual bases.
1675 if (Base->isVirtual())
1676 continue;
1677
1678 // Ignore trivial destructors.
1679 CXXRecordDecl *BaseClassDecl
1680 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1681 if (BaseClassDecl->hasTrivialDestructor())
1682 continue;
1683
1684 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1685 MarkDeclarationReferenced(Destructor->getLocation(),
1686 const_cast<CXXDestructorDecl*>(Dtor));
1687 }
1688
1689 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001690 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1691 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001692 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001693 CXXRecordDecl *BaseClassDecl
1694 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1695 if (BaseClassDecl->hasTrivialDestructor())
1696 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001697
1698 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1699 MarkDeclarationReferenced(Destructor->getLocation(),
1700 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001701 }
1702}
1703
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001704void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001705 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001706 return;
Mike Stump11289f42009-09-09 15:08:12 +00001707
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001708 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001709
1710 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001711 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001712 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001713}
1714
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001715namespace {
1716 /// PureVirtualMethodCollector - traverses a class and its superclasses
1717 /// and determines if it has any pure virtual methods.
1718 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1719 ASTContext &Context;
1720
Sebastian Redlb7d64912009-03-22 21:28:55 +00001721 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001722 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001723
1724 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001725 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001726
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001727 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001728
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001729 public:
Mike Stump11289f42009-09-09 15:08:12 +00001730 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001731 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001732
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001733 MethodList List;
1734 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001735
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001736 // Copy the temporary list to methods, and make sure to ignore any
1737 // null entries.
1738 for (size_t i = 0, e = List.size(); i != e; ++i) {
1739 if (List[i])
1740 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001741 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001742 }
Mike Stump11289f42009-09-09 15:08:12 +00001743
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001744 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001745
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001746 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1747 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001748 };
Mike Stump11289f42009-09-09 15:08:12 +00001749
1750 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001751 MethodList& Methods) {
1752 // First, collect the pure virtual methods for the base classes.
1753 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1754 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001755 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001756 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001757 if (BaseDecl && BaseDecl->isAbstract())
1758 Collect(BaseDecl, Methods);
1759 }
1760 }
Mike Stump11289f42009-09-09 15:08:12 +00001761
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001762 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001763 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001764
Anders Carlsson3c012712009-05-17 00:00:05 +00001765 MethodSetTy OverriddenMethods;
1766 size_t MethodsSize = Methods.size();
1767
Mike Stump11289f42009-09-09 15:08:12 +00001768 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001769 i != e; ++i) {
1770 // Traverse the record, looking for methods.
1771 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001772 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001773 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001774 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Anders Carlsson700179432009-10-18 19:34:08 +00001776 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001777 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1778 E = MD->end_overridden_methods(); I != E; ++I) {
1779 // Keep track of the overridden methods.
1780 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001781 }
1782 }
1783 }
Mike Stump11289f42009-09-09 15:08:12 +00001784
1785 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001786 // overridden.
1787 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1788 if (OverriddenMethods.count(Methods[i]))
1789 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001790 }
Mike Stump11289f42009-09-09 15:08:12 +00001791
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001792 }
1793}
Douglas Gregore8381c02008-11-05 04:29:56 +00001794
Anders Carlssoneabf7702009-08-27 00:13:57 +00001795
Mike Stump11289f42009-09-09 15:08:12 +00001796bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001797 unsigned DiagID, AbstractDiagSelID SelID,
1798 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001799 if (SelID == -1)
1800 return RequireNonAbstractType(Loc, T,
1801 PDiag(DiagID), CurrentRD);
1802 else
1803 return RequireNonAbstractType(Loc, T,
1804 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001805}
1806
Anders Carlssoneabf7702009-08-27 00:13:57 +00001807bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1808 const PartialDiagnostic &PD,
1809 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001810 if (!getLangOptions().CPlusPlus)
1811 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001813 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001814 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001815 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001816
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001817 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001818 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001819 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001820 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001821
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001822 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001823 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001826 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001827 if (!RT)
1828 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001829
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001830 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1831 if (!RD)
1832 return false;
1833
Anders Carlssonb57738b2009-03-24 17:23:42 +00001834 if (CurrentRD && CurrentRD != RD)
1835 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001836
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001837 if (!RD->isAbstract())
1838 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001839
Anders Carlssoneabf7702009-08-27 00:13:57 +00001840 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001841
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001842 // Check if we've already emitted the list of pure virtual functions for this
1843 // class.
1844 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1845 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001846
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001847 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001848
1849 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001850 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1851 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001852
1853 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001854 MD->getDeclName();
1855 }
1856
1857 if (!PureVirtualClassDiagSet)
1858 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1859 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001860
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001861 return true;
1862}
1863
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001864namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001865 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001866 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1867 Sema &SemaRef;
1868 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001869
Anders Carlssonb57738b2009-03-24 17:23:42 +00001870 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001871 bool Invalid = false;
1872
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001873 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1874 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001875 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001876
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001877 return Invalid;
1878 }
Mike Stump11289f42009-09-09 15:08:12 +00001879
Anders Carlssonb57738b2009-03-24 17:23:42 +00001880 public:
1881 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1882 : SemaRef(SemaRef), AbstractClass(ac) {
1883 Visit(SemaRef.Context.getTranslationUnitDecl());
1884 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001885
Anders Carlssonb57738b2009-03-24 17:23:42 +00001886 bool VisitFunctionDecl(const FunctionDecl *FD) {
1887 if (FD->isThisDeclarationADefinition()) {
1888 // No need to do the check if we're in a definition, because it requires
1889 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001890 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001891 return VisitDeclContext(FD);
1892 }
Mike Stump11289f42009-09-09 15:08:12 +00001893
Anders Carlssonb57738b2009-03-24 17:23:42 +00001894 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001895 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001896 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001897 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1898 diag::err_abstract_type_in_decl,
1899 Sema::AbstractReturnType,
1900 AbstractClass);
1901
Mike Stump11289f42009-09-09 15:08:12 +00001902 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001903 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001904 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001905 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001906 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001907 VD->getOriginalType(),
1908 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001909 Sema::AbstractParamType,
1910 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001911 }
1912
1913 return Invalid;
1914 }
Mike Stump11289f42009-09-09 15:08:12 +00001915
Anders Carlssonb57738b2009-03-24 17:23:42 +00001916 bool VisitDecl(const Decl* D) {
1917 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1918 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001919
Anders Carlssonb57738b2009-03-24 17:23:42 +00001920 return false;
1921 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001922 };
1923}
1924
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001925void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001926 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001927 SourceLocation LBrac,
1928 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001929 if (!TagDecl)
1930 return;
Mike Stump11289f42009-09-09 15:08:12 +00001931
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001932 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001933 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001934 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001935 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001936
Chris Lattner83f095c2009-03-28 19:18:32 +00001937 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001938 if (!RD->isAbstract()) {
1939 // Collect all the pure virtual methods and see if this is an abstract
1940 // class after all.
1941 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001942 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001943 RD->setAbstract(true);
1944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
1946 if (RD->isAbstract())
Douglas Gregor120f6a62009-11-17 06:14:37 +00001947 (void)AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor3c74d412009-10-14 20:14:33 +00001949 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001950 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001951}
1952
Douglas Gregor05379422008-11-03 17:51:48 +00001953/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1954/// special functions, such as the default constructor, copy
1955/// constructor, or destructor, to the given C++ class (C++
1956/// [special]p1). This routine can only be executed just before the
1957/// definition of the class is complete.
1958void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001959 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001960 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001961
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001962 // FIXME: Implicit declarations have exception specifications, which are
1963 // the union of the specifications of the implicitly called functions.
1964
Douglas Gregor05379422008-11-03 17:51:48 +00001965 if (!ClassDecl->hasUserDeclaredConstructor()) {
1966 // C++ [class.ctor]p5:
1967 // A default constructor for a class X is a constructor of class X
1968 // that can be called without an argument. If there is no
1969 // user-declared constructor for class X, a default constructor is
1970 // implicitly declared. An implicitly-declared default constructor
1971 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001972 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001973 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001974 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001975 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001976 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001977 Context.getFunctionType(Context.VoidTy,
1978 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001979 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001980 /*isExplicit=*/false,
1981 /*isInline=*/true,
1982 /*isImplicitlyDeclared=*/true);
1983 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001984 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001985 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001986 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001987 }
1988
1989 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1990 // C++ [class.copy]p4:
1991 // If the class definition does not explicitly declare a copy
1992 // constructor, one is declared implicitly.
1993
1994 // C++ [class.copy]p5:
1995 // The implicitly-declared copy constructor for a class X will
1996 // have the form
1997 //
1998 // X::X(const X&)
1999 //
2000 // if
2001 bool HasConstCopyConstructor = true;
2002
2003 // -- each direct or virtual base class B of X has a copy
2004 // constructor whose first parameter is of type const B& or
2005 // const volatile B&, and
2006 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2007 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2008 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002009 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002010 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002011 = BaseClassDecl->hasConstCopyConstructor(Context);
2012 }
2013
2014 // -- for all the nonstatic data members of X that are of a
2015 // class type M (or array thereof), each such class type
2016 // has a copy constructor whose first parameter is of type
2017 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002018 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2019 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002020 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002021 QualType FieldType = (*Field)->getType();
2022 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2023 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002024 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002025 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002026 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002027 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002028 = FieldClassDecl->hasConstCopyConstructor(Context);
2029 }
2030 }
2031
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002032 // Otherwise, the implicitly declared copy constructor will have
2033 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002034 //
2035 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002036 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002037 if (HasConstCopyConstructor)
2038 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002039 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002040
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002041 // An implicitly-declared copy constructor is an inline public
2042 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002043 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002044 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002045 CXXConstructorDecl *CopyConstructor
2046 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002047 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002048 Context.getFunctionType(Context.VoidTy,
2049 &ArgType, 1,
2050 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002051 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002052 /*isExplicit=*/false,
2053 /*isInline=*/true,
2054 /*isImplicitlyDeclared=*/true);
2055 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002056 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002057 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002058
2059 // Add the parameter to the constructor.
2060 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2061 ClassDecl->getLocation(),
2062 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002063 ArgType, /*DInfo=*/0,
2064 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002065 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002066 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002067 }
2068
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002069 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2070 // Note: The following rules are largely analoguous to the copy
2071 // constructor rules. Note that virtual bases are not taken into account
2072 // for determining the argument type of the operator. Note also that
2073 // operators taking an object instead of a reference are allowed.
2074 //
2075 // C++ [class.copy]p10:
2076 // If the class definition does not explicitly declare a copy
2077 // assignment operator, one is declared implicitly.
2078 // The implicitly-defined copy assignment operator for a class X
2079 // will have the form
2080 //
2081 // X& X::operator=(const X&)
2082 //
2083 // if
2084 bool HasConstCopyAssignment = true;
2085
2086 // -- each direct base class B of X has a copy assignment operator
2087 // whose parameter is of type const B&, const volatile B& or B,
2088 // and
2089 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2090 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002091 assert(!Base->getType()->isDependentType() &&
2092 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002093 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002094 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002095 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002096 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002097 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002098 }
2099
2100 // -- for all the nonstatic data members of X that are of a class
2101 // type M (or array thereof), each such class type has a copy
2102 // assignment operator whose parameter is of type const M&,
2103 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002104 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2105 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002106 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002107 QualType FieldType = (*Field)->getType();
2108 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2109 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002110 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002111 const CXXRecordDecl *FieldClassDecl
2112 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002113 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002114 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002115 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002116 }
2117 }
2118
2119 // Otherwise, the implicitly declared copy assignment operator will
2120 // have the form
2121 //
2122 // X& X::operator=(X&)
2123 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002124 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002125 if (HasConstCopyAssignment)
2126 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002127 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002128
2129 // An implicitly-declared copy assignment operator is an inline public
2130 // member of its class.
2131 DeclarationName Name =
2132 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2133 CXXMethodDecl *CopyAssignment =
2134 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2135 Context.getFunctionType(RetType, &ArgType, 1,
2136 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002137 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002138 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002139 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002140 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002141 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002142
2143 // Add the parameter to the operator.
2144 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2145 ClassDecl->getLocation(),
2146 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002147 ArgType, /*DInfo=*/0,
2148 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002149 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002150
2151 // Don't call addedAssignmentOperator. There is no way to distinguish an
2152 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002153 ClassDecl->addDecl(CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002154 }
2155
Douglas Gregor1349b452008-12-15 21:24:18 +00002156 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002157 // C++ [class.dtor]p2:
2158 // If a class has no user-declared destructor, a destructor is
2159 // declared implicitly. An implicitly-declared destructor is an
2160 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002161 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002162 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002163 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002164 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002165 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002166 Context.getFunctionType(Context.VoidTy,
2167 0, 0, false, 0),
2168 /*isInline=*/true,
2169 /*isImplicitlyDeclared=*/true);
2170 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002171 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002172 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002173 ClassDecl->addDecl(Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002174 }
Douglas Gregor05379422008-11-03 17:51:48 +00002175}
2176
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002177void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002178 Decl *D = TemplateD.getAs<Decl>();
2179 if (!D)
2180 return;
2181
2182 TemplateParameterList *Params = 0;
2183 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2184 Params = Template->getTemplateParameters();
2185 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2186 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2187 Params = PartialSpec->getTemplateParameters();
2188 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002189 return;
2190
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002191 for (TemplateParameterList::iterator Param = Params->begin(),
2192 ParamEnd = Params->end();
2193 Param != ParamEnd; ++Param) {
2194 NamedDecl *Named = cast<NamedDecl>(*Param);
2195 if (Named->getDeclName()) {
2196 S->AddDecl(DeclPtrTy::make(Named));
2197 IdResolver.AddDecl(Named);
2198 }
2199 }
2200}
2201
Douglas Gregor4d87df52008-12-16 21:30:33 +00002202/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2203/// parsing a top-level (non-nested) C++ class, and we are now
2204/// parsing those parts of the given Method declaration that could
2205/// not be parsed earlier (C++ [class.mem]p2), such as default
2206/// arguments. This action should enter the scope of the given
2207/// Method declaration as if we had just parsed the qualified method
2208/// name. However, it should not bring the parameters into scope;
2209/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002210void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002211 if (!MethodD)
2212 return;
Mike Stump11289f42009-09-09 15:08:12 +00002213
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002214 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002215
Douglas Gregor4d87df52008-12-16 21:30:33 +00002216 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002217 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002218 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002219 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2220 SS.setScopeRep(
2221 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002222 ActOnCXXEnterDeclaratorScope(S, SS);
2223}
2224
2225/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2226/// C++ method declaration. We're (re-)introducing the given
2227/// function parameter into scope for use in parsing later parts of
2228/// the method declaration. For example, we could see an
2229/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002230void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002231 if (!ParamD)
2232 return;
Mike Stump11289f42009-09-09 15:08:12 +00002233
Chris Lattner83f095c2009-03-28 19:18:32 +00002234 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002235
2236 // If this parameter has an unparsed default argument, clear it out
2237 // to make way for the parsed default argument.
2238 if (Param->hasUnparsedDefaultArg())
2239 Param->setDefaultArg(0);
2240
Chris Lattner83f095c2009-03-28 19:18:32 +00002241 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002242 if (Param->getDeclName())
2243 IdResolver.AddDecl(Param);
2244}
2245
2246/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2247/// processing the delayed method declaration for Method. The method
2248/// declaration is now considered finished. There may be a separate
2249/// ActOnStartOfFunctionDef action later (not necessarily
2250/// immediately!) for this method, if it was also defined inside the
2251/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002252void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002253 if (!MethodD)
2254 return;
Mike Stump11289f42009-09-09 15:08:12 +00002255
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002256 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002257
Chris Lattner83f095c2009-03-28 19:18:32 +00002258 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002259 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002260 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002261 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2262 SS.setScopeRep(
2263 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002264 ActOnCXXExitDeclaratorScope(S, SS);
2265
2266 // Now that we have our default arguments, check the constructor
2267 // again. It could produce additional diagnostics or affect whether
2268 // the class has implicitly-declared destructors, among other
2269 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002270 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2271 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002272
2273 // Check the default arguments, which we may have added.
2274 if (!Method->isInvalidDecl())
2275 CheckCXXDefaultArguments(Method);
2276}
2277
Douglas Gregor831c93f2008-11-05 20:51:48 +00002278/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002279/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002280/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002281/// emit diagnostics and set the invalid bit to true. In any case, the type
2282/// will be updated to reflect a well-formed type for the constructor and
2283/// returned.
2284QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2285 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002286 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002287
2288 // C++ [class.ctor]p3:
2289 // A constructor shall not be virtual (10.3) or static (9.4). A
2290 // constructor can be invoked for a const, volatile or const
2291 // volatile object. A constructor shall not be declared const,
2292 // volatile, or const volatile (9.3.2).
2293 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002294 if (!D.isInvalidType())
2295 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2296 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2297 << SourceRange(D.getIdentifierLoc());
2298 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002299 }
2300 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002301 if (!D.isInvalidType())
2302 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2303 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2304 << SourceRange(D.getIdentifierLoc());
2305 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002306 SC = FunctionDecl::None;
2307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Chris Lattner38378bf2009-04-25 08:28:21 +00002309 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2310 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002311 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002312 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2313 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002314 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002315 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2316 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002317 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002318 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2319 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002320 }
Mike Stump11289f42009-09-09 15:08:12 +00002321
Douglas Gregor831c93f2008-11-05 20:51:48 +00002322 // Rebuild the function type "R" without any type qualifiers (in
2323 // case any of the errors above fired) and with "void" as the
2324 // return type, since constructors don't have return types. We
2325 // *always* have to do this, because GetTypeForDeclarator will
2326 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002327 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002328 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2329 Proto->getNumArgs(),
2330 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002331}
2332
Douglas Gregor4d87df52008-12-16 21:30:33 +00002333/// CheckConstructor - Checks a fully-formed constructor for
2334/// well-formedness, issuing any diagnostics required. Returns true if
2335/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002336void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002337 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002338 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2339 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002340 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002341
2342 // C++ [class.copy]p3:
2343 // A declaration of a constructor for a class X is ill-formed if
2344 // its first parameter is of type (optionally cv-qualified) X and
2345 // either there are no other parameters or else all other
2346 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002347 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002348 ((Constructor->getNumParams() == 1) ||
2349 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002350 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2351 Constructor->getTemplateSpecializationKind()
2352 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002353 QualType ParamType = Constructor->getParamDecl(0)->getType();
2354 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2355 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002356 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2357 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002358 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002359
2360 // FIXME: Rather that making the constructor invalid, we should endeavor
2361 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002362 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002363 }
2364 }
Mike Stump11289f42009-09-09 15:08:12 +00002365
Douglas Gregor4d87df52008-12-16 21:30:33 +00002366 // Notify the class that we've added a constructor.
2367 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002368}
2369
Anders Carlsson2a50e952009-11-15 22:49:34 +00002370/// CheckDestructor - Checks a fully-formed destructor for
2371/// well-formedness, issuing any diagnostics required.
2372void Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2373 CXXRecordDecl *RD = Destructor->getParent();
2374
2375 if (Destructor->isVirtual()) {
2376 SourceLocation Loc;
2377
2378 if (!Destructor->isImplicit())
2379 Loc = Destructor->getLocation();
2380 else
2381 Loc = RD->getLocation();
2382
2383 // If we have a virtual destructor, look up the deallocation function
2384 FunctionDecl *OperatorDelete = 0;
2385 DeclarationName Name =
2386 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2387 if (!FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2388 Destructor->setOperatorDelete(OperatorDelete);
2389 }
2390}
2391
Mike Stump11289f42009-09-09 15:08:12 +00002392static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002393FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2394 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2395 FTI.ArgInfo[0].Param &&
2396 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2397}
2398
Douglas Gregor831c93f2008-11-05 20:51:48 +00002399/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2400/// the well-formednes of the destructor declarator @p D with type @p
2401/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002402/// emit diagnostics and set the declarator to invalid. Even if this happens,
2403/// will be updated to reflect a well-formed type for the destructor and
2404/// returned.
2405QualType Sema::CheckDestructorDeclarator(Declarator &D,
2406 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002407 // C++ [class.dtor]p1:
2408 // [...] A typedef-name that names a class is a class-name
2409 // (7.1.3); however, a typedef-name that names a class shall not
2410 // be used as the identifier in the declarator for a destructor
2411 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002412 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002413 if (isa<TypedefType>(DeclaratorType)) {
2414 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002415 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002416 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002417 }
2418
2419 // C++ [class.dtor]p2:
2420 // A destructor is used to destroy objects of its class type. A
2421 // destructor takes no parameters, and no return type can be
2422 // specified for it (not even void). The address of a destructor
2423 // shall not be taken. A destructor shall not be static. A
2424 // destructor can be invoked for a const, volatile or const
2425 // volatile object. A destructor shall not be declared const,
2426 // volatile or const volatile (9.3.2).
2427 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002428 if (!D.isInvalidType())
2429 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2430 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2431 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002432 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002433 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002434 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002435 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002436 // Destructors don't have return types, but the parser will
2437 // happily parse something like:
2438 //
2439 // class X {
2440 // float ~X();
2441 // };
2442 //
2443 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002444 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2445 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2446 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002447 }
Mike Stump11289f42009-09-09 15:08:12 +00002448
Chris Lattner38378bf2009-04-25 08:28:21 +00002449 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2450 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002451 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002452 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2453 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002454 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002455 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2456 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002457 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002458 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2459 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002460 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002461 }
2462
2463 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002464 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002465 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2466
2467 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002468 FTI.freeArgs();
2469 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002470 }
2471
Mike Stump11289f42009-09-09 15:08:12 +00002472 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002473 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002474 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002475 D.setInvalidType();
2476 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002477
2478 // Rebuild the function type "R" without any type qualifiers or
2479 // parameters (in case any of the errors above fired) and with
2480 // "void" as the return type, since destructors don't have return
2481 // types. We *always* have to do this, because GetTypeForDeclarator
2482 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002483 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002484}
2485
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002486/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2487/// well-formednes of the conversion function declarator @p D with
2488/// type @p R. If there are any errors in the declarator, this routine
2489/// will emit diagnostics and return true. Otherwise, it will return
2490/// false. Either way, the type @p R will be updated to reflect a
2491/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002492void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002493 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002494 // C++ [class.conv.fct]p1:
2495 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002496 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002497 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002498 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002499 if (!D.isInvalidType())
2500 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2501 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2502 << SourceRange(D.getIdentifierLoc());
2503 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002504 SC = FunctionDecl::None;
2505 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002506 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002507 // Conversion functions don't have return types, but the parser will
2508 // happily parse something like:
2509 //
2510 // class X {
2511 // float operator bool();
2512 // };
2513 //
2514 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002515 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2516 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2517 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002518 }
2519
2520 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002521 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002522 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2523
2524 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002525 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002526 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002527 }
2528
Mike Stump11289f42009-09-09 15:08:12 +00002529 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002530 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002531 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002532 D.setInvalidType();
2533 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002534
2535 // C++ [class.conv.fct]p4:
2536 // The conversion-type-id shall not represent a function type nor
2537 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002538 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002539 if (ConvType->isArrayType()) {
2540 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2541 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002542 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002543 } else if (ConvType->isFunctionType()) {
2544 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2545 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002546 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002547 }
2548
2549 // Rebuild the function type "R" without any parameters (in case any
2550 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002551 // return type.
2552 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002553 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002554
Douglas Gregor5fb53972009-01-14 15:45:31 +00002555 // C++0x explicit conversion operators.
2556 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002557 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002558 diag::warn_explicit_conversion_functions)
2559 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002560}
2561
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002562/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2563/// the declaration of the given C++ conversion function. This routine
2564/// is responsible for recording the conversion function in the C++
2565/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002566Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002567 assert(Conversion && "Expected to receive a conversion function declaration");
2568
Douglas Gregor4287b372008-12-12 08:25:50 +00002569 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002570
2571 // Make sure we aren't redeclaring the conversion function.
2572 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002573
2574 // C++ [class.conv.fct]p1:
2575 // [...] A conversion function is never used to convert a
2576 // (possibly cv-qualified) object to the (possibly cv-qualified)
2577 // same object type (or a reference to it), to a (possibly
2578 // cv-qualified) base class of that type (or a reference to it),
2579 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002580 // FIXME: Suppress this warning if the conversion function ends up being a
2581 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002582 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002583 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002584 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002585 ConvType = ConvTypeRef->getPointeeType();
2586 if (ConvType->isRecordType()) {
2587 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2588 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002589 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002590 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002591 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002592 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002593 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002594 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002595 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002596 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002597 }
2598
Douglas Gregor1dc98262008-12-26 15:00:45 +00002599 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002600 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002601 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002602 = Conversion->getDescribedFunctionTemplate())
2603 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCalld14a8642009-11-21 08:51:07 +00002604 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2605 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002606 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002607 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002608 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002609 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002610 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002611 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002612
Chris Lattner83f095c2009-03-28 19:18:32 +00002613 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002614}
2615
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002616//===----------------------------------------------------------------------===//
2617// Namespace Handling
2618//===----------------------------------------------------------------------===//
2619
2620/// ActOnStartNamespaceDef - This is called at the start of a namespace
2621/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002622Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2623 SourceLocation IdentLoc,
2624 IdentifierInfo *II,
2625 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002626 NamespaceDecl *Namespc =
2627 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2628 Namespc->setLBracLoc(LBrace);
2629
2630 Scope *DeclRegionScope = NamespcScope->getParent();
2631
2632 if (II) {
2633 // C++ [namespace.def]p2:
2634 // The identifier in an original-namespace-definition shall not have been
2635 // previously defined in the declarative region in which the
2636 // original-namespace-definition appears. The identifier in an
2637 // original-namespace-definition is the name of the namespace. Subsequently
2638 // in that declarative region, it is treated as an original-namespace-name.
2639
John McCall9f3059a2009-10-09 21:13:30 +00002640 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002641 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002642 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002643
Douglas Gregor91f84212008-12-11 16:49:14 +00002644 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2645 // This is an extended namespace definition.
2646 // Attach this namespace decl to the chain of extended namespace
2647 // definitions.
2648 OrigNS->setNextNamespace(Namespc);
2649 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002650
Mike Stump11289f42009-09-09 15:08:12 +00002651 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002652 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002653 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002654 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002655 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002656 } else if (PrevDecl) {
2657 // This is an invalid name redefinition.
2658 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2659 << Namespc->getDeclName();
2660 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2661 Namespc->setInvalidDecl();
2662 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002663 } else if (II->isStr("std") &&
2664 CurContext->getLookupContext()->isTranslationUnit()) {
2665 // This is the first "real" definition of the namespace "std", so update
2666 // our cache of the "std" namespace to point at this definition.
2667 if (StdNamespace) {
2668 // We had already defined a dummy namespace "std". Link this new
2669 // namespace definition to the dummy namespace "std".
2670 StdNamespace->setNextNamespace(Namespc);
2671 StdNamespace->setLocation(IdentLoc);
2672 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2673 }
2674
2675 // Make our StdNamespace cache point at the first real definition of the
2676 // "std" namespace.
2677 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002678 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002679
2680 PushOnScopeChains(Namespc, DeclRegionScope);
2681 } else {
John McCall4fa53422009-10-01 00:25:31 +00002682 // Anonymous namespaces.
2683
2684 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2685 // behaves as if it were replaced by
2686 // namespace unique { /* empty body */ }
2687 // using namespace unique;
2688 // namespace unique { namespace-body }
2689 // where all occurrences of 'unique' in a translation unit are
2690 // replaced by the same identifier and this identifier differs
2691 // from all other identifiers in the entire program.
2692
2693 // We just create the namespace with an empty name and then add an
2694 // implicit using declaration, just like the standard suggests.
2695 //
2696 // CodeGen enforces the "universally unique" aspect by giving all
2697 // declarations semantically contained within an anonymous
2698 // namespace internal linkage.
2699
2700 assert(Namespc->isAnonymousNamespace());
2701 CurContext->addDecl(Namespc);
2702
2703 UsingDirectiveDecl* UD
2704 = UsingDirectiveDecl::Create(Context, CurContext,
2705 /* 'using' */ LBrace,
2706 /* 'namespace' */ SourceLocation(),
2707 /* qualifier */ SourceRange(),
2708 /* NNS */ NULL,
2709 /* identifier */ SourceLocation(),
2710 Namespc,
2711 /* Ancestor */ CurContext);
2712 UD->setImplicit();
2713 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002714 }
2715
2716 // Although we could have an invalid decl (i.e. the namespace name is a
2717 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002718 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2719 // for the namespace has the declarations that showed up in that particular
2720 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002721 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002722 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002723}
2724
Sebastian Redla6602e92009-11-23 15:34:23 +00002725/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2726/// is a namespace alias, returns the namespace it points to.
2727static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2728 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2729 return AD->getNamespace();
2730 return dyn_cast_or_null<NamespaceDecl>(D);
2731}
2732
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002733/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2734/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002735void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2736 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002737 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2738 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2739 Namespc->setRBracLoc(RBrace);
2740 PopDeclContext();
2741}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002742
Chris Lattner83f095c2009-03-28 19:18:32 +00002743Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2744 SourceLocation UsingLoc,
2745 SourceLocation NamespcLoc,
2746 const CXXScopeSpec &SS,
2747 SourceLocation IdentLoc,
2748 IdentifierInfo *NamespcName,
2749 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002750 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2751 assert(NamespcName && "Invalid NamespcName.");
2752 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002753 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002754
Douglas Gregor889ceb72009-02-03 19:21:40 +00002755 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002756
Douglas Gregor34074322009-01-14 22:20:51 +00002757 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002758 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2759 LookupParsedName(R, S, &SS);
2760 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002761 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002762
John McCall9f3059a2009-10-09 21:13:30 +00002763 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002764 NamedDecl *Named = R.getFoundDecl();
2765 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2766 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002767 // C++ [namespace.udir]p1:
2768 // A using-directive specifies that the names in the nominated
2769 // namespace can be used in the scope in which the
2770 // using-directive appears after the using-directive. During
2771 // unqualified name lookup (3.4.1), the names appear as if they
2772 // were declared in the nearest enclosing namespace which
2773 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002774 // namespace. [Note: in this context, "contains" means "contains
2775 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002776
2777 // Find enclosing context containing both using-directive and
2778 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002779 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002780 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2781 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2782 CommonAncestor = CommonAncestor->getParent();
2783
Sebastian Redla6602e92009-11-23 15:34:23 +00002784 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002785 SS.getRange(),
2786 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00002787 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002788 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002789 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002790 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002791 }
2792
Douglas Gregor889ceb72009-02-03 19:21:40 +00002793 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002794 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002795 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002796}
2797
2798void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2799 // If scope has associated entity, then using directive is at namespace
2800 // or translation unit scope. We add UsingDirectiveDecls, into
2801 // it's lookup structure.
2802 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002803 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002804 else
2805 // Otherwise it is block-sope. using-directives will affect lookup
2806 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002807 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002808}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002809
Douglas Gregorfec52632009-06-20 00:51:54 +00002810
2811Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002812 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002813 SourceLocation UsingLoc,
2814 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002815 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002816 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002817 bool IsTypeName,
2818 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002819 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002820
Douglas Gregor220f4272009-11-04 16:30:06 +00002821 switch (Name.getKind()) {
2822 case UnqualifiedId::IK_Identifier:
2823 case UnqualifiedId::IK_OperatorFunctionId:
2824 case UnqualifiedId::IK_ConversionFunctionId:
2825 break;
2826
2827 case UnqualifiedId::IK_ConstructorName:
2828 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2829 << SS.getRange();
2830 return DeclPtrTy();
2831
2832 case UnqualifiedId::IK_DestructorName:
2833 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2834 << SS.getRange();
2835 return DeclPtrTy();
2836
2837 case UnqualifiedId::IK_TemplateId:
2838 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2839 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2840 return DeclPtrTy();
2841 }
2842
2843 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3f746822009-11-17 05:59:44 +00002844 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002845 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002846 TargetName, AttrList,
2847 /* IsInstantiation */ false,
2848 IsTypeName, TypenameLoc);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002849 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002850 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002851 UD->setAccess(AS);
2852 }
Mike Stump11289f42009-09-09 15:08:12 +00002853
Anders Carlsson696a3f12009-08-28 05:40:36 +00002854 return DeclPtrTy::make(UD);
2855}
2856
John McCall3f746822009-11-17 05:59:44 +00002857/// Builds a shadow declaration corresponding to a 'using' declaration.
2858static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2859 AccessSpecifier AS,
2860 UsingDecl *UD, NamedDecl *Orig) {
2861 // FIXME: diagnose hiding, collisions
2862
2863 // If we resolved to another shadow declaration, just coalesce them.
2864 if (isa<UsingShadowDecl>(Orig)) {
2865 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2866 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2867 }
2868
2869 UsingShadowDecl *Shadow
2870 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2871 UD->getLocation(), UD, Orig);
2872 UD->addShadowDecl(Shadow);
2873
2874 if (S)
2875 SemaRef.PushOnScopeChains(Shadow, S);
2876 else
2877 SemaRef.CurContext->addDecl(Shadow);
2878 Shadow->setAccess(AS);
2879
2880 return Shadow;
2881}
2882
John McCalle61f2ba2009-11-18 02:36:19 +00002883/// Builds a using declaration.
2884///
2885/// \param IsInstantiation - Whether this call arises from an
2886/// instantiation of an unresolved using declaration. We treat
2887/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00002888NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2889 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002890 const CXXScopeSpec &SS,
2891 SourceLocation IdentLoc,
2892 DeclarationName Name,
2893 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002894 bool IsInstantiation,
2895 bool IsTypeName,
2896 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002897 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2898 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002899
Anders Carlssonf038fc22009-08-28 05:49:21 +00002900 // FIXME: We ignore attributes for now.
2901 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002902
Anders Carlsson59140b32009-08-28 03:16:11 +00002903 if (SS.isEmpty()) {
2904 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002905 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002906 }
Mike Stump11289f42009-09-09 15:08:12 +00002907
2908 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002909 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2910
John McCall84c16cf2009-11-12 03:15:40 +00002911 DeclContext *LookupContext = computeDeclContext(SS);
2912 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00002913 if (IsTypeName) {
2914 return UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2915 UsingLoc, TypenameLoc,
2916 SS.getRange(), NNS,
2917 IdentLoc, Name);
2918 } else {
2919 return UnresolvedUsingValueDecl::Create(Context, CurContext,
2920 UsingLoc, SS.getRange(), NNS,
2921 IdentLoc, Name);
2922 }
Anders Carlssonf038fc22009-08-28 05:49:21 +00002923 }
Mike Stump11289f42009-09-09 15:08:12 +00002924
Anders Carlsson59140b32009-08-28 03:16:11 +00002925 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2926 // C++0x N2914 [namespace.udecl]p3:
2927 // A using-declaration used as a member-declaration shall refer to a member
2928 // of a base class of the class being defined, shall refer to a member of an
2929 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002930 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002931 // a member of a base class of the class being defined.
John McCall3f746822009-11-17 05:59:44 +00002932
John McCall84c16cf2009-11-12 03:15:40 +00002933 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2934 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlsson59140b32009-08-28 03:16:11 +00002935 Diag(SS.getRange().getBegin(),
2936 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2937 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002938 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002939 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002940 } else {
2941 // C++0x N2914 [namespace.udecl]p8:
2942 // A using-declaration for a class member shall be a member-declaration.
John McCall84c16cf2009-11-12 03:15:40 +00002943 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002944 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002945 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002946 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002947 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002948 }
2949
John McCall3f746822009-11-17 05:59:44 +00002950 // Look up the target name. Unlike most lookups, we do not want to
2951 // hide tag declarations: tag names are visible through the using
2952 // declaration even if hidden by ordinary names.
John McCall27b18f82009-11-17 02:14:36 +00002953 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00002954
2955 // We don't hide tags behind ordinary decls if we're in a
2956 // non-dependent context, but in a dependent context, this is
2957 // important for the stability of two-phase lookup.
2958 if (!IsInstantiation)
2959 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00002960
John McCall27b18f82009-11-17 02:14:36 +00002961 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00002962
John McCall9f3059a2009-10-09 21:13:30 +00002963 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00002964 Diag(IdentLoc, diag::err_no_member)
2965 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002966 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002967 }
2968
John McCall3f746822009-11-17 05:59:44 +00002969 if (R.isAmbiguous())
2970 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002971
John McCalle61f2ba2009-11-18 02:36:19 +00002972 if (IsTypeName) {
2973 // If we asked for a typename and got a non-type decl, error out.
2974 if (R.getResultKind() != LookupResult::Found
2975 || !isa<TypeDecl>(R.getFoundDecl())) {
2976 Diag(IdentLoc, diag::err_using_typename_non_type);
2977 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2978 Diag((*I)->getUnderlyingDecl()->getLocation(),
2979 diag::note_using_decl_target);
2980 return 0;
2981 }
2982 } else {
2983 // If we asked for a non-typename and we got a type, error out,
2984 // but only if this is an instantiation of an unresolved using
2985 // decl. Otherwise just silently find the type name.
2986 if (IsInstantiation &&
2987 R.getResultKind() == LookupResult::Found &&
2988 isa<TypeDecl>(R.getFoundDecl())) {
2989 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
2990 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
2991 return 0;
2992 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002993 }
2994
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002995 // C++0x N2914 [namespace.udecl]p6:
2996 // A using-declaration shall not name a namespace.
John McCall3f746822009-11-17 05:59:44 +00002997 if (R.getResultKind() == LookupResult::Found
2998 && isa<NamespaceDecl>(R.getFoundDecl())) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002999 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3000 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003001 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
John McCall3f746822009-11-17 05:59:44 +00003004 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc,
3005 SS.getRange(), UsingLoc, NNS, Name,
3006 IsTypeName);
3007
3008 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3009 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3010
3011 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003012}
3013
Mike Stump11289f42009-09-09 15:08:12 +00003014Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003015 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003016 SourceLocation AliasLoc,
3017 IdentifierInfo *Alias,
3018 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003019 SourceLocation IdentLoc,
3020 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003021
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003022 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003023 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3024 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003025
Anders Carlssondca83c42009-03-28 06:23:46 +00003026 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003027 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003028 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003029 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003030 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003031 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003032 if (!R.isAmbiguous() && !R.empty() &&
3033 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003034 return DeclPtrTy();
3035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036
Anders Carlssondca83c42009-03-28 06:23:46 +00003037 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3038 diag::err_redefinition_different_kind;
3039 Diag(AliasLoc, DiagID) << Alias;
3040 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003041 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003042 }
3043
John McCall27b18f82009-11-17 02:14:36 +00003044 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003045 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003046
John McCall9f3059a2009-10-09 21:13:30 +00003047 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003048 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003049 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003050 }
Mike Stump11289f42009-09-09 15:08:12 +00003051
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003052 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003053 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3054 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003055 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003056 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003057
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003058 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003059 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003060}
3061
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003062void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3063 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003064 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3065 !Constructor->isUsed()) &&
3066 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003067
Eli Friedman9cf6b592009-11-09 19:20:36 +00003068 CXXRecordDecl *ClassDecl
3069 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3070 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003071
Eli Friedman9cf6b592009-11-09 19:20:36 +00003072 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
3073 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
3074 << Context.getTagDeclType(ClassDecl);
3075 Constructor->setInvalidDecl();
3076 } else {
3077 Constructor->setUsed();
3078 }
Eli Friedmand7686ef2009-11-09 01:05:47 +00003079 return;
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003080}
3081
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003082void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003083 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003084 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3085 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003086 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003087 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3088 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003089 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003090 // implicitly defined, all the implicitly-declared default destructors
3091 // for its base class and its non-static data members shall have been
3092 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003093 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3094 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003095 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003096 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003097 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003098 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003099 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3100 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3101 else
Mike Stump11289f42009-09-09 15:08:12 +00003102 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003103 "DefineImplicitDestructor - missing dtor in a base class");
3104 }
3105 }
Mike Stump11289f42009-09-09 15:08:12 +00003106
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003107 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3108 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003109 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3110 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3111 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003112 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003113 CXXRecordDecl *FieldClassDecl
3114 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3115 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003116 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003117 const_cast<CXXDestructorDecl*>(
3118 FieldClassDecl->getDestructor(Context)))
3119 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3120 else
Mike Stump11289f42009-09-09 15:08:12 +00003121 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003122 "DefineImplicitDestructor - missing dtor in class of a data member");
3123 }
3124 }
3125 }
3126 Destructor->setUsed();
3127}
3128
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003129void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3130 CXXMethodDecl *MethodDecl) {
3131 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3132 MethodDecl->getOverloadedOperator() == OO_Equal &&
3133 !MethodDecl->isUsed()) &&
3134 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003135
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003136 CXXRecordDecl *ClassDecl
3137 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003138
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003139 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003140 // Before the implicitly-declared copy assignment operator for a class is
3141 // implicitly defined, all implicitly-declared copy assignment operators
3142 // for its direct base classes and its nonstatic data members shall have
3143 // been implicitly defined.
3144 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003145 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3146 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003147 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003148 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003149 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003150 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3151 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3152 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003153 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3154 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003155 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3156 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3157 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003158 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003159 CXXRecordDecl *FieldClassDecl
3160 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003161 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003162 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3163 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003164 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003165 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003166 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3167 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003168 Diag(CurrentLocation, diag::note_first_required_here);
3169 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003170 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003171 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003172 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3173 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003174 Diag(CurrentLocation, diag::note_first_required_here);
3175 err = true;
3176 }
3177 }
3178 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003179 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003180}
3181
3182CXXMethodDecl *
3183Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3184 CXXRecordDecl *ClassDecl) {
3185 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3186 QualType RHSType(LHSType);
3187 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003188 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003189 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003190 RHSType = Context.getCVRQualifiedType(RHSType,
3191 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003192 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3193 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003194 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003195 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3196 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003197 SourceLocation()));
3198 Expr *Args[2] = { &*LHS, &*RHS };
3199 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003200 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003201 CandidateSet);
3202 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003203 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003204 ClassDecl->getLocation(), Best) == OR_Success)
3205 return cast<CXXMethodDecl>(Best->Function);
3206 assert(false &&
3207 "getAssignOperatorMethod - copy assignment operator method not found");
3208 return 0;
3209}
3210
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003211void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3212 CXXConstructorDecl *CopyConstructor,
3213 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003214 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003215 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3216 !CopyConstructor->isUsed()) &&
3217 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003218
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003219 CXXRecordDecl *ClassDecl
3220 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3221 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003222 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003223 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003224 // implicitly defined, all the implicitly-declared copy constructors
3225 // for its base class and its non-static data members shall have been
3226 // implicitly defined.
3227 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3228 Base != ClassDecl->bases_end(); ++Base) {
3229 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003230 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003231 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003232 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003233 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003234 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003235 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3236 FieldEnd = ClassDecl->field_end();
3237 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003238 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3239 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3240 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003241 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003242 CXXRecordDecl *FieldClassDecl
3243 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003244 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003245 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003246 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003247 }
3248 }
3249 CopyConstructor->setUsed();
3250}
3251
Anders Carlsson6eb55572009-08-25 05:12:04 +00003252Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003253Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003254 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003255 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003256 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003257
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003258 // C++ [class.copy]p15:
3259 // Whenever a temporary class object is copied using a copy constructor, and
3260 // this object and the copy have the same cv-unqualified type, an
3261 // implementation is permitted to treat the original and the copy as two
3262 // different ways of referring to the same object and not perform a copy at
3263 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003264
Anders Carlsson250aada2009-08-16 05:13:48 +00003265 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003266 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003267 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003268 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3269 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003270 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3271 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3272 E = ICE->getSubExpr();
3273
Anders Carlsson250aada2009-08-16 05:13:48 +00003274 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3275 Elidable = true;
3276 }
Mike Stump11289f42009-09-09 15:08:12 +00003277
3278 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003279 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003280}
3281
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003282/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3283/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003284Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003285Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3286 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003287 MultiExprArg ExprArgs) {
3288 unsigned NumExprs = ExprArgs.size();
3289 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003290
Douglas Gregor27381f32009-11-23 12:27:39 +00003291 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003292 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3293 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003294}
3295
Anders Carlsson574315a2009-08-27 05:08:22 +00003296Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003297Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3298 QualType Ty,
3299 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003300 MultiExprArg Args,
3301 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003302 unsigned NumExprs = Args.size();
3303 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003304
Douglas Gregor27381f32009-11-23 12:27:39 +00003305 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003306 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3307 TyBeginLoc, Exprs,
3308 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003309}
3310
3311
Mike Stump11289f42009-09-09 15:08:12 +00003312bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003313 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003314 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003315 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003316 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003317 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003318 if (TempResult.isInvalid())
3319 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003320
Anders Carlsson6eb55572009-08-25 05:12:04 +00003321 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003322 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003323 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003324 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003325
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003326 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003327}
3328
Mike Stump11289f42009-09-09 15:08:12 +00003329void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003330 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003331 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003332 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003333 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003334 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003335 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003336}
3337
Mike Stump11289f42009-09-09 15:08:12 +00003338/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003339/// ActOnDeclarator, when a C++ direct initializer is present.
3340/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003341void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3342 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003343 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003344 SourceLocation *CommaLocs,
3345 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003346 unsigned NumExprs = Exprs.size();
3347 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003348 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003349
3350 // If there is no declaration, there was an error parsing it. Just ignore
3351 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003352 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003353 return;
Mike Stump11289f42009-09-09 15:08:12 +00003354
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003355 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3356 if (!VDecl) {
3357 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3358 RealDecl->setInvalidDecl();
3359 return;
3360 }
3361
Douglas Gregor402250f2009-08-26 21:14:46 +00003362 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003363 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003364 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3365 //
3366 // Clients that want to distinguish between the two forms, can check for
3367 // direct initializer using VarDecl::hasCXXDirectInitializer().
3368 // A major benefit is that clients that don't particularly care about which
3369 // exactly form was it (like the CodeGen) can handle both cases without
3370 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003371
Douglas Gregor402250f2009-08-26 21:14:46 +00003372 // If either the declaration has a dependent type or if any of the expressions
3373 // is type-dependent, we represent the initialization via a ParenListExpr for
3374 // later use during template instantiation.
3375 if (VDecl->getType()->isDependentType() ||
3376 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3377 // Let clients know that initialization was done with a direct initializer.
3378 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003379
Douglas Gregor402250f2009-08-26 21:14:46 +00003380 // Store the initialization expressions as a ParenListExpr.
3381 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003382 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003383 new (Context) ParenListExpr(Context, LParenLoc,
3384 (Expr **)Exprs.release(),
3385 NumExprs, RParenLoc));
3386 return;
3387 }
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregor402250f2009-08-26 21:14:46 +00003389
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003390 // C++ 8.5p11:
3391 // The form of initialization (using parentheses or '=') is generally
3392 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003393 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003394 QualType DeclInitType = VDecl->getType();
3395 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003396 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003397
Douglas Gregor4044d992009-03-24 16:43:20 +00003398 // FIXME: This isn't the right place to complete the type.
3399 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3400 diag::err_typecheck_decl_incomplete_type)) {
3401 VDecl->setInvalidDecl();
3402 return;
3403 }
3404
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003405 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003406 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3407
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003408 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003409 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003410 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003411 VDecl->getLocation(),
3412 SourceRange(VDecl->getLocation(),
3413 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003414 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003415 IK_Direct,
3416 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003417 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003418 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003419 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003420 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003421 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003422 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003423 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003424 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003425 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003426 return;
3427 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003428
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003429 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003430 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3431 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003432 RealDecl->setInvalidDecl();
3433 return;
3434 }
3435
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003436 // Let clients know that initialization was done with a direct initializer.
3437 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003438
3439 assert(NumExprs == 1 && "Expected 1 expression");
3440 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003441 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3442 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003443}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003444
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003445/// \brief Add the applicable constructor candidates for an initialization
3446/// by constructor.
3447static void AddConstructorInitializationCandidates(Sema &SemaRef,
3448 QualType ClassType,
3449 Expr **Args,
3450 unsigned NumArgs,
3451 Sema::InitializationKind Kind,
3452 OverloadCandidateSet &CandidateSet) {
3453 // C++ [dcl.init]p14:
3454 // If the initialization is direct-initialization, or if it is
3455 // copy-initialization where the cv-unqualified version of the
3456 // source type is the same class as, or a derived class of, the
3457 // class of the destination, constructors are considered. The
3458 // applicable constructors are enumerated (13.3.1.3), and the
3459 // best one is chosen through overload resolution (13.3). The
3460 // constructor so selected is called to initialize the object,
3461 // with the initializer expression(s) as its argument(s). If no
3462 // constructor applies, or the overload resolution is ambiguous,
3463 // the initialization is ill-formed.
3464 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3465 assert(ClassRec && "Can only initialize a class type here");
3466
3467 // FIXME: When we decide not to synthesize the implicitly-declared
3468 // constructors, we'll need to make them appear here.
3469
3470 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3471 DeclarationName ConstructorName
3472 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3473 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3474 DeclContext::lookup_const_iterator Con, ConEnd;
3475 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3476 Con != ConEnd; ++Con) {
3477 // Find the constructor (which may be a template).
3478 CXXConstructorDecl *Constructor = 0;
3479 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3480 if (ConstructorTmpl)
3481 Constructor
3482 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3483 else
3484 Constructor = cast<CXXConstructorDecl>(*Con);
3485
3486 if ((Kind == Sema::IK_Direct) ||
3487 (Kind == Sema::IK_Copy &&
3488 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3489 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3490 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00003491 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3492 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003493 Args, NumArgs, CandidateSet);
3494 else
3495 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3496 }
3497 }
3498}
3499
3500/// \brief Attempt to perform initialization by constructor
3501/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3502/// copy-initialization.
3503///
3504/// This routine determines whether initialization by constructor is possible,
3505/// but it does not emit any diagnostics in the case where the initialization
3506/// is ill-formed.
3507///
3508/// \param ClassType the type of the object being initialized, which must have
3509/// class type.
3510///
3511/// \param Args the arguments provided to initialize the object
3512///
3513/// \param NumArgs the number of arguments provided to initialize the object
3514///
3515/// \param Kind the type of initialization being performed
3516///
3517/// \returns the constructor used to initialize the object, if successful.
3518/// Otherwise, emits a diagnostic and returns NULL.
3519CXXConstructorDecl *
3520Sema::TryInitializationByConstructor(QualType ClassType,
3521 Expr **Args, unsigned NumArgs,
3522 SourceLocation Loc,
3523 InitializationKind Kind) {
3524 // Build the overload candidate set
3525 OverloadCandidateSet CandidateSet;
3526 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3527 CandidateSet);
3528
3529 // Determine whether we found a constructor we can use.
3530 OverloadCandidateSet::iterator Best;
3531 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3532 case OR_Success:
3533 case OR_Deleted:
3534 // We found a constructor. Return it.
3535 return cast<CXXConstructorDecl>(Best->Function);
3536
3537 case OR_No_Viable_Function:
3538 case OR_Ambiguous:
3539 // Overload resolution failed. Return nothing.
3540 return 0;
3541 }
3542
3543 // Silence GCC warning
3544 return 0;
3545}
3546
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003547/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3548/// may occur as part of direct-initialization or copy-initialization.
3549///
3550/// \param ClassType the type of the object being initialized, which must have
3551/// class type.
3552///
3553/// \param ArgsPtr the arguments provided to initialize the object
3554///
3555/// \param Loc the source location where the initialization occurs
3556///
3557/// \param Range the source range that covers the entire initialization
3558///
3559/// \param InitEntity the name of the entity being initialized, if known
3560///
3561/// \param Kind the type of initialization being performed
3562///
3563/// \param ConvertedArgs a vector that will be filled in with the
3564/// appropriately-converted arguments to the constructor (if initialization
3565/// succeeded).
3566///
3567/// \returns the constructor used to initialize the object, if successful.
3568/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003569CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003570Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003571 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003572 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003573 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003574 InitializationKind Kind,
3575 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003576
3577 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003578 Expr **Args = (Expr **)ArgsPtr.get();
3579 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003580 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003581 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3582 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00003583
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003584 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003585 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003586 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003587 // We found a constructor. Break out so that we can convert the arguments
3588 // appropriately.
3589 break;
Mike Stump11289f42009-09-09 15:08:12 +00003590
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003591 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003592 if (InitEntity)
3593 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003594 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003595 else
3596 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003597 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003598 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003599 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003600
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003601 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003602 if (InitEntity)
3603 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3604 else
3605 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003606 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3607 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003608
3609 case OR_Deleted:
3610 if (InitEntity)
3611 Diag(Loc, diag::err_ovl_deleted_init)
3612 << Best->Function->isDeleted()
3613 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003614 else {
3615 const CXXRecordDecl *RD =
3616 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003617 Diag(Loc, diag::err_ovl_deleted_init)
3618 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003619 << RD->getDeclName() << Range;
3620 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00003621 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3622 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003623 }
Mike Stump11289f42009-09-09 15:08:12 +00003624
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003625 // Convert the arguments, fill in default arguments, etc.
3626 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3627 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3628 return 0;
3629
3630 return Constructor;
3631}
3632
3633/// \brief Given a constructor and the set of arguments provided for the
3634/// constructor, convert the arguments and add any required default arguments
3635/// to form a proper call to this constructor.
3636///
3637/// \returns true if an error occurred, false otherwise.
3638bool
3639Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3640 MultiExprArg ArgsPtr,
3641 SourceLocation Loc,
3642 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3643 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3644 unsigned NumArgs = ArgsPtr.size();
3645 Expr **Args = (Expr **)ArgsPtr.get();
3646
3647 const FunctionProtoType *Proto
3648 = Constructor->getType()->getAs<FunctionProtoType>();
3649 assert(Proto && "Constructor without a prototype?");
3650 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003651
3652 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003653 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003654 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003655 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003656 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003657
3658 VariadicCallType CallType =
3659 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3660 llvm::SmallVector<Expr *, 8> AllArgs;
3661 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3662 Proto, 0, Args, NumArgs, AllArgs,
3663 CallType);
3664 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3665 ConvertedArgs.push_back(AllArgs[i]);
3666 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003667}
3668
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003669/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3670/// determine whether they are reference-related,
3671/// reference-compatible, reference-compatible with added
3672/// qualification, or incompatible, for use in C++ initialization by
3673/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3674/// type, and the first type (T1) is the pointee type of the reference
3675/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003676Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003677Sema::CompareReferenceRelationship(SourceLocation Loc,
3678 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003679 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003680 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003681 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003682 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003683
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003684 QualType T1 = Context.getCanonicalType(OrigT1);
3685 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003686 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3687 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003688
3689 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003690 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003691 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003692 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003693 if (UnqualT1 == UnqualT2)
3694 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003695 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3696 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3697 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003698 DerivedToBase = true;
3699 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003700 return Ref_Incompatible;
3701
3702 // At this point, we know that T1 and T2 are reference-related (at
3703 // least).
3704
3705 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003706 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003707 // reference-related to T2 and cv1 is the same cv-qualification
3708 // as, or greater cv-qualification than, cv2. For purposes of
3709 // overload resolution, cases for which cv1 is greater
3710 // cv-qualification than cv2 are identified as
3711 // reference-compatible with added qualification (see 13.3.3.2).
3712 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3713 return Ref_Compatible;
3714 else if (T1.isMoreQualifiedThan(T2))
3715 return Ref_Compatible_With_Added_Qualification;
3716 else
3717 return Ref_Related;
3718}
3719
3720/// CheckReferenceInit - Check the initialization of a reference
3721/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3722/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003723/// list), and DeclType is the type of the declaration. When ICS is
3724/// non-null, this routine will compute the implicit conversion
3725/// sequence according to C++ [over.ics.ref] and will not produce any
3726/// diagnostics; when ICS is null, it will emit diagnostics when any
3727/// errors are found. Either way, a return value of true indicates
3728/// that there was a failure, a return value of false indicates that
3729/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003730///
3731/// When @p SuppressUserConversions, user-defined conversions are
3732/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003733/// When @p AllowExplicit, we also permit explicit user-defined
3734/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003735/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00003736/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3737/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00003738bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003739Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003740 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003741 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003742 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00003743 ImplicitConversionSequence *ICS,
3744 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003745 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3746
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003747 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003748 QualType T2 = Init->getType();
3749
Douglas Gregorcd695e52008-11-10 20:40:00 +00003750 // If the initializer is the address of an overloaded function, try
3751 // to resolve the overloaded function. If all goes well, T2 is the
3752 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003753 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003754 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003755 ICS != 0);
3756 if (Fn) {
3757 // Since we're performing this reference-initialization for
3758 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003759 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003760 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003761 return true;
3762
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003763 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003764 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003765
3766 T2 = Fn->getType();
3767 }
3768 }
3769
Douglas Gregor786ab212008-10-29 02:00:59 +00003770 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003771 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003772 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003773 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3774 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003775 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003776 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003777
3778 // Most paths end in a failed conversion.
3779 if (ICS)
3780 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003781
3782 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003783 // A reference to type "cv1 T1" is initialized by an expression
3784 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003785
3786 // -- If the initializer expression
3787
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003788 // Rvalue references cannot bind to lvalues (N2812).
3789 // There is absolutely no situation where they can. In particular, note that
3790 // this is ill-formed, even if B has a user-defined conversion to A&&:
3791 // B b;
3792 // A&& r = b;
3793 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3794 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003795 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003796 << Init->getSourceRange();
3797 return true;
3798 }
3799
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003800 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003801 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3802 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003803 //
3804 // Note that the bit-field check is skipped if we are just computing
3805 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003806 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003807 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003808 BindsDirectly = true;
3809
Douglas Gregor786ab212008-10-29 02:00:59 +00003810 if (ICS) {
3811 // C++ [over.ics.ref]p1:
3812 // When a parameter of reference type binds directly (8.5.3)
3813 // to an argument expression, the implicit conversion sequence
3814 // is the identity conversion, unless the argument expression
3815 // has a type that is a derived class of the parameter type,
3816 // in which case the implicit conversion sequence is a
3817 // derived-to-base Conversion (13.3.3.1).
3818 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3819 ICS->Standard.First = ICK_Identity;
3820 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3821 ICS->Standard.Third = ICK_Identity;
3822 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3823 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003824 ICS->Standard.ReferenceBinding = true;
3825 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003826 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003827 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003828
3829 // Nothing more to do: the inaccessibility/ambiguity check for
3830 // derived-to-base conversions is suppressed when we're
3831 // computing the implicit conversion sequence (C++
3832 // [over.best.ics]p2).
3833 return false;
3834 } else {
3835 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003836 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3837 if (DerivedToBase)
3838 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003839 else if(CheckExceptionSpecCompatibility(Init, T1))
3840 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003841 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003842 }
3843 }
3844
3845 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003846 // implicitly converted to an lvalue of type "cv3 T3,"
3847 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003848 // 92) (this conversion is selected by enumerating the
3849 // applicable conversion functions (13.3.1.6) and choosing
3850 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003851 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003852 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003853 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003854 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003855
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003856 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00003857 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003858 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003859 for (UnresolvedSet::iterator I = Conversions->begin(),
3860 E = Conversions->end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00003861 FunctionTemplateDecl *ConvTemplate
John McCalld14a8642009-11-21 08:51:07 +00003862 = dyn_cast<FunctionTemplateDecl>(*I);
Douglas Gregor05155d82009-08-21 23:19:43 +00003863 CXXConversionDecl *Conv;
3864 if (ConvTemplate)
3865 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3866 else
John McCalld14a8642009-11-21 08:51:07 +00003867 Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003868
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003869 // If the conversion function doesn't return a reference type,
3870 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003871 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003872 (AllowExplicit || !Conv->isExplicit())) {
3873 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003874 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003875 CandidateSet);
3876 else
3877 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3878 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003879 }
3880
3881 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003882 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003883 case OR_Success:
3884 // This is a direct binding.
3885 BindsDirectly = true;
3886
3887 if (ICS) {
3888 // C++ [over.ics.ref]p1:
3889 //
3890 // [...] If the parameter binds directly to the result of
3891 // applying a conversion function to the argument
3892 // expression, the implicit conversion sequence is a
3893 // user-defined conversion sequence (13.3.3.1.2), with the
3894 // second standard conversion sequence either an identity
3895 // conversion or, if the conversion function returns an
3896 // entity of a type that is a derived class of the parameter
3897 // type, a derived-to-base Conversion.
3898 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3899 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3900 ICS->UserDefined.After = Best->FinalConversion;
3901 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003902 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003903 assert(ICS->UserDefined.After.ReferenceBinding &&
3904 ICS->UserDefined.After.DirectBinding &&
3905 "Expected a direct reference binding!");
3906 return false;
3907 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003908 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003909 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003910 CastExpr::CK_UserDefinedConversion,
3911 cast<CXXMethodDecl>(Best->Function),
3912 Owned(Init));
3913 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003914
3915 if (CheckExceptionSpecCompatibility(Init, T1))
3916 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003917 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3918 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003919 }
3920 break;
3921
3922 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003923 if (ICS) {
3924 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3925 Cand != CandidateSet.end(); ++Cand)
3926 if (Cand->Viable)
3927 ICS->ConversionFunctionSet.push_back(Cand->Function);
3928 break;
3929 }
3930 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3931 << Init->getSourceRange();
3932 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003933 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003934
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003935 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003936 case OR_Deleted:
3937 // There was no suitable conversion, or we found a deleted
3938 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003939 break;
3940 }
3941 }
Mike Stump11289f42009-09-09 15:08:12 +00003942
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003943 if (BindsDirectly) {
3944 // C++ [dcl.init.ref]p4:
3945 // [...] In all cases where the reference-related or
3946 // reference-compatible relationship of two types is used to
3947 // establish the validity of a reference binding, and T1 is a
3948 // base class of T2, a program that necessitates such a binding
3949 // is ill-formed if T1 is an inaccessible (clause 11) or
3950 // ambiguous (10.2) base class of T2.
3951 //
3952 // Note that we only check this condition when we're allowed to
3953 // complain about errors, because we should not be checking for
3954 // ambiguity (or inaccessibility) unless the reference binding
3955 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003956 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003957 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00003958 Init->getSourceRange(),
3959 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00003960 else
3961 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003962 }
3963
3964 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003965 // type (i.e., cv1 shall be const), or the reference shall be an
3966 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00003967 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003968 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003969 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003970 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3971 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003972 return true;
3973 }
3974
3975 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003976 // class type, and "cv1 T1" is reference-compatible with
3977 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003978 // following ways (the choice is implementation-defined):
3979 //
3980 // -- The reference is bound to the object represented by
3981 // the rvalue (see 3.10) or to a sub-object within that
3982 // object.
3983 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00003984 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003985 // a constructor is called to copy the entire rvalue
3986 // object into the temporary. The reference is bound to
3987 // the temporary or to a sub-object within the
3988 // temporary.
3989 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003990 // The constructor that would be used to make the copy
3991 // shall be callable whether or not the copy is actually
3992 // done.
3993 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003994 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003995 // freedom, so we will always take the first option and never build
3996 // a temporary in this case. FIXME: We will, however, have to check
3997 // for the presence of a copy constructor in C++98/03 mode.
3998 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003999 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4000 if (ICS) {
4001 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4002 ICS->Standard.First = ICK_Identity;
4003 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4004 ICS->Standard.Third = ICK_Identity;
4005 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4006 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004007 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004008 ICS->Standard.DirectBinding = false;
4009 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004010 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004011 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004012 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4013 if (DerivedToBase)
4014 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004015 else if(CheckExceptionSpecCompatibility(Init, T1))
4016 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004017 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004018 }
4019 return false;
4020 }
4021
Eli Friedman44b83ee2009-08-05 19:21:58 +00004022 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004023 // initialized from the initializer expression using the
4024 // rules for a non-reference copy initialization (8.5). The
4025 // reference is then bound to the temporary. If T1 is
4026 // reference-related to T2, cv1 must be the same
4027 // cv-qualification as, or greater cv-qualification than,
4028 // cv2; otherwise, the program is ill-formed.
4029 if (RefRelationship == Ref_Related) {
4030 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4031 // we would be reference-compatible or reference-compatible with
4032 // added qualification. But that wasn't the case, so the reference
4033 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004034 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004035 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004036 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4037 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004038 return true;
4039 }
4040
Douglas Gregor576e98c2009-01-30 23:27:23 +00004041 // If at least one of the types is a class type, the types are not
4042 // related, and we aren't allowed any user conversions, the
4043 // reference binding fails. This case is important for breaking
4044 // recursion, since TryImplicitConversion below will attempt to
4045 // create a temporary through the use of a copy constructor.
4046 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4047 (T1->isRecordType() || T2->isRecordType())) {
4048 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004049 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00004050 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4051 return true;
4052 }
4053
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004054 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004055 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004056 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004057 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004058 // When a parameter of reference type is not bound directly to
4059 // an argument expression, the conversion sequence is the one
4060 // required to convert the argument expression to the
4061 // underlying type of the reference according to
4062 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4063 // to copy-initializing a temporary of the underlying type with
4064 // the argument expression. Any difference in top-level
4065 // cv-qualification is subsumed by the initialization itself
4066 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004067 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4068 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004069 /*ForceRValue=*/false,
4070 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004071
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004072 // Of course, that's still a reference binding.
4073 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4074 ICS->Standard.ReferenceBinding = true;
4075 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004076 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004077 ImplicitConversionSequence::UserDefinedConversion) {
4078 ICS->UserDefined.After.ReferenceBinding = true;
4079 ICS->UserDefined.After.RRefBinding = isRValRef;
4080 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004081 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4082 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004083 ImplicitConversionSequence Conversions;
4084 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4085 false, false,
4086 Conversions);
4087 if (badConversion) {
4088 if ((Conversions.ConversionKind ==
4089 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004090 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004091 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004092 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4093 for (int j = Conversions.ConversionFunctionSet.size()-1;
4094 j >= 0; j--) {
4095 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4096 Diag(Func->getLocation(), diag::err_ovl_candidate);
4097 }
4098 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004099 else {
4100 if (isRValRef)
4101 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4102 << Init->getSourceRange();
4103 else
4104 Diag(DeclLoc, diag::err_invalid_initialization)
4105 << DeclType << Init->getType() << Init->getSourceRange();
4106 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004107 }
4108 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004109 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004110}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004111
4112/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4113/// of this overloaded operator is well-formed. If so, returns false;
4114/// otherwise, emits appropriate diagnostics and returns true.
4115bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004116 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004117 "Expected an overloaded operator declaration");
4118
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004119 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4120
Mike Stump11289f42009-09-09 15:08:12 +00004121 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004122 // The allocation and deallocation functions, operator new,
4123 // operator new[], operator delete and operator delete[], are
4124 // described completely in 3.7.3. The attributes and restrictions
4125 // found in the rest of this subclause do not apply to them unless
4126 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004127 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004128 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004129 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004130
4131 if (Op == OO_New || Op == OO_Array_New) {
4132 bool ret = false;
4133 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4134 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4135 QualType T = Context.getCanonicalType((*Param)->getType());
4136 if (!T->isDependentType() && SizeTy != T) {
4137 Diag(FnDecl->getLocation(),
4138 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4139 << SizeTy;
4140 ret = true;
4141 }
4142 }
4143 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4144 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4145 return Diag(FnDecl->getLocation(),
4146 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004147 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004148 return ret;
4149 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004150
4151 // C++ [over.oper]p6:
4152 // An operator function shall either be a non-static member
4153 // function or be a non-member function and have at least one
4154 // parameter whose type is a class, a reference to a class, an
4155 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004156 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4157 if (MethodDecl->isStatic())
4158 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004159 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004160 } else {
4161 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004162 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4163 ParamEnd = FnDecl->param_end();
4164 Param != ParamEnd; ++Param) {
4165 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004166 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4167 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004168 ClassOrEnumParam = true;
4169 break;
4170 }
4171 }
4172
Douglas Gregord69246b2008-11-17 16:14:12 +00004173 if (!ClassOrEnumParam)
4174 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004175 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004176 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004177 }
4178
4179 // C++ [over.oper]p8:
4180 // An operator function cannot have default arguments (8.3.6),
4181 // except where explicitly stated below.
4182 //
Mike Stump11289f42009-09-09 15:08:12 +00004183 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004184 // (C++ [over.call]p1).
4185 if (Op != OO_Call) {
4186 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4187 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004188 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004189 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004190 diag::err_operator_overload_default_arg)
4191 << FnDecl->getDeclName();
4192 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004193 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004194 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004195 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004196 }
4197 }
4198
Douglas Gregor6cf08062008-11-10 13:38:07 +00004199 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4200 { false, false, false }
4201#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4202 , { Unary, Binary, MemberOnly }
4203#include "clang/Basic/OperatorKinds.def"
4204 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004205
Douglas Gregor6cf08062008-11-10 13:38:07 +00004206 bool CanBeUnaryOperator = OperatorUses[Op][0];
4207 bool CanBeBinaryOperator = OperatorUses[Op][1];
4208 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004209
4210 // C++ [over.oper]p8:
4211 // [...] Operator functions cannot have more or fewer parameters
4212 // than the number required for the corresponding operator, as
4213 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004214 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004215 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004216 if (Op != OO_Call &&
4217 ((NumParams == 1 && !CanBeUnaryOperator) ||
4218 (NumParams == 2 && !CanBeBinaryOperator) ||
4219 (NumParams < 1) || (NumParams > 2))) {
4220 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004221 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004222 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004223 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004224 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004225 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004226 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004227 assert(CanBeBinaryOperator &&
4228 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004229 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004230 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004231
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004232 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004233 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004234 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004235
Douglas Gregord69246b2008-11-17 16:14:12 +00004236 // Overloaded operators other than operator() cannot be variadic.
4237 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004238 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004239 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004240 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004241 }
4242
4243 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004244 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4245 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004246 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004247 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004248 }
4249
4250 // C++ [over.inc]p1:
4251 // The user-defined function called operator++ implements the
4252 // prefix and postfix ++ operator. If this function is a member
4253 // function with no parameters, or a non-member function with one
4254 // parameter of class or enumeration type, it defines the prefix
4255 // increment operator ++ for objects of that type. If the function
4256 // is a member function with one parameter (which shall be of type
4257 // int) or a non-member function with two parameters (the second
4258 // of which shall be of type int), it defines the postfix
4259 // increment operator ++ for objects of that type.
4260 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4261 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4262 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004263 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004264 ParamIsInt = BT->getKind() == BuiltinType::Int;
4265
Chris Lattner2b786902008-11-21 07:50:02 +00004266 if (!ParamIsInt)
4267 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004268 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004269 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004270 }
4271
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004272 // Notify the class if it got an assignment operator.
4273 if (Op == OO_Equal) {
4274 // Would have returned earlier otherwise.
4275 assert(isa<CXXMethodDecl>(FnDecl) &&
4276 "Overloaded = not member, but not filtered.");
4277 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4278 Method->getParent()->addedAssignmentOperator(Context, Method);
4279 }
4280
Douglas Gregord69246b2008-11-17 16:14:12 +00004281 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004282}
Chris Lattner3b024a32008-12-17 07:09:26 +00004283
Douglas Gregor07665a62009-01-05 19:45:36 +00004284/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4285/// linkage specification, including the language and (if present)
4286/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4287/// the location of the language string literal, which is provided
4288/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4289/// the '{' brace. Otherwise, this linkage specification does not
4290/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004291Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4292 SourceLocation ExternLoc,
4293 SourceLocation LangLoc,
4294 const char *Lang,
4295 unsigned StrSize,
4296 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004297 LinkageSpecDecl::LanguageIDs Language;
4298 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4299 Language = LinkageSpecDecl::lang_c;
4300 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4301 Language = LinkageSpecDecl::lang_cxx;
4302 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004303 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004304 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004305 }
Mike Stump11289f42009-09-09 15:08:12 +00004306
Chris Lattner438e5012008-12-17 07:13:27 +00004307 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004308
Douglas Gregor07665a62009-01-05 19:45:36 +00004309 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004310 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004311 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004312 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004313 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004314 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004315}
4316
Douglas Gregor07665a62009-01-05 19:45:36 +00004317/// ActOnFinishLinkageSpecification - Completely the definition of
4318/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4319/// valid, it's the position of the closing '}' brace in a linkage
4320/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004321Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4322 DeclPtrTy LinkageSpec,
4323 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004324 if (LinkageSpec)
4325 PopDeclContext();
4326 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004327}
4328
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004329/// \brief Perform semantic analysis for the variable declaration that
4330/// occurs within a C++ catch clause, returning the newly-created
4331/// variable.
4332VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004333 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004334 IdentifierInfo *Name,
4335 SourceLocation Loc,
4336 SourceRange Range) {
4337 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004338
4339 // Arrays and functions decay.
4340 if (ExDeclType->isArrayType())
4341 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4342 else if (ExDeclType->isFunctionType())
4343 ExDeclType = Context.getPointerType(ExDeclType);
4344
4345 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4346 // The exception-declaration shall not denote a pointer or reference to an
4347 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004348 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004349 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004350 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004351 Invalid = true;
4352 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004353
Sebastian Redl54c04d42008-12-22 19:15:10 +00004354 QualType BaseType = ExDeclType;
4355 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004356 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004357 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004358 BaseType = Ptr->getPointeeType();
4359 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004360 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004361 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004362 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004363 BaseType = Ref->getPointeeType();
4364 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004365 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004366 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004367 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004368 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004369 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004370
Mike Stump11289f42009-09-09 15:08:12 +00004371 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004372 RequireNonAbstractType(Loc, ExDeclType,
4373 diag::err_abstract_type_in_decl,
4374 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004375 Invalid = true;
4376
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004377 // FIXME: Need to test for ability to copy-construct and destroy the
4378 // exception variable.
4379
Sebastian Redl9b244a82008-12-22 21:35:02 +00004380 // FIXME: Need to check for abstract classes.
4381
Mike Stump11289f42009-09-09 15:08:12 +00004382 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004383 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004384
4385 if (Invalid)
4386 ExDecl->setInvalidDecl();
4387
4388 return ExDecl;
4389}
4390
4391/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4392/// handler.
4393Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004394 DeclaratorInfo *DInfo = 0;
4395 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004396
4397 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004398 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004399 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004400 // The scope should be freshly made just for us. There is just no way
4401 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004402 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004403 if (PrevDecl->isTemplateParameter()) {
4404 // Maybe we will complain about the shadowed template parameter.
4405 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004406 }
4407 }
4408
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004409 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004410 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4411 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004412 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004413 }
4414
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004415 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004416 D.getIdentifier(),
4417 D.getIdentifierLoc(),
4418 D.getDeclSpec().getSourceRange());
4419
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004420 if (Invalid)
4421 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004422
Sebastian Redl54c04d42008-12-22 19:15:10 +00004423 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004424 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004425 PushOnScopeChains(ExDecl, S);
4426 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004427 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004428
Douglas Gregor758a8692009-06-17 21:51:59 +00004429 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004430 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004431}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004432
Mike Stump11289f42009-09-09 15:08:12 +00004433Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004434 ExprArg assertexpr,
4435 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004436 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004437 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004438 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4439
Anders Carlsson54b26982009-03-14 00:33:21 +00004440 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4441 llvm::APSInt Value(32);
4442 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4443 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4444 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004445 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004446 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004447
Anders Carlsson54b26982009-03-14 00:33:21 +00004448 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004449 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004450 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004451 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004452 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004453 }
4454 }
Mike Stump11289f42009-09-09 15:08:12 +00004455
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004456 assertexpr.release();
4457 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004458 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004459 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004460
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004461 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004462 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004463}
Sebastian Redlf769df52009-03-24 22:27:57 +00004464
John McCall11083da2009-09-16 22:47:08 +00004465/// Handle a friend type declaration. This works in tandem with
4466/// ActOnTag.
4467///
4468/// Notes on friend class templates:
4469///
4470/// We generally treat friend class declarations as if they were
4471/// declaring a class. So, for example, the elaborated type specifier
4472/// in a friend declaration is required to obey the restrictions of a
4473/// class-head (i.e. no typedefs in the scope chain), template
4474/// parameters are required to match up with simple template-ids, &c.
4475/// However, unlike when declaring a template specialization, it's
4476/// okay to refer to a template specialization without an empty
4477/// template parameter declaration, e.g.
4478/// friend class A<T>::B<unsigned>;
4479/// We permit this as a special case; if there are any template
4480/// parameters present at all, require proper matching, i.e.
4481/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004482Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004483 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004484 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004485
4486 assert(DS.isFriendSpecified());
4487 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4488
John McCall11083da2009-09-16 22:47:08 +00004489 // Try to convert the decl specifier to a type. This works for
4490 // friend templates because ActOnTag never produces a ClassTemplateDecl
4491 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004492 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004493 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4494 if (TheDeclarator.isInvalidType())
4495 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004496
John McCall11083da2009-09-16 22:47:08 +00004497 // This is definitely an error in C++98. It's probably meant to
4498 // be forbidden in C++0x, too, but the specification is just
4499 // poorly written.
4500 //
4501 // The problem is with declarations like the following:
4502 // template <T> friend A<T>::foo;
4503 // where deciding whether a class C is a friend or not now hinges
4504 // on whether there exists an instantiation of A that causes
4505 // 'foo' to equal C. There are restrictions on class-heads
4506 // (which we declare (by fiat) elaborated friend declarations to
4507 // be) that makes this tractable.
4508 //
4509 // FIXME: handle "template <> friend class A<T>;", which
4510 // is possibly well-formed? Who even knows?
4511 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4512 Diag(Loc, diag::err_tagless_friend_type_template)
4513 << DS.getSourceRange();
4514 return DeclPtrTy();
4515 }
4516
John McCallaa74a0c2009-08-28 07:59:38 +00004517 // C++ [class.friend]p2:
4518 // An elaborated-type-specifier shall be used in a friend declaration
4519 // for a class.*
4520 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004521 // This is one of the rare places in Clang where it's legitimate to
4522 // ask about the "spelling" of the type.
4523 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4524 // If we evaluated the type to a record type, suggest putting
4525 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004526 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004527 RecordDecl *RD = RT->getDecl();
4528
4529 std::string InsertionText = std::string(" ") + RD->getKindName();
4530
John McCallc3987482009-10-07 23:34:25 +00004531 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4532 << (unsigned) RD->getTagKind()
4533 << T
4534 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004535 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4536 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004537 return DeclPtrTy();
4538 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004539 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4540 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004541 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004542 }
4543 }
4544
John McCallc3987482009-10-07 23:34:25 +00004545 // Enum types cannot be friends.
4546 if (T->getAs<EnumType>()) {
4547 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4548 << SourceRange(DS.getFriendSpecLoc());
4549 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004550 }
John McCallaa74a0c2009-08-28 07:59:38 +00004551
John McCallaa74a0c2009-08-28 07:59:38 +00004552 // C++98 [class.friend]p1: A friend of a class is a function
4553 // or class that is not a member of the class . . .
4554 // But that's a silly restriction which nobody implements for
4555 // inner classes, and C++0x removes it anyway, so we only report
4556 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004557 if (!getLangOptions().CPlusPlus0x)
4558 if (const RecordType *RT = T->getAs<RecordType>())
4559 if (RT->getDecl()->getDeclContext() == CurContext)
4560 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004561
John McCall11083da2009-09-16 22:47:08 +00004562 Decl *D;
4563 if (TempParams.size())
4564 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4565 TempParams.size(),
4566 (TemplateParameterList**) TempParams.release(),
4567 T.getTypePtr(),
4568 DS.getFriendSpecLoc());
4569 else
4570 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4571 DS.getFriendSpecLoc());
4572 D->setAccess(AS_public);
4573 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004574
John McCall11083da2009-09-16 22:47:08 +00004575 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004576}
4577
John McCall2f212b32009-09-11 21:02:39 +00004578Sema::DeclPtrTy
4579Sema::ActOnFriendFunctionDecl(Scope *S,
4580 Declarator &D,
4581 bool IsDefinition,
4582 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004583 const DeclSpec &DS = D.getDeclSpec();
4584
4585 assert(DS.isFriendSpecified());
4586 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4587
4588 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004589 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004590 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004591
4592 // C++ [class.friend]p1
4593 // A friend of a class is a function or class....
4594 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004595 // It *doesn't* see through dependent types, which is correct
4596 // according to [temp.arg.type]p3:
4597 // If a declaration acquires a function type through a
4598 // type dependent on a template-parameter and this causes
4599 // a declaration that does not use the syntactic form of a
4600 // function declarator to have a function type, the program
4601 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004602 if (!T->isFunctionType()) {
4603 Diag(Loc, diag::err_unexpected_friend);
4604
4605 // It might be worthwhile to try to recover by creating an
4606 // appropriate declaration.
4607 return DeclPtrTy();
4608 }
4609
4610 // C++ [namespace.memdef]p3
4611 // - If a friend declaration in a non-local class first declares a
4612 // class or function, the friend class or function is a member
4613 // of the innermost enclosing namespace.
4614 // - The name of the friend is not found by simple name lookup
4615 // until a matching declaration is provided in that namespace
4616 // scope (either before or after the class declaration granting
4617 // friendship).
4618 // - If a friend function is called, its name may be found by the
4619 // name lookup that considers functions from namespaces and
4620 // classes associated with the types of the function arguments.
4621 // - When looking for a prior declaration of a class or a function
4622 // declared as a friend, scopes outside the innermost enclosing
4623 // namespace scope are not considered.
4624
John McCallaa74a0c2009-08-28 07:59:38 +00004625 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4626 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004627 assert(Name);
4628
John McCall07e91c02009-08-06 02:15:43 +00004629 // The context we found the declaration in, or in which we should
4630 // create the declaration.
4631 DeclContext *DC;
4632
4633 // FIXME: handle local classes
4634
4635 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00004636 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4637 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00004638 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004639 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004640 DC = computeDeclContext(ScopeQual);
4641
4642 // FIXME: handle dependent contexts
4643 if (!DC) return DeclPtrTy();
4644
John McCall1f82f242009-11-18 22:49:29 +00004645 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004646
4647 // If searching in that context implicitly found a declaration in
4648 // a different context, treat it like it wasn't found at all.
4649 // TODO: better diagnostics for this case. Suggesting the right
4650 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00004651 // FIXME: getRepresentativeDecl() is not right here at all
4652 if (Previous.empty() ||
4653 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004654 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004655 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4656 return DeclPtrTy();
4657 }
4658
4659 // C++ [class.friend]p1: A friend of a class is a function or
4660 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004661 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004662 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4663
John McCall07e91c02009-08-06 02:15:43 +00004664 // Otherwise walk out to the nearest namespace scope looking for matches.
4665 } else {
4666 // TODO: handle local class contexts.
4667
4668 DC = CurContext;
4669 while (true) {
4670 // Skip class contexts. If someone can cite chapter and verse
4671 // for this behavior, that would be nice --- it's what GCC and
4672 // EDG do, and it seems like a reasonable intent, but the spec
4673 // really only says that checks for unqualified existing
4674 // declarations should stop at the nearest enclosing namespace,
4675 // not that they should only consider the nearest enclosing
4676 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004677 while (DC->isRecord())
4678 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004679
John McCall1f82f242009-11-18 22:49:29 +00004680 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004681
4682 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00004683 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00004684 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004685
John McCall07e91c02009-08-06 02:15:43 +00004686 if (DC->isFileContext()) break;
4687 DC = DC->getParent();
4688 }
4689
4690 // C++ [class.friend]p1: A friend of a class is a function or
4691 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004692 // C++0x changes this for both friend types and functions.
4693 // Most C++ 98 compilers do seem to give an error here, so
4694 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00004695 if (!Previous.empty() && DC->Equals(CurContext)
4696 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004697 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4698 }
4699
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004700 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004701 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004702 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4703 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4704 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004705 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004706 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4707 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004708 return DeclPtrTy();
4709 }
John McCall07e91c02009-08-06 02:15:43 +00004710 }
4711
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004712 bool Redeclaration = false;
John McCall1f82f242009-11-18 22:49:29 +00004713 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004714 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004715 IsDefinition,
4716 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004717 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004718
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004719 assert(ND->getDeclContext() == DC);
4720 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004721
John McCall759e32b2009-08-31 22:39:49 +00004722 // Add the function declaration to the appropriate lookup tables,
4723 // adjusting the redeclarations list as necessary. We don't
4724 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004725 //
John McCall759e32b2009-08-31 22:39:49 +00004726 // Also update the scope-based lookup if the target context's
4727 // lookup context is in lexical scope.
4728 if (!CurContext->isDependentContext()) {
4729 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004730 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004731 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004732 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004733 }
John McCallaa74a0c2009-08-28 07:59:38 +00004734
4735 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004736 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004737 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004738 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004739 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004740
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004741 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004742}
4743
Chris Lattner83f095c2009-03-28 19:18:32 +00004744void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004745 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004746
Chris Lattner83f095c2009-03-28 19:18:32 +00004747 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004748 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4749 if (!Fn) {
4750 Diag(DelLoc, diag::err_deleted_non_function);
4751 return;
4752 }
4753 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4754 Diag(DelLoc, diag::err_deleted_decl_not_first);
4755 Diag(Prev->getLocation(), diag::note_previous_declaration);
4756 // If the declaration wasn't the first, we delete the function anyway for
4757 // recovery.
4758 }
4759 Fn->setDeleted();
4760}
Sebastian Redl4c018662009-04-27 21:33:24 +00004761
4762static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4763 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4764 ++CI) {
4765 Stmt *SubStmt = *CI;
4766 if (!SubStmt)
4767 continue;
4768 if (isa<ReturnStmt>(SubStmt))
4769 Self.Diag(SubStmt->getSourceRange().getBegin(),
4770 diag::err_return_in_constructor_handler);
4771 if (!isa<Expr>(SubStmt))
4772 SearchForReturnInStmt(Self, SubStmt);
4773 }
4774}
4775
4776void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4777 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4778 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4779 SearchForReturnInStmt(*this, Handler);
4780 }
4781}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004782
Mike Stump11289f42009-09-09 15:08:12 +00004783bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004784 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004785 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4786 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004787
4788 QualType CNewTy = Context.getCanonicalType(NewTy);
4789 QualType COldTy = Context.getCanonicalType(OldTy);
4790
Mike Stump11289f42009-09-09 15:08:12 +00004791 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004792 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004793 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004794
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004795 // Check if the return types are covariant
4796 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004797
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004798 /// Both types must be pointers or references to classes.
4799 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4800 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4801 NewClassTy = NewPT->getPointeeType();
4802 OldClassTy = OldPT->getPointeeType();
4803 }
4804 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4805 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4806 NewClassTy = NewRT->getPointeeType();
4807 OldClassTy = OldRT->getPointeeType();
4808 }
4809 }
Mike Stump11289f42009-09-09 15:08:12 +00004810
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004811 // The return types aren't either both pointers or references to a class type.
4812 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004813 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004814 diag::err_different_return_type_for_overriding_virtual_function)
4815 << New->getDeclName() << NewTy << OldTy;
4816 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004817
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004818 return true;
4819 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004820
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004821 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004822 // Check if the new class derives from the old class.
4823 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4824 Diag(New->getLocation(),
4825 diag::err_covariant_return_not_derived)
4826 << New->getDeclName() << NewTy << OldTy;
4827 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4828 return true;
4829 }
Mike Stump11289f42009-09-09 15:08:12 +00004830
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004831 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004832 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004833 diag::err_covariant_return_inaccessible_base,
4834 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4835 // FIXME: Should this point to the return type?
4836 New->getLocation(), SourceRange(), New->getDeclName())) {
4837 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4838 return true;
4839 }
4840 }
Mike Stump11289f42009-09-09 15:08:12 +00004841
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004842 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004843 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004844 Diag(New->getLocation(),
4845 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004846 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004847 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4848 return true;
4849 };
Mike Stump11289f42009-09-09 15:08:12 +00004850
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004851
4852 // The new class type must have the same or less qualifiers as the old type.
4853 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4854 Diag(New->getLocation(),
4855 diag::err_covariant_return_type_class_type_more_qualified)
4856 << New->getDeclName() << NewTy << OldTy;
4857 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4858 return true;
4859 };
Mike Stump11289f42009-09-09 15:08:12 +00004860
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004861 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004862}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004863
Alexis Hunt96d5c762009-11-21 08:43:09 +00004864bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4865 const CXXMethodDecl *Old)
4866{
4867 if (Old->hasAttr<FinalAttr>()) {
4868 Diag(New->getLocation(), diag::err_final_function_overridden)
4869 << New->getDeclName();
4870 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4871 return true;
4872 }
4873
4874 return false;
4875}
4876
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004877/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4878/// initializer for the declaration 'Dcl'.
4879/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4880/// static data member of class X, names should be looked up in the scope of
4881/// class X.
4882void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004883 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004884
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004885 Decl *D = Dcl.getAs<Decl>();
4886 // If there is no declaration, there was an error parsing it.
4887 if (D == 0)
4888 return;
4889
4890 // Check whether it is a declaration with a nested name specifier like
4891 // int foo::bar;
4892 if (!D->isOutOfLine())
4893 return;
Mike Stump11289f42009-09-09 15:08:12 +00004894
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004895 // C++ [basic.lookup.unqual]p13
4896 //
4897 // A name used in the definition of a static data member of class X
4898 // (after the qualified-id of the static member) is looked up as if the name
4899 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004900
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004901 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004902 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004903}
4904
4905/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4906/// initializer for the declaration 'Dcl'.
4907void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004908 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004909
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004910 Decl *D = Dcl.getAs<Decl>();
4911 // If there is no declaration, there was an error parsing it.
4912 if (D == 0)
4913 return;
4914
4915 // Check whether it is a declaration with a nested name specifier like
4916 // int foo::bar;
4917 if (!D->isOutOfLine())
4918 return;
4919
4920 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004921 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004922}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00004923
4924/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
4925/// C++ if/switch/while/for statement.
4926/// e.g: "if (int x = f()) {...}"
4927Action::DeclResult
4928Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
4929 // C++ 6.4p2:
4930 // The declarator shall not specify a function or an array.
4931 // The type-specifier-seq shall not contain typedef and shall not declare a
4932 // new class or enumeration.
4933 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4934 "Parser allowed 'typedef' as storage class of condition decl.");
4935
4936 DeclaratorInfo *DInfo = 0;
4937 TagDecl *OwnedTag = 0;
4938 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
4939
4940 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
4941 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
4942 // would be created and CXXConditionDeclExpr wants a VarDecl.
4943 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
4944 << D.getSourceRange();
4945 return DeclResult();
4946 } else if (OwnedTag && OwnedTag->isDefinition()) {
4947 // The type-specifier-seq shall not declare a new class or enumeration.
4948 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
4949 }
4950
4951 DeclPtrTy Dcl = ActOnDeclarator(S, D);
4952 if (!Dcl)
4953 return DeclResult();
4954
4955 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
4956 VD->setDeclaredInCondition(true);
4957 return Dcl;
4958}