blob: 2df172e76e7231b1a70d834e20ddd254fec2bb50 [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"
Anders Carlssonf98849e2009-12-02 17:15:43 +000018#include "clang/AST/RecordLayout.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000021#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000022#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000026#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000028#include "llvm/ADT/STLExtras.h"
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.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000044 class 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");
Eli Friedman89c038e2009-12-05 23:03:49 +0000487
Alexis Hunt96d5c762009-11-21 08:43:09 +0000488 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
489 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
490 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000491 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
492 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000493 return 0;
494 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000495
Eli Friedman89c038e2009-12-05 23:03:49 +0000496 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000497
498 // Create the base specifier.
499 // FIXME: Allocate via ASTContext?
500 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
501 Class->getTagKind() == RecordDecl::TK_class,
502 Access, BaseType);
503}
504
505void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
506 const CXXRecordDecl *BaseClass,
507 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000508 // A class with a non-empty base class is not empty.
509 // FIXME: Standard ref?
510 if (!BaseClass->isEmpty())
511 Class->setEmpty(false);
512
513 // C++ [class.virtual]p1:
514 // A class that [...] inherits a virtual function is called a polymorphic
515 // class.
516 if (BaseClass->isPolymorphic())
517 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000518
Douglas Gregor463421d2009-03-03 04:44:36 +0000519 // C++ [dcl.init.aggr]p1:
520 // An aggregate is [...] a class with [...] no base classes [...].
521 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000522
523 // C++ [class]p4:
524 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000525 Class->setPOD(false);
526
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000527 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000528 // C++ [class.ctor]p5:
529 // A constructor is trivial if its class has no virtual base classes.
530 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000531
532 // C++ [class.copy]p6:
533 // A copy constructor is trivial if its class has no virtual base classes.
534 Class->setHasTrivialCopyConstructor(false);
535
536 // C++ [class.copy]p11:
537 // A copy assignment operator is trivial if its class has no virtual
538 // base classes.
539 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000540
541 // C++0x [meta.unary.prop] is_empty:
542 // T is a class type, but not a union type, with ... no virtual base
543 // classes
544 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000545 } else {
546 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000547 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000548 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000549 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000550 Class->setHasTrivialConstructor(false);
551
552 // C++ [class.copy]p6:
553 // A copy constructor is trivial if all the direct base classes of its
554 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000555 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000556 Class->setHasTrivialCopyConstructor(false);
557
558 // C++ [class.copy]p11:
559 // A copy assignment operator is trivial if all the direct base classes
560 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000561 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000562 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000563 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000564
565 // C++ [class.ctor]p3:
566 // A destructor is trivial if all the direct base classes of its class
567 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000568 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000569 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000570}
571
Douglas Gregor556877c2008-04-13 21:30:24 +0000572/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
573/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000574/// example:
575/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000576/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000577Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000578Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000579 bool Virtual, AccessSpecifier Access,
580 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000581 if (!classdecl)
582 return true;
583
Douglas Gregorc40290e2009-03-09 23:48:35 +0000584 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000585 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000586 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000587 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
588 Virtual, Access,
589 BaseType, BaseLoc))
590 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000591
Douglas Gregor463421d2009-03-03 04:44:36 +0000592 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000593}
Douglas Gregor556877c2008-04-13 21:30:24 +0000594
Douglas Gregor463421d2009-03-03 04:44:36 +0000595/// \brief Performs the actual work of attaching the given base class
596/// specifiers to a C++ class.
597bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
598 unsigned NumBases) {
599 if (NumBases == 0)
600 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000601
602 // Used to keep track of which base types we have already seen, so
603 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000604 // that the key is always the unqualified canonical type of the base
605 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000606 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
607
608 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000609 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000610 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000611 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000612 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000613 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000614 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000615
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 if (KnownBaseTypes[NewBaseType]) {
617 // C++ [class.mi]p3:
618 // A class shall not be specified as a direct base class of a
619 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000620 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000621 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000622 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000623 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000624
625 // Delete the duplicate base class specifier; we're going to
626 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000627 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000628
629 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000630 } else {
631 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000632 KnownBaseTypes[NewBaseType] = Bases[idx];
633 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000634 }
635 }
636
637 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000638 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000639
640 // Delete the remaining (good) base class specifiers, since their
641 // data has been copied into the CXXRecordDecl.
642 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000643 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000644
645 return Invalid;
646}
647
648/// ActOnBaseSpecifiers - Attach the given base specifiers to the
649/// class, after checking whether there are any duplicate base
650/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000651void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000652 unsigned NumBases) {
653 if (!ClassDecl || !Bases || !NumBases)
654 return;
655
656 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000657 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000658 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000659}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000660
Douglas Gregor36d1b142009-10-06 17:59:45 +0000661/// \brief Determine whether the type \p Derived is a C++ class that is
662/// derived from the type \p Base.
663bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
664 if (!getLangOptions().CPlusPlus)
665 return false;
666
667 const RecordType *DerivedRT = Derived->getAs<RecordType>();
668 if (!DerivedRT)
669 return false;
670
671 const RecordType *BaseRT = Base->getAs<RecordType>();
672 if (!BaseRT)
673 return false;
674
675 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
676 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
677 return DerivedRD->isDerivedFrom(BaseRD);
678}
679
680/// \brief Determine whether the type \p Derived is a C++ class that is
681/// derived from the type \p Base.
682bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
683 if (!getLangOptions().CPlusPlus)
684 return false;
685
686 const RecordType *DerivedRT = Derived->getAs<RecordType>();
687 if (!DerivedRT)
688 return false;
689
690 const RecordType *BaseRT = Base->getAs<RecordType>();
691 if (!BaseRT)
692 return false;
693
694 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
695 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
696 return DerivedRD->isDerivedFrom(BaseRD, Paths);
697}
698
699/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
700/// conversion (where Derived and Base are class types) is
701/// well-formed, meaning that the conversion is unambiguous (and
702/// that all of the base classes are accessible). Returns true
703/// and emits a diagnostic if the code is ill-formed, returns false
704/// otherwise. Loc is the location where this routine should point to
705/// if there is an error, and Range is the source range to highlight
706/// if there is an error.
707bool
708Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
709 unsigned InaccessibleBaseID,
710 unsigned AmbigiousBaseConvID,
711 SourceLocation Loc, SourceRange Range,
712 DeclarationName Name) {
713 // First, determine whether the path from Derived to Base is
714 // ambiguous. This is slightly more expensive than checking whether
715 // the Derived to Base conversion exists, because here we need to
716 // explore multiple paths to determine if there is an ambiguity.
717 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
718 /*DetectVirtual=*/false);
719 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
720 assert(DerivationOkay &&
721 "Can only be used with a derived-to-base conversion");
722 (void)DerivationOkay;
723
724 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000725 if (InaccessibleBaseID == 0)
726 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000727 // Check that the base class can be accessed.
728 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
729 Name);
730 }
731
732 // We know that the derived-to-base conversion is ambiguous, and
733 // we're going to produce a diagnostic. Perform the derived-to-base
734 // search just one more time to compute all of the possible paths so
735 // that we can print them out. This is more expensive than any of
736 // the previous derived-to-base checks we've done, but at this point
737 // performance isn't as much of an issue.
738 Paths.clear();
739 Paths.setRecordingPaths(true);
740 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
741 assert(StillOkay && "Can only be used with a derived-to-base conversion");
742 (void)StillOkay;
743
744 // Build up a textual representation of the ambiguous paths, e.g.,
745 // D -> B -> A, that will be used to illustrate the ambiguous
746 // conversions in the diagnostic. We only print one of the paths
747 // to each base class subobject.
748 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
749
750 Diag(Loc, AmbigiousBaseConvID)
751 << Derived << Base << PathDisplayStr << Range << Name;
752 return true;
753}
754
755bool
756Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000757 SourceLocation Loc, SourceRange Range,
758 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000759 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000760 IgnoreAccess ? 0 :
761 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000762 diag::err_ambiguous_derived_to_base_conv,
763 Loc, Range, DeclarationName());
764}
765
766
767/// @brief Builds a string representing ambiguous paths from a
768/// specific derived class to different subobjects of the same base
769/// class.
770///
771/// This function builds a string that can be used in error messages
772/// to show the different paths that one can take through the
773/// inheritance hierarchy to go from the derived class to different
774/// subobjects of a base class. The result looks something like this:
775/// @code
776/// struct D -> struct B -> struct A
777/// struct D -> struct C -> struct A
778/// @endcode
779std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
780 std::string PathDisplayStr;
781 std::set<unsigned> DisplayedPaths;
782 for (CXXBasePaths::paths_iterator Path = Paths.begin();
783 Path != Paths.end(); ++Path) {
784 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
785 // We haven't displayed a path to this particular base
786 // class subobject yet.
787 PathDisplayStr += "\n ";
788 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
789 for (CXXBasePath::const_iterator Element = Path->begin();
790 Element != Path->end(); ++Element)
791 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
792 }
793 }
794
795 return PathDisplayStr;
796}
797
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000798//===----------------------------------------------------------------------===//
799// C++ class member Handling
800//===----------------------------------------------------------------------===//
801
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000802/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
803/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
804/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000805/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000806Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000807Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000808 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000809 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
810 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000811 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000812 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000813 Expr *BitWidth = static_cast<Expr*>(BW);
814 Expr *Init = static_cast<Expr*>(InitExpr);
815 SourceLocation Loc = D.getIdentifierLoc();
816
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000817 bool isFunc = D.isFunctionDeclarator();
818
John McCall07e91c02009-08-06 02:15:43 +0000819 assert(!DS.isFriendSpecified());
820
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000821 // C++ 9.2p6: A member shall not be declared to have automatic storage
822 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000823 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
824 // data members and cannot be applied to names declared const or static,
825 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000826 switch (DS.getStorageClassSpec()) {
827 case DeclSpec::SCS_unspecified:
828 case DeclSpec::SCS_typedef:
829 case DeclSpec::SCS_static:
830 // FALL THROUGH.
831 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000832 case DeclSpec::SCS_mutable:
833 if (isFunc) {
834 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000835 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000836 else
Chris Lattner3b054132008-11-19 05:08:23 +0000837 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Sebastian Redl8071edb2008-11-17 23:24:37 +0000839 // FIXME: It would be nicer if the keyword was ignored only for this
840 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000841 D.getMutableDeclSpec().ClearStorageClassSpecs();
842 } else {
843 QualType T = GetTypeForDeclarator(D, S);
844 diag::kind err = static_cast<diag::kind>(0);
845 if (T->isReferenceType())
846 err = diag::err_mutable_reference;
847 else if (T.isConstQualified())
848 err = diag::err_mutable_const;
849 if (err != 0) {
850 if (DS.getStorageClassSpecLoc().isValid())
851 Diag(DS.getStorageClassSpecLoc(), err);
852 else
853 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000854 // FIXME: It would be nicer if the keyword was ignored only for this
855 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000856 D.getMutableDeclSpec().ClearStorageClassSpecs();
857 }
858 }
859 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000860 default:
861 if (DS.getStorageClassSpecLoc().isValid())
862 Diag(DS.getStorageClassSpecLoc(),
863 diag::err_storageclass_invalid_for_member);
864 else
865 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
866 D.getMutableDeclSpec().ClearStorageClassSpecs();
867 }
868
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000869 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000870 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000871 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000872 // Check also for this case:
873 //
874 // typedef int f();
875 // f a;
876 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000877 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000878 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000879 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000880
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000881 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
882 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000883 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000884
885 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000886 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000887 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000888 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
889 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000890 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000891 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000892 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000893 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000894 if (!Member) {
895 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000896 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000897 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000898
899 // Non-instance-fields can't have a bitfield.
900 if (BitWidth) {
901 if (Member->isInvalidDecl()) {
902 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000903 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000904 // C++ 9.6p3: A bit-field shall not be a static member.
905 // "static member 'A' cannot be a bit-field"
906 Diag(Loc, diag::err_static_not_bitfield)
907 << Name << BitWidth->getSourceRange();
908 } else if (isa<TypedefDecl>(Member)) {
909 // "typedef member 'x' cannot be a bit-field"
910 Diag(Loc, diag::err_typedef_not_bitfield)
911 << Name << BitWidth->getSourceRange();
912 } else {
913 // A function typedef ("typedef int f(); f a;").
914 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
915 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000916 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000917 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
Chris Lattnerd26760a2009-03-05 23:01:03 +0000920 DeleteExpr(BitWidth);
921 BitWidth = 0;
922 Member->setInvalidDecl();
923 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000924
925 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000926
Douglas Gregor3447e762009-08-20 22:52:58 +0000927 // If we have declared a member function template, set the access of the
928 // templated declaration as well.
929 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
930 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000931 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000932
Douglas Gregor92751d42008-11-17 22:58:34 +0000933 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000934
Douglas Gregor0c880302009-03-11 23:00:04 +0000935 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000936 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000937 if (Deleted) // FIXME: Source location is not very good.
938 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000939
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000940 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000941 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000942 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000943 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000944 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000945}
946
Douglas Gregore8381c02008-11-05 04:29:56 +0000947/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000948Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000949Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000950 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000951 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000952 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000953 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000954 SourceLocation IdLoc,
955 SourceLocation LParenLoc,
956 ExprTy **Args, unsigned NumArgs,
957 SourceLocation *CommaLocs,
958 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000959 if (!ConstructorD)
960 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000961
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000962 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000963
964 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000965 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000966 if (!Constructor) {
967 // The user wrote a constructor initializer on a function that is
968 // not a C++ constructor. Ignore the error for now, because we may
969 // have more member initializers coming; we'll diagnose it just
970 // once in ActOnMemInitializers.
971 return true;
972 }
973
974 CXXRecordDecl *ClassDecl = Constructor->getParent();
975
976 // C++ [class.base.init]p2:
977 // Names in a mem-initializer-id are looked up in the scope of the
978 // constructor’s class and, if not found in that scope, are looked
979 // up in the scope containing the constructor’s
980 // definition. [Note: if the constructor’s class contains a member
981 // with the same name as a direct or virtual base class of the
982 // class, a mem-initializer-id naming the member or base class and
983 // composed of a single identifier refers to the class member. A
984 // mem-initializer-id for the hidden base class may be specified
985 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000986 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000987 // Look for a member, first.
988 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000989 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000990 = ClassDecl->lookup(MemberOrBase);
991 if (Result.first != Result.second)
992 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000993
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000994 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000995
Eli Friedman8e1433b2009-07-29 19:44:27 +0000996 if (Member)
997 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000998 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000999 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001000 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001001 QualType BaseType;
1002
John McCallbcd03502009-12-07 02:54:59 +00001003 TypeSourceInfo *TInfo = 0;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001004 if (TemplateTypeTy)
John McCallbcd03502009-12-07 02:54:59 +00001005 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001006 else
1007 BaseType = QualType::getFromOpaquePtr(getTypeName(*MemberOrBase, IdLoc,
1008 S, &SS));
1009 if (BaseType.isNull())
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001010 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1011 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001012
John McCallbcd03502009-12-07 02:54:59 +00001013 if (!TInfo)
1014 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001015
John McCallbcd03502009-12-07 02:54:59 +00001016 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001017 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001018}
1019
John McCalle22a04a2009-11-04 23:02:40 +00001020/// Checks an initializer expression for use of uninitialized fields, such as
1021/// containing the field that is being initialized. Returns true if there is an
1022/// uninitialized field was used an updates the SourceLocation parameter; false
1023/// otherwise.
1024static bool InitExprContainsUninitializedFields(const Stmt* S,
1025 const FieldDecl* LhsField,
1026 SourceLocation* L) {
1027 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1028 if (ME) {
1029 const NamedDecl* RhsField = ME->getMemberDecl();
1030 if (RhsField == LhsField) {
1031 // Initializing a field with itself. Throw a warning.
1032 // But wait; there are exceptions!
1033 // Exception #1: The field may not belong to this record.
1034 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1035 const Expr* base = ME->getBase();
1036 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1037 // Even though the field matches, it does not belong to this record.
1038 return false;
1039 }
1040 // None of the exceptions triggered; return true to indicate an
1041 // uninitialized field was used.
1042 *L = ME->getMemberLoc();
1043 return true;
1044 }
1045 }
1046 bool found = false;
1047 for (Stmt::const_child_iterator it = S->child_begin();
1048 it != S->child_end() && found == false;
1049 ++it) {
1050 if (isa<CallExpr>(S)) {
1051 // Do not descend into function calls or constructors, as the use
1052 // of an uninitialized field may be valid. One would have to inspect
1053 // the contents of the function/ctor to determine if it is safe or not.
1054 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1055 // may be safe, depending on what the function/ctor does.
1056 continue;
1057 }
1058 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1059 }
1060 return found;
1061}
1062
Eli Friedman8e1433b2009-07-29 19:44:27 +00001063Sema::MemInitResult
1064Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1065 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001066 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001067 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001068 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1069 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1070 ExprTemporaries.clear();
1071
John McCalle22a04a2009-11-04 23:02:40 +00001072 // Diagnose value-uses of fields to initialize themselves, e.g.
1073 // foo(foo)
1074 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001075 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001076 for (unsigned i = 0; i < NumArgs; ++i) {
1077 SourceLocation L;
1078 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1079 // FIXME: Return true in the case when other fields are used before being
1080 // uninitialized. For example, let this field be the i'th field. When
1081 // initializing the i'th field, throw a warning if any of the >= i'th
1082 // fields are used, as they are not yet initialized.
1083 // Right now we are only handling the case where the i'th field uses
1084 // itself in its initializer.
1085 Diag(L, diag::warn_field_is_uninit);
1086 }
1087 }
1088
Eli Friedman8e1433b2009-07-29 19:44:27 +00001089 bool HasDependentArg = false;
1090 for (unsigned i = 0; i < NumArgs; i++)
1091 HasDependentArg |= Args[i]->isTypeDependent();
1092
1093 CXXConstructorDecl *C = 0;
1094 QualType FieldType = Member->getType();
1095 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1096 FieldType = Array->getElementType();
1097 if (FieldType->isDependentType()) {
1098 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001099 } else if (FieldType->isRecordType()) {
1100 // Member is a record (struct/union/class), so pass the initializer
1101 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001102 if (!HasDependentArg) {
1103 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1104
1105 C = PerformInitializationByConstructor(FieldType,
1106 MultiExprArg(*this,
1107 (void**)Args,
1108 NumArgs),
1109 IdLoc,
1110 SourceRange(IdLoc, RParenLoc),
1111 Member->getDeclName(), IK_Direct,
1112 ConstructorArgs);
1113
1114 if (C) {
1115 // Take over the constructor arguments as our own.
1116 NumArgs = ConstructorArgs.size();
1117 Args = (Expr **)ConstructorArgs.take();
1118 }
1119 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001120 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001121 // The member type is not a record type (or an array of record
1122 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001123 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001124 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1125 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001126 Expr *NewExp;
1127 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001128 if (FieldType->isReferenceType()) {
1129 Diag(IdLoc, diag::err_null_intialized_reference_member)
1130 << Member->getDeclName();
1131 return Diag(Member->getLocation(), diag::note_declared_at);
1132 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001133 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1134 NumArgs = 1;
1135 }
1136 else
1137 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001138 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1139 return true;
1140 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001141 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001142
1143 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1144 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1145 ExprTemporaries.clear();
1146
Eli Friedman8e1433b2009-07-29 19:44:27 +00001147 // FIXME: Perform direct initialization of the member.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001148 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1149 C, LParenLoc, (Expr **)Args,
1150 NumArgs, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001151}
1152
1153Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001154Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001155 Expr **Args, unsigned NumArgs,
1156 SourceLocation LParenLoc, SourceLocation RParenLoc,
1157 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001158 bool HasDependentArg = false;
1159 for (unsigned i = 0; i < NumArgs; i++)
1160 HasDependentArg |= Args[i]->isTypeDependent();
1161
John McCallbcd03502009-12-07 02:54:59 +00001162 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001163 if (!BaseType->isDependentType()) {
1164 if (!BaseType->isRecordType())
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001165 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCallbcd03502009-12-07 02:54:59 +00001166 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001167
1168 // C++ [class.base.init]p2:
1169 // [...] Unless the mem-initializer-id names a nonstatic data
1170 // member of the constructor’s class or a direct or virtual base
1171 // of that class, the mem-initializer is ill-formed. A
1172 // mem-initializer-list can initialize a base class using any
1173 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001174
Eli Friedman8e1433b2009-07-29 19:44:27 +00001175 // First, check for a direct base class.
1176 const CXXBaseSpecifier *DirectBaseSpec = 0;
1177 for (CXXRecordDecl::base_class_const_iterator Base =
1178 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001179 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001180 // We found a direct base of this type. That's what we're
1181 // initializing.
1182 DirectBaseSpec = &*Base;
1183 break;
1184 }
1185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186
Eli Friedman8e1433b2009-07-29 19:44:27 +00001187 // Check for a virtual base class.
1188 // FIXME: We might be able to short-circuit this if we know in advance that
1189 // there are no virtual bases.
1190 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1191 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1192 // We haven't found a base yet; search the class hierarchy for a
1193 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001194 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1195 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001196 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001197 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001198 Path != Paths.end(); ++Path) {
1199 if (Path->back().Base->isVirtual()) {
1200 VirtualBaseSpec = Path->back().Base;
1201 break;
1202 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001203 }
1204 }
1205 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001206
1207 // C++ [base.class.init]p2:
1208 // If a mem-initializer-id is ambiguous because it designates both
1209 // a direct non-virtual base class and an inherited virtual base
1210 // class, the mem-initializer is ill-formed.
1211 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001212 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCallbcd03502009-12-07 02:54:59 +00001213 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001214 // C++ [base.class.init]p2:
1215 // Unless the mem-initializer-id names a nonstatic data membeer of the
1216 // constructor's class ot a direst or virtual base of that class, the
1217 // mem-initializer is ill-formed.
1218 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001219 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1220 << BaseType << ClassDecl->getNameAsCString()
John McCallbcd03502009-12-07 02:54:59 +00001221 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregore8381c02008-11-05 04:29:56 +00001222 }
1223
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001224 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001225 if (!BaseType->isDependentType() && !HasDependentArg) {
1226 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001227 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001228 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1229
1230 C = PerformInitializationByConstructor(BaseType,
1231 MultiExprArg(*this,
1232 (void**)Args, NumArgs),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001233 BaseLoc,
1234 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001235 Name, IK_Direct,
1236 ConstructorArgs);
1237 if (C) {
1238 // Take over the constructor arguments as our own.
1239 NumArgs = ConstructorArgs.size();
1240 Args = (Expr **)ConstructorArgs.take();
1241 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001242 }
1243
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001244 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1245 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1246 ExprTemporaries.clear();
1247
John McCallbcd03502009-12-07 02:54:59 +00001248 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001249 LParenLoc, (Expr **)Args,
1250 NumArgs, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001251}
1252
Eli Friedman9cf6b592009-11-09 19:20:36 +00001253bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001254Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001255 CXXBaseOrMemberInitializer **Initializers,
1256 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001257 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001258 // We need to build the initializer AST according to order of construction
1259 // and not what user specified in the Initializers list.
1260 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1261 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1262 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1263 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001264 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001265
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001266 for (unsigned i = 0; i < NumInitializers; i++) {
1267 CXXBaseOrMemberInitializer *Member = Initializers[i];
1268 if (Member->isBaseInitializer()) {
1269 if (Member->getBaseClass()->isDependentType())
1270 HasDependentBaseInit = true;
1271 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1272 } else {
1273 AllBaseFields[Member->getMember()] = Member;
1274 }
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001277 if (HasDependentBaseInit) {
1278 // FIXME. This does not preserve the ordering of the initializers.
1279 // Try (with -Wreorder)
1280 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001281 // template<class X> struct B : A<X> {
1282 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001283 // int x1;
1284 // };
1285 // B<int> x;
1286 // On seeing one dependent type, we should essentially exit this routine
1287 // while preserving user-declared initializer list. When this routine is
1288 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001289 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001290
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001291 // If we have a dependent base initialization, we can't determine the
1292 // association between initializers and bases; just dump the known
1293 // initializers into the list, and don't try to deal with other bases.
1294 for (unsigned i = 0; i < NumInitializers; i++) {
1295 CXXBaseOrMemberInitializer *Member = Initializers[i];
1296 if (Member->isBaseInitializer())
1297 AllToInit.push_back(Member);
1298 }
1299 } else {
1300 // Push virtual bases before others.
1301 for (CXXRecordDecl::base_class_iterator VBase =
1302 ClassDecl->vbases_begin(),
1303 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1304 if (VBase->getType()->isDependentType())
1305 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001306 if (CXXBaseOrMemberInitializer *Value
1307 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001308 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001309 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001310 else {
Mike Stump11289f42009-09-09 15:08:12 +00001311 CXXRecordDecl *VBaseDecl =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001312 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001313 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001314 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001315 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001316 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1317 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1318 << 0 << VBase->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001319 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001320 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001321 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001322 continue;
1323 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001324
Anders Carlsson561f7932009-10-29 15:46:07 +00001325 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1326 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1327 Constructor->getLocation(), CtorArgs))
1328 continue;
1329
1330 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1331
Anders Carlssonbdd12402009-11-13 20:11:49 +00001332 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001333 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1334 // necessary.
1335 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001336 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001337 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001338 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001339 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001340 SourceLocation()),
1341 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001342 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001343 CtorArgs.takeAs<Expr>(),
1344 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001345 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001346 AllToInit.push_back(Member);
1347 }
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001350 for (CXXRecordDecl::base_class_iterator Base =
1351 ClassDecl->bases_begin(),
1352 E = ClassDecl->bases_end(); Base != E; ++Base) {
1353 // Virtuals are in the virtual base list and already constructed.
1354 if (Base->isVirtual())
1355 continue;
1356 // Skip dependent types.
1357 if (Base->getType()->isDependentType())
1358 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001359 if (CXXBaseOrMemberInitializer *Value
1360 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001361 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001362 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001363 else {
Mike Stump11289f42009-09-09 15:08:12 +00001364 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001365 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001366 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001367 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001368 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001369 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1370 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1371 << 0 << Base->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001372 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001373 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001374 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001375 continue;
1376 }
1377
1378 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1379 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1380 Constructor->getLocation(), CtorArgs))
1381 continue;
1382
1383 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001384
Anders Carlssonbdd12402009-11-13 20:11:49 +00001385 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001386 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1387 // necessary.
1388 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001389 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001390 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001391 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001392 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001393 SourceLocation()),
1394 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001395 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001396 CtorArgs.takeAs<Expr>(),
1397 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001398 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001399 AllToInit.push_back(Member);
1400 }
1401 }
1402 }
Mike Stump11289f42009-09-09 15:08:12 +00001403
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001404 // non-static data members.
1405 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1406 E = ClassDecl->field_end(); Field != E; ++Field) {
1407 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001408 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001409 Field->getType()->getAs<RecordType>()) {
1410 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001411 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001412 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001413 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1414 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1415 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1416 // set to the anonymous union data member used in the initializer
1417 // list.
1418 Value->setMember(*Field);
1419 Value->setAnonUnionMember(*FA);
1420 AllToInit.push_back(Value);
1421 break;
1422 }
1423 }
1424 }
1425 continue;
1426 }
1427 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1428 AllToInit.push_back(Value);
1429 continue;
1430 }
Mike Stump11289f42009-09-09 15:08:12 +00001431
Eli Friedmand7686ef2009-11-09 01:05:47 +00001432 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001433 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001434
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001435 QualType FT = Context.getBaseElementType((*Field)->getType());
1436 if (const RecordType* RT = FT->getAs<RecordType>()) {
1437 CXXConstructorDecl *Ctor =
1438 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001439 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001440 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1441 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1442 << 1 << (*Field)->getDeclName();
1443 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregore7488b92009-12-01 16:58:18 +00001444 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001445 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001446 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001447 continue;
1448 }
Eli Friedman22683fe2009-11-16 23:07:59 +00001449
1450 if (FT.isConstQualified() && Ctor->isTrivial()) {
1451 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1452 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1453 << 1 << (*Field)->getDeclName();
1454 Diag((*Field)->getLocation(), diag::note_declared_at);
1455 HadError = true;
1456 }
1457
1458 // Don't create initializers for trivial constructors, since they don't
1459 // actually need to be run.
1460 if (Ctor->isTrivial())
1461 continue;
1462
Anders Carlsson561f7932009-10-29 15:46:07 +00001463 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1464 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1465 Constructor->getLocation(), CtorArgs))
1466 continue;
1467
Anders Carlssonbdd12402009-11-13 20:11:49 +00001468 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1469 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1470 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001471 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001472 new (Context) CXXBaseOrMemberInitializer(Context,
1473 *Field, SourceLocation(),
1474 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001475 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001476 CtorArgs.takeAs<Expr>(),
1477 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001478 SourceLocation());
1479
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001480 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001481 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001482 }
1483 else if (FT->isReferenceType()) {
1484 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001485 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1486 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001487 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001488 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001489 }
1490 else if (FT.isConstQualified()) {
1491 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001492 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1493 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001494 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001495 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001496 }
1497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001499 NumInitializers = AllToInit.size();
1500 if (NumInitializers > 0) {
1501 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1502 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1503 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001504
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001505 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1506 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1507 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1508 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001509
1510 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001511}
1512
Eli Friedman952c15d2009-07-21 19:28:10 +00001513static void *GetKeyForTopLevelField(FieldDecl *Field) {
1514 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001515 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001516 if (RT->getDecl()->isAnonymousStructOrUnion())
1517 return static_cast<void *>(RT->getDecl());
1518 }
1519 return static_cast<void *>(Field);
1520}
1521
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001522static void *GetKeyForBase(QualType BaseType) {
1523 if (const RecordType *RT = BaseType->getAs<RecordType>())
1524 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001525
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001526 assert(0 && "Unexpected base type!");
1527 return 0;
1528}
1529
Mike Stump11289f42009-09-09 15:08:12 +00001530static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001531 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001532 // For fields injected into the class via declaration of an anonymous union,
1533 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001534 if (Member->isMemberInitializer()) {
1535 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001536
Eli Friedmand7686ef2009-11-09 01:05:47 +00001537 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001538 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001539 // in AnonUnionMember field.
1540 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1541 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001542 if (Field->getDeclContext()->isRecord()) {
1543 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1544 if (RD->isAnonymousStructOrUnion())
1545 return static_cast<void *>(RD);
1546 }
1547 return static_cast<void *>(Field);
1548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001550 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001551}
1552
John McCallc90f6d72009-11-04 23:13:52 +00001553/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001554void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001555 SourceLocation ColonLoc,
1556 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001557 if (!ConstructorDecl)
1558 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001559
1560 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001561
1562 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001563 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001564
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001565 if (!Constructor) {
1566 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1567 return;
1568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001570 if (!Constructor->isDependentContext()) {
1571 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1572 bool err = false;
1573 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001574 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001575 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1576 void *KeyToMember = GetKeyForMember(Member);
1577 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1578 if (!PrevMember) {
1579 PrevMember = Member;
1580 continue;
1581 }
1582 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001583 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001584 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001585 << Field->getNameAsString()
1586 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001587 else {
1588 Type *BaseClass = Member->getBaseClass();
1589 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001590 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001591 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001592 << QualType(BaseClass, 0)
1593 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001594 }
1595 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1596 << 0;
1597 err = true;
1598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001600 if (err)
1601 return;
1602 }
Mike Stump11289f42009-09-09 15:08:12 +00001603
Eli Friedmand7686ef2009-11-09 01:05:47 +00001604 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001605 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001606 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001607
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001608 if (Constructor->isDependentContext())
1609 return;
Mike Stump11289f42009-09-09 15:08:12 +00001610
1611 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001612 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001613 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001614 Diagnostic::Ignored)
1615 return;
Mike Stump11289f42009-09-09 15:08:12 +00001616
Anders Carlssone0eebb32009-08-27 05:45:01 +00001617 // Also issue warning if order of ctor-initializer list does not match order
1618 // of 1) base class declarations and 2) order of non-static data members.
1619 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001620
Anders Carlssone0eebb32009-08-27 05:45:01 +00001621 CXXRecordDecl *ClassDecl
1622 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1623 // Push virtual bases before others.
1624 for (CXXRecordDecl::base_class_iterator VBase =
1625 ClassDecl->vbases_begin(),
1626 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001627 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001628
Anders Carlssone0eebb32009-08-27 05:45:01 +00001629 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1630 E = ClassDecl->bases_end(); Base != E; ++Base) {
1631 // Virtuals are alread in the virtual base list and are constructed
1632 // first.
1633 if (Base->isVirtual())
1634 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001635 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001636 }
Mike Stump11289f42009-09-09 15:08:12 +00001637
Anders Carlssone0eebb32009-08-27 05:45:01 +00001638 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1639 E = ClassDecl->field_end(); Field != E; ++Field)
1640 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001641
Anders Carlssone0eebb32009-08-27 05:45:01 +00001642 int Last = AllBaseOrMembers.size();
1643 int curIndex = 0;
1644 CXXBaseOrMemberInitializer *PrevMember = 0;
1645 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001646 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001647 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1648 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001649
Anders Carlssone0eebb32009-08-27 05:45:01 +00001650 for (; curIndex < Last; curIndex++)
1651 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1652 break;
1653 if (curIndex == Last) {
1654 assert(PrevMember && "Member not in member list?!");
1655 // Initializer as specified in ctor-initializer list is out of order.
1656 // Issue a warning diagnostic.
1657 if (PrevMember->isBaseInitializer()) {
1658 // Diagnostics is for an initialized base class.
1659 Type *BaseClass = PrevMember->getBaseClass();
1660 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001661 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001662 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001663 } else {
1664 FieldDecl *Field = PrevMember->getMember();
1665 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001666 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001667 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001668 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001669 // Also the note!
1670 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001671 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001672 diag::note_fieldorbase_initialized_here) << 0
1673 << Field->getNameAsString();
1674 else {
1675 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001676 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001677 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001678 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001679 }
1680 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001681 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001682 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001683 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001684 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001685 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001686}
1687
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001688void
Anders Carlssondee9a302009-11-17 04:44:12 +00001689Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1690 // Ignore dependent destructors.
1691 if (Destructor->isDependentContext())
1692 return;
1693
1694 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001695
Anders Carlssondee9a302009-11-17 04:44:12 +00001696 // Non-static data members.
1697 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1698 E = ClassDecl->field_end(); I != E; ++I) {
1699 FieldDecl *Field = *I;
1700
1701 QualType FieldType = Context.getBaseElementType(Field->getType());
1702
1703 const RecordType* RT = FieldType->getAs<RecordType>();
1704 if (!RT)
1705 continue;
1706
1707 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1708 if (FieldClassDecl->hasTrivialDestructor())
1709 continue;
1710
1711 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1712 MarkDeclarationReferenced(Destructor->getLocation(),
1713 const_cast<CXXDestructorDecl*>(Dtor));
1714 }
1715
1716 // Bases.
1717 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1718 E = ClassDecl->bases_end(); Base != E; ++Base) {
1719 // Ignore virtual bases.
1720 if (Base->isVirtual())
1721 continue;
1722
1723 // Ignore trivial destructors.
1724 CXXRecordDecl *BaseClassDecl
1725 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1726 if (BaseClassDecl->hasTrivialDestructor())
1727 continue;
1728
1729 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1730 MarkDeclarationReferenced(Destructor->getLocation(),
1731 const_cast<CXXDestructorDecl*>(Dtor));
1732 }
1733
1734 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001735 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1736 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001737 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001738 CXXRecordDecl *BaseClassDecl
1739 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1740 if (BaseClassDecl->hasTrivialDestructor())
1741 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001742
1743 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1744 MarkDeclarationReferenced(Destructor->getLocation(),
1745 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001746 }
1747}
1748
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001749void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001750 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001751 return;
Mike Stump11289f42009-09-09 15:08:12 +00001752
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001753 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001754
1755 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001756 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001757 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001758}
1759
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001760namespace {
1761 /// PureVirtualMethodCollector - traverses a class and its superclasses
1762 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001763 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001764 ASTContext &Context;
1765
Sebastian Redlb7d64912009-03-22 21:28:55 +00001766 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001767 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001768
1769 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001770 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001771
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001772 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001773
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001774 public:
Mike Stump11289f42009-09-09 15:08:12 +00001775 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001776 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001777
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001778 MethodList List;
1779 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001780
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001781 // Copy the temporary list to methods, and make sure to ignore any
1782 // null entries.
1783 for (size_t i = 0, e = List.size(); i != e; ++i) {
1784 if (List[i])
1785 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001786 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001787 }
Mike Stump11289f42009-09-09 15:08:12 +00001788
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001789 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001790
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001791 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1792 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001793 };
Mike Stump11289f42009-09-09 15:08:12 +00001794
1795 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001796 MethodList& Methods) {
1797 // First, collect the pure virtual methods for the base classes.
1798 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1799 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001800 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001801 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001802 if (BaseDecl && BaseDecl->isAbstract())
1803 Collect(BaseDecl, Methods);
1804 }
1805 }
Mike Stump11289f42009-09-09 15:08:12 +00001806
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001807 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001808 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001809
Anders Carlsson3c012712009-05-17 00:00:05 +00001810 MethodSetTy OverriddenMethods;
1811 size_t MethodsSize = Methods.size();
1812
Mike Stump11289f42009-09-09 15:08:12 +00001813 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001814 i != e; ++i) {
1815 // Traverse the record, looking for methods.
1816 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001817 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001818 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001819 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001820
Anders Carlsson700179432009-10-18 19:34:08 +00001821 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001822 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1823 E = MD->end_overridden_methods(); I != E; ++I) {
1824 // Keep track of the overridden methods.
1825 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001826 }
1827 }
1828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
1830 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001831 // overridden.
1832 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1833 if (OverriddenMethods.count(Methods[i]))
1834 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001835 }
Mike Stump11289f42009-09-09 15:08:12 +00001836
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001837 }
1838}
Douglas Gregore8381c02008-11-05 04:29:56 +00001839
Anders Carlssoneabf7702009-08-27 00:13:57 +00001840
Mike Stump11289f42009-09-09 15:08:12 +00001841bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001842 unsigned DiagID, AbstractDiagSelID SelID,
1843 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001844 if (SelID == -1)
1845 return RequireNonAbstractType(Loc, T,
1846 PDiag(DiagID), CurrentRD);
1847 else
1848 return RequireNonAbstractType(Loc, T,
1849 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001850}
1851
Anders Carlssoneabf7702009-08-27 00:13:57 +00001852bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1853 const PartialDiagnostic &PD,
1854 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001855 if (!getLangOptions().CPlusPlus)
1856 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001857
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001858 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001859 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001860 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001862 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001863 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001864 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001865 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001866
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001867 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001868 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001869 }
Mike Stump11289f42009-09-09 15:08:12 +00001870
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001871 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001872 if (!RT)
1873 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001874
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001875 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1876 if (!RD)
1877 return false;
1878
Anders Carlssonb57738b2009-03-24 17:23:42 +00001879 if (CurrentRD && CurrentRD != RD)
1880 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001881
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001882 if (!RD->isAbstract())
1883 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001884
Anders Carlssoneabf7702009-08-27 00:13:57 +00001885 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001886
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001887 // Check if we've already emitted the list of pure virtual functions for this
1888 // class.
1889 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1890 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001891
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001892 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001893
1894 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001895 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1896 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001897
1898 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001899 MD->getDeclName();
1900 }
1901
1902 if (!PureVirtualClassDiagSet)
1903 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1904 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001905
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001906 return true;
1907}
1908
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001909namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001910 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001911 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1912 Sema &SemaRef;
1913 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001914
Anders Carlssonb57738b2009-03-24 17:23:42 +00001915 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001916 bool Invalid = false;
1917
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001918 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1919 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001920 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001921
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001922 return Invalid;
1923 }
Mike Stump11289f42009-09-09 15:08:12 +00001924
Anders Carlssonb57738b2009-03-24 17:23:42 +00001925 public:
1926 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1927 : SemaRef(SemaRef), AbstractClass(ac) {
1928 Visit(SemaRef.Context.getTranslationUnitDecl());
1929 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001930
Anders Carlssonb57738b2009-03-24 17:23:42 +00001931 bool VisitFunctionDecl(const FunctionDecl *FD) {
1932 if (FD->isThisDeclarationADefinition()) {
1933 // No need to do the check if we're in a definition, because it requires
1934 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001935 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001936 return VisitDeclContext(FD);
1937 }
Mike Stump11289f42009-09-09 15:08:12 +00001938
Anders Carlssonb57738b2009-03-24 17:23:42 +00001939 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001940 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001941 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001942 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1943 diag::err_abstract_type_in_decl,
1944 Sema::AbstractReturnType,
1945 AbstractClass);
1946
Mike Stump11289f42009-09-09 15:08:12 +00001947 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001948 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001949 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001950 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001951 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001952 VD->getOriginalType(),
1953 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001954 Sema::AbstractParamType,
1955 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001956 }
1957
1958 return Invalid;
1959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Anders Carlssonb57738b2009-03-24 17:23:42 +00001961 bool VisitDecl(const Decl* D) {
1962 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1963 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001964
Anders Carlssonb57738b2009-03-24 17:23:42 +00001965 return false;
1966 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001967 };
1968}
1969
Douglas Gregorc99f1552009-12-03 18:33:45 +00001970/// \brief Perform semantic checks on a class definition that has been
1971/// completing, introducing implicitly-declared members, checking for
1972/// abstract types, etc.
1973void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1974 if (!Record || Record->isInvalidDecl())
1975 return;
1976
1977 if (!Record->isAbstract()) {
1978 // Collect all the pure virtual methods and see if this is an abstract
1979 // class after all.
1980 PureVirtualMethodCollector Collector(Context, Record);
1981 if (!Collector.empty())
1982 Record->setAbstract(true);
1983 }
1984
1985 if (Record->isAbstract())
1986 (void)AbstractClassUsageDiagnoser(*this, Record);
1987
1988 if (!Record->isDependentType() && !Record->isInvalidDecl())
1989 AddImplicitlyDeclaredMembersToClass(Record);
1990}
1991
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001992void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001993 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001994 SourceLocation LBrac,
1995 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001996 if (!TagDecl)
1997 return;
Mike Stump11289f42009-09-09 15:08:12 +00001998
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001999 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002000
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002001 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002002 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00002003 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00002004
Douglas Gregorc99f1552009-12-03 18:33:45 +00002005 CheckCompletedCXXClass(
2006 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002007}
2008
Douglas Gregor05379422008-11-03 17:51:48 +00002009/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2010/// special functions, such as the default constructor, copy
2011/// constructor, or destructor, to the given C++ class (C++
2012/// [special]p1). This routine can only be executed just before the
2013/// definition of the class is complete.
2014void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002015 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002016 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002017
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002018 // FIXME: Implicit declarations have exception specifications, which are
2019 // the union of the specifications of the implicitly called functions.
2020
Douglas Gregor05379422008-11-03 17:51:48 +00002021 if (!ClassDecl->hasUserDeclaredConstructor()) {
2022 // C++ [class.ctor]p5:
2023 // A default constructor for a class X is a constructor of class X
2024 // that can be called without an argument. If there is no
2025 // user-declared constructor for class X, a default constructor is
2026 // implicitly declared. An implicitly-declared default constructor
2027 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002028 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002029 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002030 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002031 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002032 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002033 Context.getFunctionType(Context.VoidTy,
2034 0, 0, false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002035 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002036 /*isExplicit=*/false,
2037 /*isInline=*/true,
2038 /*isImplicitlyDeclared=*/true);
2039 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002040 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002041 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002042 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002043 }
2044
2045 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2046 // C++ [class.copy]p4:
2047 // If the class definition does not explicitly declare a copy
2048 // constructor, one is declared implicitly.
2049
2050 // C++ [class.copy]p5:
2051 // The implicitly-declared copy constructor for a class X will
2052 // have the form
2053 //
2054 // X::X(const X&)
2055 //
2056 // if
2057 bool HasConstCopyConstructor = true;
2058
2059 // -- each direct or virtual base class B of X has a copy
2060 // constructor whose first parameter is of type const B& or
2061 // const volatile B&, and
2062 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2063 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2064 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002065 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002066 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002067 = BaseClassDecl->hasConstCopyConstructor(Context);
2068 }
2069
2070 // -- for all the nonstatic data members of X that are of a
2071 // class type M (or array thereof), each such class type
2072 // has a copy constructor whose first parameter is of type
2073 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002074 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2075 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002076 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002077 QualType FieldType = (*Field)->getType();
2078 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2079 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002080 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002081 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002082 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002083 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002084 = FieldClassDecl->hasConstCopyConstructor(Context);
2085 }
2086 }
2087
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002088 // Otherwise, the implicitly declared copy constructor will have
2089 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002090 //
2091 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002092 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002093 if (HasConstCopyConstructor)
2094 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002095 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002096
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002097 // An implicitly-declared copy constructor is an inline public
2098 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002099 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002100 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002101 CXXConstructorDecl *CopyConstructor
2102 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002103 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002104 Context.getFunctionType(Context.VoidTy,
2105 &ArgType, 1,
2106 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002107 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002108 /*isExplicit=*/false,
2109 /*isInline=*/true,
2110 /*isImplicitlyDeclared=*/true);
2111 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002112 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002113 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002114
2115 // Add the parameter to the constructor.
2116 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2117 ClassDecl->getLocation(),
2118 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002119 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002120 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002121 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002122 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002123 }
2124
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002125 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2126 // Note: The following rules are largely analoguous to the copy
2127 // constructor rules. Note that virtual bases are not taken into account
2128 // for determining the argument type of the operator. Note also that
2129 // operators taking an object instead of a reference are allowed.
2130 //
2131 // C++ [class.copy]p10:
2132 // If the class definition does not explicitly declare a copy
2133 // assignment operator, one is declared implicitly.
2134 // The implicitly-defined copy assignment operator for a class X
2135 // will have the form
2136 //
2137 // X& X::operator=(const X&)
2138 //
2139 // if
2140 bool HasConstCopyAssignment = true;
2141
2142 // -- each direct base class B of X has a copy assignment operator
2143 // whose parameter is of type const B&, const volatile B& or B,
2144 // and
2145 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2146 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002147 assert(!Base->getType()->isDependentType() &&
2148 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002149 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002150 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002151 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002152 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002153 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002154 }
2155
2156 // -- for all the nonstatic data members of X that are of a class
2157 // type M (or array thereof), each such class type has a copy
2158 // assignment operator whose parameter is of type const M&,
2159 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002160 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2161 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002162 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002163 QualType FieldType = (*Field)->getType();
2164 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2165 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002166 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002167 const CXXRecordDecl *FieldClassDecl
2168 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002169 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002170 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002171 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002172 }
2173 }
2174
2175 // Otherwise, the implicitly declared copy assignment operator will
2176 // have the form
2177 //
2178 // X& X::operator=(X&)
2179 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002180 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002181 if (HasConstCopyAssignment)
2182 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002183 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002184
2185 // An implicitly-declared copy assignment operator is an inline public
2186 // member of its class.
2187 DeclarationName Name =
2188 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2189 CXXMethodDecl *CopyAssignment =
2190 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2191 Context.getFunctionType(RetType, &ArgType, 1,
2192 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002193 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002194 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002195 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002196 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002197 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002198
2199 // Add the parameter to the operator.
2200 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2201 ClassDecl->getLocation(),
2202 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002203 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002204 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002205 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002206
2207 // Don't call addedAssignmentOperator. There is no way to distinguish an
2208 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002209 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002210 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002211 }
2212
Douglas Gregor1349b452008-12-15 21:24:18 +00002213 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002214 // C++ [class.dtor]p2:
2215 // If a class has no user-declared destructor, a destructor is
2216 // declared implicitly. An implicitly-declared destructor is an
2217 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002218 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002219 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002220 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002221 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002222 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002223 Context.getFunctionType(Context.VoidTy,
2224 0, 0, false, 0),
2225 /*isInline=*/true,
2226 /*isImplicitlyDeclared=*/true);
2227 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002228 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002229 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002230 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002231
2232 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002233 }
Douglas Gregor05379422008-11-03 17:51:48 +00002234}
2235
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002236void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002237 Decl *D = TemplateD.getAs<Decl>();
2238 if (!D)
2239 return;
2240
2241 TemplateParameterList *Params = 0;
2242 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2243 Params = Template->getTemplateParameters();
2244 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2245 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2246 Params = PartialSpec->getTemplateParameters();
2247 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002248 return;
2249
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002250 for (TemplateParameterList::iterator Param = Params->begin(),
2251 ParamEnd = Params->end();
2252 Param != ParamEnd; ++Param) {
2253 NamedDecl *Named = cast<NamedDecl>(*Param);
2254 if (Named->getDeclName()) {
2255 S->AddDecl(DeclPtrTy::make(Named));
2256 IdResolver.AddDecl(Named);
2257 }
2258 }
2259}
2260
Douglas Gregor4d87df52008-12-16 21:30:33 +00002261/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2262/// parsing a top-level (non-nested) C++ class, and we are now
2263/// parsing those parts of the given Method declaration that could
2264/// not be parsed earlier (C++ [class.mem]p2), such as default
2265/// arguments. This action should enter the scope of the given
2266/// Method declaration as if we had just parsed the qualified method
2267/// name. However, it should not bring the parameters into scope;
2268/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002269void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002270 if (!MethodD)
2271 return;
Mike Stump11289f42009-09-09 15:08:12 +00002272
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002273 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002274
Douglas Gregor4d87df52008-12-16 21:30:33 +00002275 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002276 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002277 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002278 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2279 SS.setScopeRep(
2280 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002281 ActOnCXXEnterDeclaratorScope(S, SS);
2282}
2283
2284/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2285/// C++ method declaration. We're (re-)introducing the given
2286/// function parameter into scope for use in parsing later parts of
2287/// the method declaration. For example, we could see an
2288/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002289void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002290 if (!ParamD)
2291 return;
Mike Stump11289f42009-09-09 15:08:12 +00002292
Chris Lattner83f095c2009-03-28 19:18:32 +00002293 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002294
2295 // If this parameter has an unparsed default argument, clear it out
2296 // to make way for the parsed default argument.
2297 if (Param->hasUnparsedDefaultArg())
2298 Param->setDefaultArg(0);
2299
Chris Lattner83f095c2009-03-28 19:18:32 +00002300 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002301 if (Param->getDeclName())
2302 IdResolver.AddDecl(Param);
2303}
2304
2305/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2306/// processing the delayed method declaration for Method. The method
2307/// declaration is now considered finished. There may be a separate
2308/// ActOnStartOfFunctionDef action later (not necessarily
2309/// immediately!) for this method, if it was also defined inside the
2310/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002311void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002312 if (!MethodD)
2313 return;
Mike Stump11289f42009-09-09 15:08:12 +00002314
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002315 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002316
Chris Lattner83f095c2009-03-28 19:18:32 +00002317 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002318 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002319 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002320 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2321 SS.setScopeRep(
2322 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002323 ActOnCXXExitDeclaratorScope(S, SS);
2324
2325 // Now that we have our default arguments, check the constructor
2326 // again. It could produce additional diagnostics or affect whether
2327 // the class has implicitly-declared destructors, among other
2328 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002329 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2330 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002331
2332 // Check the default arguments, which we may have added.
2333 if (!Method->isInvalidDecl())
2334 CheckCXXDefaultArguments(Method);
2335}
2336
Douglas Gregor831c93f2008-11-05 20:51:48 +00002337/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002338/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002339/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002340/// emit diagnostics and set the invalid bit to true. In any case, the type
2341/// will be updated to reflect a well-formed type for the constructor and
2342/// returned.
2343QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2344 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002345 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002346
2347 // C++ [class.ctor]p3:
2348 // A constructor shall not be virtual (10.3) or static (9.4). A
2349 // constructor can be invoked for a const, volatile or const
2350 // volatile object. A constructor shall not be declared const,
2351 // volatile, or const volatile (9.3.2).
2352 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002353 if (!D.isInvalidType())
2354 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2355 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2356 << SourceRange(D.getIdentifierLoc());
2357 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002358 }
2359 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002360 if (!D.isInvalidType())
2361 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2362 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2363 << SourceRange(D.getIdentifierLoc());
2364 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002365 SC = FunctionDecl::None;
2366 }
Mike Stump11289f42009-09-09 15:08:12 +00002367
Chris Lattner38378bf2009-04-25 08:28:21 +00002368 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2369 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002370 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002371 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2372 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002373 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002374 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2375 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002376 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002377 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2378 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002379 }
Mike Stump11289f42009-09-09 15:08:12 +00002380
Douglas Gregor831c93f2008-11-05 20:51:48 +00002381 // Rebuild the function type "R" without any type qualifiers (in
2382 // case any of the errors above fired) and with "void" as the
2383 // return type, since constructors don't have return types. We
2384 // *always* have to do this, because GetTypeForDeclarator will
2385 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002386 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002387 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2388 Proto->getNumArgs(),
2389 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002390}
2391
Douglas Gregor4d87df52008-12-16 21:30:33 +00002392/// CheckConstructor - Checks a fully-formed constructor for
2393/// well-formedness, issuing any diagnostics required. Returns true if
2394/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002395void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002396 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002397 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2398 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002399 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002400
2401 // C++ [class.copy]p3:
2402 // A declaration of a constructor for a class X is ill-formed if
2403 // its first parameter is of type (optionally cv-qualified) X and
2404 // either there are no other parameters or else all other
2405 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002406 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002407 ((Constructor->getNumParams() == 1) ||
2408 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002409 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2410 Constructor->getTemplateSpecializationKind()
2411 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002412 QualType ParamType = Constructor->getParamDecl(0)->getType();
2413 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2414 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002415 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2416 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002417 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002418
2419 // FIXME: Rather that making the constructor invalid, we should endeavor
2420 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002421 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002422 }
2423 }
Mike Stump11289f42009-09-09 15:08:12 +00002424
Douglas Gregor4d87df52008-12-16 21:30:33 +00002425 // Notify the class that we've added a constructor.
2426 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002427}
2428
Anders Carlsson26a807d2009-11-30 21:24:50 +00002429/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2430/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002431bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002432 CXXRecordDecl *RD = Destructor->getParent();
2433
2434 if (Destructor->isVirtual()) {
2435 SourceLocation Loc;
2436
2437 if (!Destructor->isImplicit())
2438 Loc = Destructor->getLocation();
2439 else
2440 Loc = RD->getLocation();
2441
2442 // If we have a virtual destructor, look up the deallocation function
2443 FunctionDecl *OperatorDelete = 0;
2444 DeclarationName Name =
2445 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002446 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002447 return true;
2448
2449 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002450 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002451
2452 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002453}
2454
Mike Stump11289f42009-09-09 15:08:12 +00002455static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002456FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2457 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2458 FTI.ArgInfo[0].Param &&
2459 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2460}
2461
Douglas Gregor831c93f2008-11-05 20:51:48 +00002462/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2463/// the well-formednes of the destructor declarator @p D with type @p
2464/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002465/// emit diagnostics and set the declarator to invalid. Even if this happens,
2466/// will be updated to reflect a well-formed type for the destructor and
2467/// returned.
2468QualType Sema::CheckDestructorDeclarator(Declarator &D,
2469 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002470 // C++ [class.dtor]p1:
2471 // [...] A typedef-name that names a class is a class-name
2472 // (7.1.3); however, a typedef-name that names a class shall not
2473 // be used as the identifier in the declarator for a destructor
2474 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002475 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002476 if (isa<TypedefType>(DeclaratorType)) {
2477 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002478 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002479 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002480 }
2481
2482 // C++ [class.dtor]p2:
2483 // A destructor is used to destroy objects of its class type. A
2484 // destructor takes no parameters, and no return type can be
2485 // specified for it (not even void). The address of a destructor
2486 // shall not be taken. A destructor shall not be static. A
2487 // destructor can be invoked for a const, volatile or const
2488 // volatile object. A destructor shall not be declared const,
2489 // volatile or const volatile (9.3.2).
2490 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002491 if (!D.isInvalidType())
2492 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2493 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2494 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002495 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002496 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002497 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002498 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002499 // Destructors don't have return types, but the parser will
2500 // happily parse something like:
2501 //
2502 // class X {
2503 // float ~X();
2504 // };
2505 //
2506 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002507 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2508 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2509 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002510 }
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chris Lattner38378bf2009-04-25 08:28:21 +00002512 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2513 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002514 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002515 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2516 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002517 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002518 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2519 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002520 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002521 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2522 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002523 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002524 }
2525
2526 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002527 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002528 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2529
2530 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002531 FTI.freeArgs();
2532 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002533 }
2534
Mike Stump11289f42009-09-09 15:08:12 +00002535 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002536 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002537 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002538 D.setInvalidType();
2539 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002540
2541 // Rebuild the function type "R" without any type qualifiers or
2542 // parameters (in case any of the errors above fired) and with
2543 // "void" as the return type, since destructors don't have return
2544 // types. We *always* have to do this, because GetTypeForDeclarator
2545 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002546 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002547}
2548
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002549/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2550/// well-formednes of the conversion function declarator @p D with
2551/// type @p R. If there are any errors in the declarator, this routine
2552/// will emit diagnostics and return true. Otherwise, it will return
2553/// false. Either way, the type @p R will be updated to reflect a
2554/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002555void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002556 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002557 // C++ [class.conv.fct]p1:
2558 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002559 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002560 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002561 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002562 if (!D.isInvalidType())
2563 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2564 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2565 << SourceRange(D.getIdentifierLoc());
2566 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002567 SC = FunctionDecl::None;
2568 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002569 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002570 // Conversion functions don't have return types, but the parser will
2571 // happily parse something like:
2572 //
2573 // class X {
2574 // float operator bool();
2575 // };
2576 //
2577 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002578 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2579 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2580 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002581 }
2582
2583 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002584 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002585 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2586
2587 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002588 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002589 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002590 }
2591
Mike Stump11289f42009-09-09 15:08:12 +00002592 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002593 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002594 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002595 D.setInvalidType();
2596 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002597
2598 // C++ [class.conv.fct]p4:
2599 // The conversion-type-id shall not represent a function type nor
2600 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002601 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002602 if (ConvType->isArrayType()) {
2603 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2604 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002605 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002606 } else if (ConvType->isFunctionType()) {
2607 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2608 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002609 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002610 }
2611
2612 // Rebuild the function type "R" without any parameters (in case any
2613 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002614 // return type.
2615 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002616 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002617
Douglas Gregor5fb53972009-01-14 15:45:31 +00002618 // C++0x explicit conversion operators.
2619 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002620 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002621 diag::warn_explicit_conversion_functions)
2622 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002623}
2624
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002625/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2626/// the declaration of the given C++ conversion function. This routine
2627/// is responsible for recording the conversion function in the C++
2628/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002629Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002630 assert(Conversion && "Expected to receive a conversion function declaration");
2631
Douglas Gregor4287b372008-12-12 08:25:50 +00002632 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002633
2634 // Make sure we aren't redeclaring the conversion function.
2635 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002636
2637 // C++ [class.conv.fct]p1:
2638 // [...] A conversion function is never used to convert a
2639 // (possibly cv-qualified) object to the (possibly cv-qualified)
2640 // same object type (or a reference to it), to a (possibly
2641 // cv-qualified) base class of that type (or a reference to it),
2642 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002643 // FIXME: Suppress this warning if the conversion function ends up being a
2644 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002645 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002646 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002647 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002648 ConvType = ConvTypeRef->getPointeeType();
2649 if (ConvType->isRecordType()) {
2650 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2651 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002652 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002653 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002654 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002655 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002656 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002657 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002658 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002659 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002660 }
2661
Douglas Gregor1dc98262008-12-26 15:00:45 +00002662 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002663 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002664 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002665 = Conversion->getDescribedFunctionTemplate())
2666 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCalld14a8642009-11-21 08:51:07 +00002667 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2668 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002669 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002670 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002671 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002672 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002673 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002674 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002675
Chris Lattner83f095c2009-03-28 19:18:32 +00002676 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002677}
2678
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002679//===----------------------------------------------------------------------===//
2680// Namespace Handling
2681//===----------------------------------------------------------------------===//
2682
2683/// ActOnStartNamespaceDef - This is called at the start of a namespace
2684/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002685Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2686 SourceLocation IdentLoc,
2687 IdentifierInfo *II,
2688 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002689 NamespaceDecl *Namespc =
2690 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2691 Namespc->setLBracLoc(LBrace);
2692
2693 Scope *DeclRegionScope = NamespcScope->getParent();
2694
2695 if (II) {
2696 // C++ [namespace.def]p2:
2697 // The identifier in an original-namespace-definition shall not have been
2698 // previously defined in the declarative region in which the
2699 // original-namespace-definition appears. The identifier in an
2700 // original-namespace-definition is the name of the namespace. Subsequently
2701 // in that declarative region, it is treated as an original-namespace-name.
2702
John McCall9f3059a2009-10-09 21:13:30 +00002703 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002704 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002705 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002706
Douglas Gregor91f84212008-12-11 16:49:14 +00002707 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2708 // This is an extended namespace definition.
2709 // Attach this namespace decl to the chain of extended namespace
2710 // definitions.
2711 OrigNS->setNextNamespace(Namespc);
2712 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002713
Mike Stump11289f42009-09-09 15:08:12 +00002714 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002715 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002716 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002717 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002718 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002719 } else if (PrevDecl) {
2720 // This is an invalid name redefinition.
2721 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2722 << Namespc->getDeclName();
2723 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2724 Namespc->setInvalidDecl();
2725 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002726 } else if (II->isStr("std") &&
2727 CurContext->getLookupContext()->isTranslationUnit()) {
2728 // This is the first "real" definition of the namespace "std", so update
2729 // our cache of the "std" namespace to point at this definition.
2730 if (StdNamespace) {
2731 // We had already defined a dummy namespace "std". Link this new
2732 // namespace definition to the dummy namespace "std".
2733 StdNamespace->setNextNamespace(Namespc);
2734 StdNamespace->setLocation(IdentLoc);
2735 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2736 }
2737
2738 // Make our StdNamespace cache point at the first real definition of the
2739 // "std" namespace.
2740 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002741 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002742
2743 PushOnScopeChains(Namespc, DeclRegionScope);
2744 } else {
John McCall4fa53422009-10-01 00:25:31 +00002745 // Anonymous namespaces.
2746
2747 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2748 // behaves as if it were replaced by
2749 // namespace unique { /* empty body */ }
2750 // using namespace unique;
2751 // namespace unique { namespace-body }
2752 // where all occurrences of 'unique' in a translation unit are
2753 // replaced by the same identifier and this identifier differs
2754 // from all other identifiers in the entire program.
2755
2756 // We just create the namespace with an empty name and then add an
2757 // implicit using declaration, just like the standard suggests.
2758 //
2759 // CodeGen enforces the "universally unique" aspect by giving all
2760 // declarations semantically contained within an anonymous
2761 // namespace internal linkage.
2762
2763 assert(Namespc->isAnonymousNamespace());
2764 CurContext->addDecl(Namespc);
2765
2766 UsingDirectiveDecl* UD
2767 = UsingDirectiveDecl::Create(Context, CurContext,
2768 /* 'using' */ LBrace,
2769 /* 'namespace' */ SourceLocation(),
2770 /* qualifier */ SourceRange(),
2771 /* NNS */ NULL,
2772 /* identifier */ SourceLocation(),
2773 Namespc,
2774 /* Ancestor */ CurContext);
2775 UD->setImplicit();
2776 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002777 }
2778
2779 // Although we could have an invalid decl (i.e. the namespace name is a
2780 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002781 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2782 // for the namespace has the declarations that showed up in that particular
2783 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002784 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002785 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002786}
2787
Sebastian Redla6602e92009-11-23 15:34:23 +00002788/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2789/// is a namespace alias, returns the namespace it points to.
2790static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2791 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2792 return AD->getNamespace();
2793 return dyn_cast_or_null<NamespaceDecl>(D);
2794}
2795
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002796/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2797/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002798void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2799 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002800 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2801 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2802 Namespc->setRBracLoc(RBrace);
2803 PopDeclContext();
2804}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002805
Chris Lattner83f095c2009-03-28 19:18:32 +00002806Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2807 SourceLocation UsingLoc,
2808 SourceLocation NamespcLoc,
2809 const CXXScopeSpec &SS,
2810 SourceLocation IdentLoc,
2811 IdentifierInfo *NamespcName,
2812 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002813 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2814 assert(NamespcName && "Invalid NamespcName.");
2815 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002816 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002817
Douglas Gregor889ceb72009-02-03 19:21:40 +00002818 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002819
Douglas Gregor34074322009-01-14 22:20:51 +00002820 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002821 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2822 LookupParsedName(R, S, &SS);
2823 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002824 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002825
John McCall9f3059a2009-10-09 21:13:30 +00002826 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002827 NamedDecl *Named = R.getFoundDecl();
2828 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2829 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002830 // C++ [namespace.udir]p1:
2831 // A using-directive specifies that the names in the nominated
2832 // namespace can be used in the scope in which the
2833 // using-directive appears after the using-directive. During
2834 // unqualified name lookup (3.4.1), the names appear as if they
2835 // were declared in the nearest enclosing namespace which
2836 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002837 // namespace. [Note: in this context, "contains" means "contains
2838 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002839
2840 // Find enclosing context containing both using-directive and
2841 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002842 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002843 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2844 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2845 CommonAncestor = CommonAncestor->getParent();
2846
Sebastian Redla6602e92009-11-23 15:34:23 +00002847 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002848 SS.getRange(),
2849 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00002850 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002851 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002852 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002853 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002854 }
2855
Douglas Gregor889ceb72009-02-03 19:21:40 +00002856 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002857 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002858 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002859}
2860
2861void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2862 // If scope has associated entity, then using directive is at namespace
2863 // or translation unit scope. We add UsingDirectiveDecls, into
2864 // it's lookup structure.
2865 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002866 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002867 else
2868 // Otherwise it is block-sope. using-directives will affect lookup
2869 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002870 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002871}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002872
Douglas Gregorfec52632009-06-20 00:51:54 +00002873
2874Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002875 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002876 SourceLocation UsingLoc,
2877 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002878 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002879 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002880 bool IsTypeName,
2881 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002882 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002883
Douglas Gregor220f4272009-11-04 16:30:06 +00002884 switch (Name.getKind()) {
2885 case UnqualifiedId::IK_Identifier:
2886 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00002887 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00002888 case UnqualifiedId::IK_ConversionFunctionId:
2889 break;
2890
2891 case UnqualifiedId::IK_ConstructorName:
2892 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2893 << SS.getRange();
2894 return DeclPtrTy();
2895
2896 case UnqualifiedId::IK_DestructorName:
2897 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2898 << SS.getRange();
2899 return DeclPtrTy();
2900
2901 case UnqualifiedId::IK_TemplateId:
2902 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2903 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2904 return DeclPtrTy();
2905 }
2906
2907 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3f746822009-11-17 05:59:44 +00002908 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002909 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002910 TargetName, AttrList,
2911 /* IsInstantiation */ false,
2912 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00002913 if (UD)
2914 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00002915
Anders Carlsson696a3f12009-08-28 05:40:36 +00002916 return DeclPtrTy::make(UD);
2917}
2918
John McCall3f746822009-11-17 05:59:44 +00002919/// Builds a shadow declaration corresponding to a 'using' declaration.
2920static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2921 AccessSpecifier AS,
2922 UsingDecl *UD, NamedDecl *Orig) {
2923 // FIXME: diagnose hiding, collisions
2924
2925 // If we resolved to another shadow declaration, just coalesce them.
2926 if (isa<UsingShadowDecl>(Orig)) {
2927 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2928 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2929 }
2930
2931 UsingShadowDecl *Shadow
2932 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2933 UD->getLocation(), UD, Orig);
2934 UD->addShadowDecl(Shadow);
2935
2936 if (S)
2937 SemaRef.PushOnScopeChains(Shadow, S);
2938 else
2939 SemaRef.CurContext->addDecl(Shadow);
2940 Shadow->setAccess(AS);
2941
2942 return Shadow;
2943}
2944
John McCalle61f2ba2009-11-18 02:36:19 +00002945/// Builds a using declaration.
2946///
2947/// \param IsInstantiation - Whether this call arises from an
2948/// instantiation of an unresolved using declaration. We treat
2949/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00002950NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2951 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002952 const CXXScopeSpec &SS,
2953 SourceLocation IdentLoc,
2954 DeclarationName Name,
2955 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002956 bool IsInstantiation,
2957 bool IsTypeName,
2958 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002959 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2960 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002961
Anders Carlssonf038fc22009-08-28 05:49:21 +00002962 // FIXME: We ignore attributes for now.
2963 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002964
Anders Carlsson59140b32009-08-28 03:16:11 +00002965 if (SS.isEmpty()) {
2966 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002967 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002968 }
Mike Stump11289f42009-09-09 15:08:12 +00002969
2970 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002971 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2972
John McCallb96ec562009-12-04 22:46:56 +00002973 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
2974 return 0;
2975
John McCall84c16cf2009-11-12 03:15:40 +00002976 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00002977 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00002978 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00002979 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00002980 // FIXME: not all declaration name kinds are legal here
2981 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2982 UsingLoc, TypenameLoc,
2983 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00002984 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00002985 } else {
2986 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
2987 UsingLoc, SS.getRange(), NNS,
2988 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00002989 }
John McCallb96ec562009-12-04 22:46:56 +00002990 } else {
2991 D = UsingDecl::Create(Context, CurContext, IdentLoc,
2992 SS.getRange(), UsingLoc, NNS, Name,
2993 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00002994 }
John McCallb96ec562009-12-04 22:46:56 +00002995 D->setAccess(AS);
2996 CurContext->addDecl(D);
2997
2998 if (!LookupContext) return D;
2999 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003000
Anders Carlsson59140b32009-08-28 03:16:11 +00003001 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
3002 // C++0x N2914 [namespace.udecl]p3:
3003 // A using-declaration used as a member-declaration shall refer to a member
3004 // of a base class of the class being defined, shall refer to a member of an
3005 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00003006 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00003007 // a member of a base class of the class being defined.
John McCall3f746822009-11-17 05:59:44 +00003008
John McCall84c16cf2009-11-12 03:15:40 +00003009 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
3010 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlsson59140b32009-08-28 03:16:11 +00003011 Diag(SS.getRange().getBegin(),
3012 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
3013 << NNS << RD->getDeclName();
John McCallb96ec562009-12-04 22:46:56 +00003014 UD->setInvalidDecl();
3015 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003016 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003017 } else {
3018 // C++0x N2914 [namespace.udecl]p8:
3019 // A using-declaration for a class member shall be a member-declaration.
John McCall84c16cf2009-11-12 03:15:40 +00003020 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003021 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00003022 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003023 UD->setInvalidDecl();
3024 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003025 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003026 }
3027
John McCall3f746822009-11-17 05:59:44 +00003028 // Look up the target name. Unlike most lookups, we do not want to
3029 // hide tag declarations: tag names are visible through the using
3030 // declaration even if hidden by ordinary names.
John McCall27b18f82009-11-17 02:14:36 +00003031 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003032
3033 // We don't hide tags behind ordinary decls if we're in a
3034 // non-dependent context, but in a dependent context, this is
3035 // important for the stability of two-phase lookup.
3036 if (!IsInstantiation)
3037 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003038
John McCall27b18f82009-11-17 02:14:36 +00003039 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003040
John McCall9f3059a2009-10-09 21:13:30 +00003041 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003042 Diag(IdentLoc, diag::err_no_member)
3043 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003044 UD->setInvalidDecl();
3045 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003046 }
3047
John McCallb96ec562009-12-04 22:46:56 +00003048 if (R.isAmbiguous()) {
3049 UD->setInvalidDecl();
3050 return UD;
3051 }
Mike Stump11289f42009-09-09 15:08:12 +00003052
John McCalle61f2ba2009-11-18 02:36:19 +00003053 if (IsTypeName) {
3054 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003055 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003056 Diag(IdentLoc, diag::err_using_typename_non_type);
3057 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3058 Diag((*I)->getUnderlyingDecl()->getLocation(),
3059 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003060 UD->setInvalidDecl();
3061 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003062 }
3063 } else {
3064 // If we asked for a non-typename and we got a type, error out,
3065 // but only if this is an instantiation of an unresolved using
3066 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003067 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003068 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3069 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003070 UD->setInvalidDecl();
3071 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003072 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003073 }
3074
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003075 // C++0x N2914 [namespace.udecl]p6:
3076 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003077 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003078 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3079 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003080 UD->setInvalidDecl();
3081 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003082 }
Mike Stump11289f42009-09-09 15:08:12 +00003083
John McCall3f746822009-11-17 05:59:44 +00003084 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3085 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3086
3087 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003088}
3089
John McCallb96ec562009-12-04 22:46:56 +00003090/// Checks that the given nested-name qualifier used in a using decl
3091/// in the current context is appropriately related to the current
3092/// scope. If an error is found, diagnoses it and returns true.
3093bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3094 const CXXScopeSpec &SS,
3095 SourceLocation NameLoc) {
3096 // FIXME: implement
3097
3098 return false;
3099}
3100
Mike Stump11289f42009-09-09 15:08:12 +00003101Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003102 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003103 SourceLocation AliasLoc,
3104 IdentifierInfo *Alias,
3105 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003106 SourceLocation IdentLoc,
3107 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003108
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003109 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003110 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3111 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003112
Anders Carlssondca83c42009-03-28 06:23:46 +00003113 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003114 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003115 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003116 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003117 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003118 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003119 if (!R.isAmbiguous() && !R.empty() &&
3120 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003121 return DeclPtrTy();
3122 }
Mike Stump11289f42009-09-09 15:08:12 +00003123
Anders Carlssondca83c42009-03-28 06:23:46 +00003124 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3125 diag::err_redefinition_different_kind;
3126 Diag(AliasLoc, DiagID) << Alias;
3127 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003128 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003129 }
3130
John McCall27b18f82009-11-17 02:14:36 +00003131 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003132 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003133
John McCall9f3059a2009-10-09 21:13:30 +00003134 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003135 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003136 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003137 }
Mike Stump11289f42009-09-09 15:08:12 +00003138
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003139 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003140 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3141 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003142 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003143 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003144
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003145 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003146 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003147}
3148
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003149void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3150 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003151 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3152 !Constructor->isUsed()) &&
3153 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003154
Eli Friedman9cf6b592009-11-09 19:20:36 +00003155 CXXRecordDecl *ClassDecl
3156 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3157 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003158
Eli Friedman9cf6b592009-11-09 19:20:36 +00003159 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003160 Diag(CurrentLocation, diag::note_member_synthesized_at)
3161 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003162 Constructor->setInvalidDecl();
3163 } else {
3164 Constructor->setUsed();
3165 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00003166
3167 MaybeMarkVirtualImplicitMembersReferenced(CurrentLocation, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003168}
3169
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003170void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003171 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003172 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3173 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003174 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003175 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3176 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003177 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003178 // implicitly defined, all the implicitly-declared default destructors
3179 // for its base class and its non-static data members shall have been
3180 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003181 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3182 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003183 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003184 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003185 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003186 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003187 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3188 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3189 else
Mike Stump11289f42009-09-09 15:08:12 +00003190 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003191 "DefineImplicitDestructor - missing dtor in a base class");
3192 }
3193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003195 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3196 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003197 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3198 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3199 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003200 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003201 CXXRecordDecl *FieldClassDecl
3202 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3203 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003204 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003205 const_cast<CXXDestructorDecl*>(
3206 FieldClassDecl->getDestructor(Context)))
3207 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3208 else
Mike Stump11289f42009-09-09 15:08:12 +00003209 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003210 "DefineImplicitDestructor - missing dtor in class of a data member");
3211 }
3212 }
3213 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003214
3215 // FIXME: If CheckDestructor fails, we should emit a note about where the
3216 // implicit destructor was needed.
3217 if (CheckDestructor(Destructor)) {
3218 Diag(CurrentLocation, diag::note_member_synthesized_at)
3219 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3220
3221 Destructor->setInvalidDecl();
3222 return;
3223 }
3224
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003225 Destructor->setUsed();
3226}
3227
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003228void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3229 CXXMethodDecl *MethodDecl) {
3230 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3231 MethodDecl->getOverloadedOperator() == OO_Equal &&
3232 !MethodDecl->isUsed()) &&
3233 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003234
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003235 CXXRecordDecl *ClassDecl
3236 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003237
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003238 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003239 // Before the implicitly-declared copy assignment operator for a class is
3240 // implicitly defined, all implicitly-declared copy assignment operators
3241 // for its direct base classes and its nonstatic data members shall have
3242 // been implicitly defined.
3243 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003244 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3245 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003246 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003247 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003248 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003249 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3250 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3251 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003252 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3253 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003254 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3255 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3256 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003257 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003258 CXXRecordDecl *FieldClassDecl
3259 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003260 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003261 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3262 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003263 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003264 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003265 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3266 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003267 Diag(CurrentLocation, diag::note_first_required_here);
3268 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003269 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003270 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003271 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3272 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003273 Diag(CurrentLocation, diag::note_first_required_here);
3274 err = true;
3275 }
3276 }
3277 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003278 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003279}
3280
3281CXXMethodDecl *
3282Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3283 CXXRecordDecl *ClassDecl) {
3284 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3285 QualType RHSType(LHSType);
3286 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003287 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003288 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003289 RHSType = Context.getCVRQualifiedType(RHSType,
3290 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003291 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3292 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003293 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003294 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3295 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003296 SourceLocation()));
3297 Expr *Args[2] = { &*LHS, &*RHS };
3298 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003299 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003300 CandidateSet);
3301 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003302 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003303 ClassDecl->getLocation(), Best) == OR_Success)
3304 return cast<CXXMethodDecl>(Best->Function);
3305 assert(false &&
3306 "getAssignOperatorMethod - copy assignment operator method not found");
3307 return 0;
3308}
3309
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003310void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3311 CXXConstructorDecl *CopyConstructor,
3312 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003313 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003314 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3315 !CopyConstructor->isUsed()) &&
3316 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003317
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003318 CXXRecordDecl *ClassDecl
3319 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3320 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003321 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003322 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003323 // implicitly defined, all the implicitly-declared copy constructors
3324 // for its base class and its non-static data members shall have been
3325 // implicitly defined.
3326 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3327 Base != ClassDecl->bases_end(); ++Base) {
3328 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003329 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003330 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003331 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003332 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003333 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003334 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3335 FieldEnd = ClassDecl->field_end();
3336 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003337 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3338 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3339 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003340 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003341 CXXRecordDecl *FieldClassDecl
3342 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003343 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003344 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003345 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003346 }
3347 }
3348 CopyConstructor->setUsed();
3349}
3350
Anders Carlsson6eb55572009-08-25 05:12:04 +00003351Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003352Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003353 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003354 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003355 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003356
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003357 // C++ [class.copy]p15:
3358 // Whenever a temporary class object is copied using a copy constructor, and
3359 // this object and the copy have the same cv-unqualified type, an
3360 // implementation is permitted to treat the original and the copy as two
3361 // different ways of referring to the same object and not perform a copy at
3362 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003363
Anders Carlsson250aada2009-08-16 05:13:48 +00003364 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003365 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003366 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003367 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3368 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003369 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3370 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3371 E = ICE->getSubExpr();
Eli Friedmaneddf1212009-12-06 09:26:33 +00003372
3373 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3374 Elidable = !CE->getCallReturnType()->isReferenceType();
3375 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson250aada2009-08-16 05:13:48 +00003376 Elidable = true;
3377 }
Mike Stump11289f42009-09-09 15:08:12 +00003378
3379 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003380 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003381}
3382
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003383/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3384/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003385Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003386Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3387 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003388 MultiExprArg ExprArgs) {
3389 unsigned NumExprs = ExprArgs.size();
3390 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003391
Douglas Gregor27381f32009-11-23 12:27:39 +00003392 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003393 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3394 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003395}
3396
Anders Carlsson574315a2009-08-27 05:08:22 +00003397Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003398Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3399 QualType Ty,
3400 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003401 MultiExprArg Args,
3402 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003403 unsigned NumExprs = Args.size();
3404 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003405
Douglas Gregor27381f32009-11-23 12:27:39 +00003406 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003407 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3408 TyBeginLoc, Exprs,
3409 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003410}
3411
3412
Mike Stump11289f42009-09-09 15:08:12 +00003413bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003414 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003415 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003416 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003417 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003418 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003419 if (TempResult.isInvalid())
3420 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003421
Anders Carlsson6eb55572009-08-25 05:12:04 +00003422 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003423 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003424 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003425 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003426
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003427 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003428}
3429
Mike Stump11289f42009-09-09 15:08:12 +00003430void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003431 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003432 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003433 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003434 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003435 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003436 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003437}
3438
Mike Stump11289f42009-09-09 15:08:12 +00003439/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003440/// ActOnDeclarator, when a C++ direct initializer is present.
3441/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003442void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3443 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003444 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003445 SourceLocation *CommaLocs,
3446 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003447 unsigned NumExprs = Exprs.size();
3448 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003449 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003450
3451 // If there is no declaration, there was an error parsing it. Just ignore
3452 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003453 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003454 return;
Mike Stump11289f42009-09-09 15:08:12 +00003455
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003456 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3457 if (!VDecl) {
3458 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3459 RealDecl->setInvalidDecl();
3460 return;
3461 }
3462
Douglas Gregor402250f2009-08-26 21:14:46 +00003463 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003464 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003465 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3466 //
3467 // Clients that want to distinguish between the two forms, can check for
3468 // direct initializer using VarDecl::hasCXXDirectInitializer().
3469 // A major benefit is that clients that don't particularly care about which
3470 // exactly form was it (like the CodeGen) can handle both cases without
3471 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003472
Douglas Gregor402250f2009-08-26 21:14:46 +00003473 // If either the declaration has a dependent type or if any of the expressions
3474 // is type-dependent, we represent the initialization via a ParenListExpr for
3475 // later use during template instantiation.
3476 if (VDecl->getType()->isDependentType() ||
3477 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3478 // Let clients know that initialization was done with a direct initializer.
3479 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003480
Douglas Gregor402250f2009-08-26 21:14:46 +00003481 // Store the initialization expressions as a ParenListExpr.
3482 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003483 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003484 new (Context) ParenListExpr(Context, LParenLoc,
3485 (Expr **)Exprs.release(),
3486 NumExprs, RParenLoc));
3487 return;
3488 }
Mike Stump11289f42009-09-09 15:08:12 +00003489
Douglas Gregor402250f2009-08-26 21:14:46 +00003490
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003491 // C++ 8.5p11:
3492 // The form of initialization (using parentheses or '=') is generally
3493 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003494 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003495 QualType DeclInitType = VDecl->getType();
3496 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003497 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003498
Douglas Gregor4044d992009-03-24 16:43:20 +00003499 // FIXME: This isn't the right place to complete the type.
3500 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3501 diag::err_typecheck_decl_incomplete_type)) {
3502 VDecl->setInvalidDecl();
3503 return;
3504 }
3505
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003506 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003507 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3508
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003509 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003510 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003511 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003512 VDecl->getLocation(),
3513 SourceRange(VDecl->getLocation(),
3514 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003515 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003516 IK_Direct,
3517 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003518 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003519 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003520 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003521 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003522 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003523 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003524 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003525 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003526 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003527 return;
3528 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003529
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003530 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003531 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3532 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003533 RealDecl->setInvalidDecl();
3534 return;
3535 }
3536
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003537 // Let clients know that initialization was done with a direct initializer.
3538 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003539
3540 assert(NumExprs == 1 && "Expected 1 expression");
3541 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003542 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3543 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003544}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003545
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003546/// \brief Add the applicable constructor candidates for an initialization
3547/// by constructor.
3548static void AddConstructorInitializationCandidates(Sema &SemaRef,
3549 QualType ClassType,
3550 Expr **Args,
3551 unsigned NumArgs,
3552 Sema::InitializationKind Kind,
3553 OverloadCandidateSet &CandidateSet) {
3554 // C++ [dcl.init]p14:
3555 // If the initialization is direct-initialization, or if it is
3556 // copy-initialization where the cv-unqualified version of the
3557 // source type is the same class as, or a derived class of, the
3558 // class of the destination, constructors are considered. The
3559 // applicable constructors are enumerated (13.3.1.3), and the
3560 // best one is chosen through overload resolution (13.3). The
3561 // constructor so selected is called to initialize the object,
3562 // with the initializer expression(s) as its argument(s). If no
3563 // constructor applies, or the overload resolution is ambiguous,
3564 // the initialization is ill-formed.
3565 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3566 assert(ClassRec && "Can only initialize a class type here");
3567
3568 // FIXME: When we decide not to synthesize the implicitly-declared
3569 // constructors, we'll need to make them appear here.
3570
3571 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3572 DeclarationName ConstructorName
3573 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3574 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3575 DeclContext::lookup_const_iterator Con, ConEnd;
3576 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3577 Con != ConEnd; ++Con) {
3578 // Find the constructor (which may be a template).
3579 CXXConstructorDecl *Constructor = 0;
3580 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3581 if (ConstructorTmpl)
3582 Constructor
3583 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3584 else
3585 Constructor = cast<CXXConstructorDecl>(*Con);
3586
3587 if ((Kind == Sema::IK_Direct) ||
3588 (Kind == Sema::IK_Copy &&
3589 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3590 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3591 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00003592 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3593 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003594 Args, NumArgs, CandidateSet);
3595 else
3596 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3597 }
3598 }
3599}
3600
3601/// \brief Attempt to perform initialization by constructor
3602/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3603/// copy-initialization.
3604///
3605/// This routine determines whether initialization by constructor is possible,
3606/// but it does not emit any diagnostics in the case where the initialization
3607/// is ill-formed.
3608///
3609/// \param ClassType the type of the object being initialized, which must have
3610/// class type.
3611///
3612/// \param Args the arguments provided to initialize the object
3613///
3614/// \param NumArgs the number of arguments provided to initialize the object
3615///
3616/// \param Kind the type of initialization being performed
3617///
3618/// \returns the constructor used to initialize the object, if successful.
3619/// Otherwise, emits a diagnostic and returns NULL.
3620CXXConstructorDecl *
3621Sema::TryInitializationByConstructor(QualType ClassType,
3622 Expr **Args, unsigned NumArgs,
3623 SourceLocation Loc,
3624 InitializationKind Kind) {
3625 // Build the overload candidate set
3626 OverloadCandidateSet CandidateSet;
3627 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3628 CandidateSet);
3629
3630 // Determine whether we found a constructor we can use.
3631 OverloadCandidateSet::iterator Best;
3632 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3633 case OR_Success:
3634 case OR_Deleted:
3635 // We found a constructor. Return it.
3636 return cast<CXXConstructorDecl>(Best->Function);
3637
3638 case OR_No_Viable_Function:
3639 case OR_Ambiguous:
3640 // Overload resolution failed. Return nothing.
3641 return 0;
3642 }
3643
3644 // Silence GCC warning
3645 return 0;
3646}
3647
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003648/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3649/// may occur as part of direct-initialization or copy-initialization.
3650///
3651/// \param ClassType the type of the object being initialized, which must have
3652/// class type.
3653///
3654/// \param ArgsPtr the arguments provided to initialize the object
3655///
3656/// \param Loc the source location where the initialization occurs
3657///
3658/// \param Range the source range that covers the entire initialization
3659///
3660/// \param InitEntity the name of the entity being initialized, if known
3661///
3662/// \param Kind the type of initialization being performed
3663///
3664/// \param ConvertedArgs a vector that will be filled in with the
3665/// appropriately-converted arguments to the constructor (if initialization
3666/// succeeded).
3667///
3668/// \returns the constructor used to initialize the object, if successful.
3669/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003670CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003671Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003672 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003673 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003674 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003675 InitializationKind Kind,
3676 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003677
3678 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003679 Expr **Args = (Expr **)ArgsPtr.get();
3680 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003681 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003682 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3683 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00003684
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003685 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003686 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003687 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003688 // We found a constructor. Break out so that we can convert the arguments
3689 // appropriately.
3690 break;
Mike Stump11289f42009-09-09 15:08:12 +00003691
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003692 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003693 if (InitEntity)
3694 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003695 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003696 else
3697 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003698 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003699 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003700 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003702 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003703 if (InitEntity)
3704 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3705 else
3706 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003707 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3708 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003709
3710 case OR_Deleted:
3711 if (InitEntity)
3712 Diag(Loc, diag::err_ovl_deleted_init)
3713 << Best->Function->isDeleted()
3714 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003715 else {
3716 const CXXRecordDecl *RD =
3717 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003718 Diag(Loc, diag::err_ovl_deleted_init)
3719 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003720 << RD->getDeclName() << Range;
3721 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00003722 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3723 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003724 }
Mike Stump11289f42009-09-09 15:08:12 +00003725
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003726 // Convert the arguments, fill in default arguments, etc.
3727 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3728 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3729 return 0;
3730
3731 return Constructor;
3732}
3733
3734/// \brief Given a constructor and the set of arguments provided for the
3735/// constructor, convert the arguments and add any required default arguments
3736/// to form a proper call to this constructor.
3737///
3738/// \returns true if an error occurred, false otherwise.
3739bool
3740Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3741 MultiExprArg ArgsPtr,
3742 SourceLocation Loc,
3743 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3744 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3745 unsigned NumArgs = ArgsPtr.size();
3746 Expr **Args = (Expr **)ArgsPtr.get();
3747
3748 const FunctionProtoType *Proto
3749 = Constructor->getType()->getAs<FunctionProtoType>();
3750 assert(Proto && "Constructor without a prototype?");
3751 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003752
3753 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003754 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003755 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003756 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003757 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003758
3759 VariadicCallType CallType =
3760 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3761 llvm::SmallVector<Expr *, 8> AllArgs;
3762 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3763 Proto, 0, Args, NumArgs, AllArgs,
3764 CallType);
3765 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3766 ConvertedArgs.push_back(AllArgs[i]);
3767 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003768}
3769
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003770/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3771/// determine whether they are reference-related,
3772/// reference-compatible, reference-compatible with added
3773/// qualification, or incompatible, for use in C++ initialization by
3774/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3775/// type, and the first type (T1) is the pointee type of the reference
3776/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003777Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003778Sema::CompareReferenceRelationship(SourceLocation Loc,
3779 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003780 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003781 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003782 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003783 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003784
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003785 QualType T1 = Context.getCanonicalType(OrigT1);
3786 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003787 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3788 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003789
3790 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003791 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003792 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003793 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003794 if (UnqualT1 == UnqualT2)
3795 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003796 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3797 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3798 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003799 DerivedToBase = true;
3800 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003801 return Ref_Incompatible;
3802
3803 // At this point, we know that T1 and T2 are reference-related (at
3804 // least).
3805
3806 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003807 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003808 // reference-related to T2 and cv1 is the same cv-qualification
3809 // as, or greater cv-qualification than, cv2. For purposes of
3810 // overload resolution, cases for which cv1 is greater
3811 // cv-qualification than cv2 are identified as
3812 // reference-compatible with added qualification (see 13.3.3.2).
3813 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3814 return Ref_Compatible;
3815 else if (T1.isMoreQualifiedThan(T2))
3816 return Ref_Compatible_With_Added_Qualification;
3817 else
3818 return Ref_Related;
3819}
3820
3821/// CheckReferenceInit - Check the initialization of a reference
3822/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3823/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003824/// list), and DeclType is the type of the declaration. When ICS is
3825/// non-null, this routine will compute the implicit conversion
3826/// sequence according to C++ [over.ics.ref] and will not produce any
3827/// diagnostics; when ICS is null, it will emit diagnostics when any
3828/// errors are found. Either way, a return value of true indicates
3829/// that there was a failure, a return value of false indicates that
3830/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003831///
3832/// When @p SuppressUserConversions, user-defined conversions are
3833/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003834/// When @p AllowExplicit, we also permit explicit user-defined
3835/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003836/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00003837/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3838/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00003839bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003840Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003841 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003842 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003843 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00003844 ImplicitConversionSequence *ICS,
3845 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003846 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3847
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003848 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003849 QualType T2 = Init->getType();
3850
Douglas Gregorcd695e52008-11-10 20:40:00 +00003851 // If the initializer is the address of an overloaded function, try
3852 // to resolve the overloaded function. If all goes well, T2 is the
3853 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003854 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003855 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003856 ICS != 0);
3857 if (Fn) {
3858 // Since we're performing this reference-initialization for
3859 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003860 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003861 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003862 return true;
3863
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003864 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003865 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003866
3867 T2 = Fn->getType();
3868 }
3869 }
3870
Douglas Gregor786ab212008-10-29 02:00:59 +00003871 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003872 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003873 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003874 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3875 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003876 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003877 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003878
3879 // Most paths end in a failed conversion.
3880 if (ICS)
3881 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003882
3883 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003884 // A reference to type "cv1 T1" is initialized by an expression
3885 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003886
3887 // -- If the initializer expression
3888
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003889 // Rvalue references cannot bind to lvalues (N2812).
3890 // There is absolutely no situation where they can. In particular, note that
3891 // this is ill-formed, even if B has a user-defined conversion to A&&:
3892 // B b;
3893 // A&& r = b;
3894 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3895 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003896 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003897 << Init->getSourceRange();
3898 return true;
3899 }
3900
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003901 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003902 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3903 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003904 //
3905 // Note that the bit-field check is skipped if we are just computing
3906 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003907 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003908 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003909 BindsDirectly = true;
3910
Douglas Gregor786ab212008-10-29 02:00:59 +00003911 if (ICS) {
3912 // C++ [over.ics.ref]p1:
3913 // When a parameter of reference type binds directly (8.5.3)
3914 // to an argument expression, the implicit conversion sequence
3915 // is the identity conversion, unless the argument expression
3916 // has a type that is a derived class of the parameter type,
3917 // in which case the implicit conversion sequence is a
3918 // derived-to-base Conversion (13.3.3.1).
3919 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3920 ICS->Standard.First = ICK_Identity;
3921 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3922 ICS->Standard.Third = ICK_Identity;
3923 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3924 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003925 ICS->Standard.ReferenceBinding = true;
3926 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003927 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003928 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003929
3930 // Nothing more to do: the inaccessibility/ambiguity check for
3931 // derived-to-base conversions is suppressed when we're
3932 // computing the implicit conversion sequence (C++
3933 // [over.best.ics]p2).
3934 return false;
3935 } else {
3936 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003937 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3938 if (DerivedToBase)
3939 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003940 else if(CheckExceptionSpecCompatibility(Init, T1))
3941 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003942 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003943 }
3944 }
3945
3946 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003947 // implicitly converted to an lvalue of type "cv3 T3,"
3948 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003949 // 92) (this conversion is selected by enumerating the
3950 // applicable conversion functions (13.3.1.6) and choosing
3951 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003952 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003953 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003954 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003955 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003956
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003957 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00003958 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003959 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003960 for (UnresolvedSet::iterator I = Conversions->begin(),
3961 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00003962 NamedDecl *D = *I;
3963 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3964 if (isa<UsingShadowDecl>(D))
3965 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3966
Mike Stump11289f42009-09-09 15:08:12 +00003967 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00003968 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00003969 CXXConversionDecl *Conv;
3970 if (ConvTemplate)
3971 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3972 else
John McCall6e9f8f62009-12-03 04:06:58 +00003973 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003974
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003975 // If the conversion function doesn't return a reference type,
3976 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003977 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003978 (AllowExplicit || !Conv->isExplicit())) {
3979 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00003980 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
3981 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003982 else
John McCall6e9f8f62009-12-03 04:06:58 +00003983 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003984 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003985 }
3986
3987 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003988 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003989 case OR_Success:
3990 // This is a direct binding.
3991 BindsDirectly = true;
3992
3993 if (ICS) {
3994 // C++ [over.ics.ref]p1:
3995 //
3996 // [...] If the parameter binds directly to the result of
3997 // applying a conversion function to the argument
3998 // expression, the implicit conversion sequence is a
3999 // user-defined conversion sequence (13.3.3.1.2), with the
4000 // second standard conversion sequence either an identity
4001 // conversion or, if the conversion function returns an
4002 // entity of a type that is a derived class of the parameter
4003 // type, a derived-to-base Conversion.
4004 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4005 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4006 ICS->UserDefined.After = Best->FinalConversion;
4007 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004008 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004009 assert(ICS->UserDefined.After.ReferenceBinding &&
4010 ICS->UserDefined.After.DirectBinding &&
4011 "Expected a direct reference binding!");
4012 return false;
4013 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004014 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00004015 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004016 CastExpr::CK_UserDefinedConversion,
4017 cast<CXXMethodDecl>(Best->Function),
4018 Owned(Init));
4019 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00004020
4021 if (CheckExceptionSpecCompatibility(Init, T1))
4022 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004023 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4024 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004025 }
4026 break;
4027
4028 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004029 if (ICS) {
4030 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4031 Cand != CandidateSet.end(); ++Cand)
4032 if (Cand->Viable)
4033 ICS->ConversionFunctionSet.push_back(Cand->Function);
4034 break;
4035 }
4036 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4037 << Init->getSourceRange();
4038 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004039 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004040
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004041 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004042 case OR_Deleted:
4043 // There was no suitable conversion, or we found a deleted
4044 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004045 break;
4046 }
4047 }
Mike Stump11289f42009-09-09 15:08:12 +00004048
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004049 if (BindsDirectly) {
4050 // C++ [dcl.init.ref]p4:
4051 // [...] In all cases where the reference-related or
4052 // reference-compatible relationship of two types is used to
4053 // establish the validity of a reference binding, and T1 is a
4054 // base class of T2, a program that necessitates such a binding
4055 // is ill-formed if T1 is an inaccessible (clause 11) or
4056 // ambiguous (10.2) base class of T2.
4057 //
4058 // Note that we only check this condition when we're allowed to
4059 // complain about errors, because we should not be checking for
4060 // ambiguity (or inaccessibility) unless the reference binding
4061 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004062 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004063 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004064 Init->getSourceRange(),
4065 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004066 else
4067 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004068 }
4069
4070 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004071 // type (i.e., cv1 shall be const), or the reference shall be an
4072 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004073 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004074 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004075 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004076 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4077 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004078 return true;
4079 }
4080
4081 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004082 // class type, and "cv1 T1" is reference-compatible with
4083 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004084 // following ways (the choice is implementation-defined):
4085 //
4086 // -- The reference is bound to the object represented by
4087 // the rvalue (see 3.10) or to a sub-object within that
4088 // object.
4089 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004090 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004091 // a constructor is called to copy the entire rvalue
4092 // object into the temporary. The reference is bound to
4093 // the temporary or to a sub-object within the
4094 // temporary.
4095 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004096 // The constructor that would be used to make the copy
4097 // shall be callable whether or not the copy is actually
4098 // done.
4099 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004100 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004101 // freedom, so we will always take the first option and never build
4102 // a temporary in this case. FIXME: We will, however, have to check
4103 // for the presence of a copy constructor in C++98/03 mode.
4104 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004105 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4106 if (ICS) {
4107 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4108 ICS->Standard.First = ICK_Identity;
4109 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4110 ICS->Standard.Third = ICK_Identity;
4111 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4112 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004113 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004114 ICS->Standard.DirectBinding = false;
4115 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004116 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004117 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004118 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4119 if (DerivedToBase)
4120 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004121 else if(CheckExceptionSpecCompatibility(Init, T1))
4122 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004123 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004124 }
4125 return false;
4126 }
4127
Eli Friedman44b83ee2009-08-05 19:21:58 +00004128 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004129 // initialized from the initializer expression using the
4130 // rules for a non-reference copy initialization (8.5). The
4131 // reference is then bound to the temporary. If T1 is
4132 // reference-related to T2, cv1 must be the same
4133 // cv-qualification as, or greater cv-qualification than,
4134 // cv2; otherwise, the program is ill-formed.
4135 if (RefRelationship == Ref_Related) {
4136 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4137 // we would be reference-compatible or reference-compatible with
4138 // added qualification. But that wasn't the case, so the reference
4139 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004140 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004141 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004142 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4143 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004144 return true;
4145 }
4146
Douglas Gregor576e98c2009-01-30 23:27:23 +00004147 // If at least one of the types is a class type, the types are not
4148 // related, and we aren't allowed any user conversions, the
4149 // reference binding fails. This case is important for breaking
4150 // recursion, since TryImplicitConversion below will attempt to
4151 // create a temporary through the use of a copy constructor.
4152 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4153 (T1->isRecordType() || T2->isRecordType())) {
4154 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004155 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00004156 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4157 return true;
4158 }
4159
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004160 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004161 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004162 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004163 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004164 // When a parameter of reference type is not bound directly to
4165 // an argument expression, the conversion sequence is the one
4166 // required to convert the argument expression to the
4167 // underlying type of the reference according to
4168 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4169 // to copy-initializing a temporary of the underlying type with
4170 // the argument expression. Any difference in top-level
4171 // cv-qualification is subsumed by the initialization itself
4172 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004173 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4174 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004175 /*ForceRValue=*/false,
4176 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004177
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004178 // Of course, that's still a reference binding.
4179 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4180 ICS->Standard.ReferenceBinding = true;
4181 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004182 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004183 ImplicitConversionSequence::UserDefinedConversion) {
4184 ICS->UserDefined.After.ReferenceBinding = true;
4185 ICS->UserDefined.After.RRefBinding = isRValRef;
4186 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004187 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4188 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004189 ImplicitConversionSequence Conversions;
4190 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4191 false, false,
4192 Conversions);
4193 if (badConversion) {
4194 if ((Conversions.ConversionKind ==
4195 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004196 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004197 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004198 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4199 for (int j = Conversions.ConversionFunctionSet.size()-1;
4200 j >= 0; j--) {
4201 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4202 Diag(Func->getLocation(), diag::err_ovl_candidate);
4203 }
4204 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004205 else {
4206 if (isRValRef)
4207 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4208 << Init->getSourceRange();
4209 else
4210 Diag(DeclLoc, diag::err_invalid_initialization)
4211 << DeclType << Init->getType() << Init->getSourceRange();
4212 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004213 }
4214 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004215 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004216}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004217
4218/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4219/// of this overloaded operator is well-formed. If so, returns false;
4220/// otherwise, emits appropriate diagnostics and returns true.
4221bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004222 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004223 "Expected an overloaded operator declaration");
4224
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004225 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4226
Mike Stump11289f42009-09-09 15:08:12 +00004227 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004228 // The allocation and deallocation functions, operator new,
4229 // operator new[], operator delete and operator delete[], are
4230 // described completely in 3.7.3. The attributes and restrictions
4231 // found in the rest of this subclause do not apply to them unless
4232 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004233 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004234 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004235 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004236
4237 if (Op == OO_New || Op == OO_Array_New) {
4238 bool ret = false;
4239 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4240 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4241 QualType T = Context.getCanonicalType((*Param)->getType());
4242 if (!T->isDependentType() && SizeTy != T) {
4243 Diag(FnDecl->getLocation(),
4244 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4245 << SizeTy;
4246 ret = true;
4247 }
4248 }
4249 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4250 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4251 return Diag(FnDecl->getLocation(),
4252 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004253 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004254 return ret;
4255 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004256
4257 // C++ [over.oper]p6:
4258 // An operator function shall either be a non-static member
4259 // function or be a non-member function and have at least one
4260 // parameter whose type is a class, a reference to a class, an
4261 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004262 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4263 if (MethodDecl->isStatic())
4264 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004265 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004266 } else {
4267 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004268 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4269 ParamEnd = FnDecl->param_end();
4270 Param != ParamEnd; ++Param) {
4271 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004272 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4273 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004274 ClassOrEnumParam = true;
4275 break;
4276 }
4277 }
4278
Douglas Gregord69246b2008-11-17 16:14:12 +00004279 if (!ClassOrEnumParam)
4280 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004281 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004282 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004283 }
4284
4285 // C++ [over.oper]p8:
4286 // An operator function cannot have default arguments (8.3.6),
4287 // except where explicitly stated below.
4288 //
Mike Stump11289f42009-09-09 15:08:12 +00004289 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004290 // (C++ [over.call]p1).
4291 if (Op != OO_Call) {
4292 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4293 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004294 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004295 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004296 diag::err_operator_overload_default_arg)
4297 << FnDecl->getDeclName();
4298 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004299 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004300 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004301 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004302 }
4303 }
4304
Douglas Gregor6cf08062008-11-10 13:38:07 +00004305 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4306 { false, false, false }
4307#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4308 , { Unary, Binary, MemberOnly }
4309#include "clang/Basic/OperatorKinds.def"
4310 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004311
Douglas Gregor6cf08062008-11-10 13:38:07 +00004312 bool CanBeUnaryOperator = OperatorUses[Op][0];
4313 bool CanBeBinaryOperator = OperatorUses[Op][1];
4314 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004315
4316 // C++ [over.oper]p8:
4317 // [...] Operator functions cannot have more or fewer parameters
4318 // than the number required for the corresponding operator, as
4319 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004320 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004321 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004322 if (Op != OO_Call &&
4323 ((NumParams == 1 && !CanBeUnaryOperator) ||
4324 (NumParams == 2 && !CanBeBinaryOperator) ||
4325 (NumParams < 1) || (NumParams > 2))) {
4326 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004327 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004328 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004329 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004330 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004331 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004332 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004333 assert(CanBeBinaryOperator &&
4334 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004335 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004336 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004337
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004338 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004339 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004340 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004341
Douglas Gregord69246b2008-11-17 16:14:12 +00004342 // Overloaded operators other than operator() cannot be variadic.
4343 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004344 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004345 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004346 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004347 }
4348
4349 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004350 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4351 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004352 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004353 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004354 }
4355
4356 // C++ [over.inc]p1:
4357 // The user-defined function called operator++ implements the
4358 // prefix and postfix ++ operator. If this function is a member
4359 // function with no parameters, or a non-member function with one
4360 // parameter of class or enumeration type, it defines the prefix
4361 // increment operator ++ for objects of that type. If the function
4362 // is a member function with one parameter (which shall be of type
4363 // int) or a non-member function with two parameters (the second
4364 // of which shall be of type int), it defines the postfix
4365 // increment operator ++ for objects of that type.
4366 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4367 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4368 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004369 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004370 ParamIsInt = BT->getKind() == BuiltinType::Int;
4371
Chris Lattner2b786902008-11-21 07:50:02 +00004372 if (!ParamIsInt)
4373 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004374 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004375 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004376 }
4377
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004378 // Notify the class if it got an assignment operator.
4379 if (Op == OO_Equal) {
4380 // Would have returned earlier otherwise.
4381 assert(isa<CXXMethodDecl>(FnDecl) &&
4382 "Overloaded = not member, but not filtered.");
4383 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4384 Method->getParent()->addedAssignmentOperator(Context, Method);
4385 }
4386
Douglas Gregord69246b2008-11-17 16:14:12 +00004387 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004388}
Chris Lattner3b024a32008-12-17 07:09:26 +00004389
Douglas Gregor07665a62009-01-05 19:45:36 +00004390/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4391/// linkage specification, including the language and (if present)
4392/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4393/// the location of the language string literal, which is provided
4394/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4395/// the '{' brace. Otherwise, this linkage specification does not
4396/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004397Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4398 SourceLocation ExternLoc,
4399 SourceLocation LangLoc,
4400 const char *Lang,
4401 unsigned StrSize,
4402 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004403 LinkageSpecDecl::LanguageIDs Language;
4404 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4405 Language = LinkageSpecDecl::lang_c;
4406 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4407 Language = LinkageSpecDecl::lang_cxx;
4408 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004409 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004410 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004411 }
Mike Stump11289f42009-09-09 15:08:12 +00004412
Chris Lattner438e5012008-12-17 07:13:27 +00004413 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004414
Douglas Gregor07665a62009-01-05 19:45:36 +00004415 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004416 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004417 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004418 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004419 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004420 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004421}
4422
Douglas Gregor07665a62009-01-05 19:45:36 +00004423/// ActOnFinishLinkageSpecification - Completely the definition of
4424/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4425/// valid, it's the position of the closing '}' brace in a linkage
4426/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004427Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4428 DeclPtrTy LinkageSpec,
4429 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004430 if (LinkageSpec)
4431 PopDeclContext();
4432 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004433}
4434
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004435/// \brief Perform semantic analysis for the variable declaration that
4436/// occurs within a C++ catch clause, returning the newly-created
4437/// variable.
4438VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00004439 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004440 IdentifierInfo *Name,
4441 SourceLocation Loc,
4442 SourceRange Range) {
4443 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004444
4445 // Arrays and functions decay.
4446 if (ExDeclType->isArrayType())
4447 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4448 else if (ExDeclType->isFunctionType())
4449 ExDeclType = Context.getPointerType(ExDeclType);
4450
4451 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4452 // The exception-declaration shall not denote a pointer or reference to an
4453 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004454 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004455 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004456 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004457 Invalid = true;
4458 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004459
Sebastian Redl54c04d42008-12-22 19:15:10 +00004460 QualType BaseType = ExDeclType;
4461 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004462 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004463 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004464 BaseType = Ptr->getPointeeType();
4465 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004466 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004467 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004468 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004469 BaseType = Ref->getPointeeType();
4470 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004471 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004472 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004473 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004474 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004475 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004476
Mike Stump11289f42009-09-09 15:08:12 +00004477 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004478 RequireNonAbstractType(Loc, ExDeclType,
4479 diag::err_abstract_type_in_decl,
4480 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004481 Invalid = true;
4482
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004483 // FIXME: Need to test for ability to copy-construct and destroy the
4484 // exception variable.
4485
Sebastian Redl9b244a82008-12-22 21:35:02 +00004486 // FIXME: Need to check for abstract classes.
4487
Mike Stump11289f42009-09-09 15:08:12 +00004488 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCallbcd03502009-12-07 02:54:59 +00004489 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004490
4491 if (Invalid)
4492 ExDecl->setInvalidDecl();
4493
4494 return ExDecl;
4495}
4496
4497/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4498/// handler.
4499Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00004500 TypeSourceInfo *TInfo = 0;
4501 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004502
4503 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004504 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004505 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004506 // The scope should be freshly made just for us. There is just no way
4507 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004508 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004509 if (PrevDecl->isTemplateParameter()) {
4510 // Maybe we will complain about the shadowed template parameter.
4511 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004512 }
4513 }
4514
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004515 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004516 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4517 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004518 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004519 }
4520
John McCallbcd03502009-12-07 02:54:59 +00004521 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004522 D.getIdentifier(),
4523 D.getIdentifierLoc(),
4524 D.getDeclSpec().getSourceRange());
4525
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004526 if (Invalid)
4527 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004528
Sebastian Redl54c04d42008-12-22 19:15:10 +00004529 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004530 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004531 PushOnScopeChains(ExDecl, S);
4532 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004533 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004534
Douglas Gregor758a8692009-06-17 21:51:59 +00004535 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004536 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004537}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004538
Mike Stump11289f42009-09-09 15:08:12 +00004539Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004540 ExprArg assertexpr,
4541 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004542 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004543 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004544 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4545
Anders Carlsson54b26982009-03-14 00:33:21 +00004546 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4547 llvm::APSInt Value(32);
4548 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4549 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4550 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004551 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004552 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004553
Anders Carlsson54b26982009-03-14 00:33:21 +00004554 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004555 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004556 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004557 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004558 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004559 }
4560 }
Mike Stump11289f42009-09-09 15:08:12 +00004561
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004562 assertexpr.release();
4563 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004564 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004565 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004566
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004567 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004568 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004569}
Sebastian Redlf769df52009-03-24 22:27:57 +00004570
John McCall11083da2009-09-16 22:47:08 +00004571/// Handle a friend type declaration. This works in tandem with
4572/// ActOnTag.
4573///
4574/// Notes on friend class templates:
4575///
4576/// We generally treat friend class declarations as if they were
4577/// declaring a class. So, for example, the elaborated type specifier
4578/// in a friend declaration is required to obey the restrictions of a
4579/// class-head (i.e. no typedefs in the scope chain), template
4580/// parameters are required to match up with simple template-ids, &c.
4581/// However, unlike when declaring a template specialization, it's
4582/// okay to refer to a template specialization without an empty
4583/// template parameter declaration, e.g.
4584/// friend class A<T>::B<unsigned>;
4585/// We permit this as a special case; if there are any template
4586/// parameters present at all, require proper matching, i.e.
4587/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004588Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004589 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004590 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004591
4592 assert(DS.isFriendSpecified());
4593 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4594
John McCall11083da2009-09-16 22:47:08 +00004595 // Try to convert the decl specifier to a type. This works for
4596 // friend templates because ActOnTag never produces a ClassTemplateDecl
4597 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004598 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004599 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4600 if (TheDeclarator.isInvalidType())
4601 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004602
John McCall11083da2009-09-16 22:47:08 +00004603 // This is definitely an error in C++98. It's probably meant to
4604 // be forbidden in C++0x, too, but the specification is just
4605 // poorly written.
4606 //
4607 // The problem is with declarations like the following:
4608 // template <T> friend A<T>::foo;
4609 // where deciding whether a class C is a friend or not now hinges
4610 // on whether there exists an instantiation of A that causes
4611 // 'foo' to equal C. There are restrictions on class-heads
4612 // (which we declare (by fiat) elaborated friend declarations to
4613 // be) that makes this tractable.
4614 //
4615 // FIXME: handle "template <> friend class A<T>;", which
4616 // is possibly well-formed? Who even knows?
4617 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4618 Diag(Loc, diag::err_tagless_friend_type_template)
4619 << DS.getSourceRange();
4620 return DeclPtrTy();
4621 }
4622
John McCallaa74a0c2009-08-28 07:59:38 +00004623 // C++ [class.friend]p2:
4624 // An elaborated-type-specifier shall be used in a friend declaration
4625 // for a class.*
4626 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004627 // This is one of the rare places in Clang where it's legitimate to
4628 // ask about the "spelling" of the type.
4629 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4630 // If we evaluated the type to a record type, suggest putting
4631 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004632 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004633 RecordDecl *RD = RT->getDecl();
4634
4635 std::string InsertionText = std::string(" ") + RD->getKindName();
4636
John McCallc3987482009-10-07 23:34:25 +00004637 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4638 << (unsigned) RD->getTagKind()
4639 << T
4640 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004641 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4642 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004643 return DeclPtrTy();
4644 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004645 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4646 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004647 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004648 }
4649 }
4650
John McCallc3987482009-10-07 23:34:25 +00004651 // Enum types cannot be friends.
4652 if (T->getAs<EnumType>()) {
4653 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4654 << SourceRange(DS.getFriendSpecLoc());
4655 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004656 }
John McCallaa74a0c2009-08-28 07:59:38 +00004657
John McCallaa74a0c2009-08-28 07:59:38 +00004658 // C++98 [class.friend]p1: A friend of a class is a function
4659 // or class that is not a member of the class . . .
4660 // But that's a silly restriction which nobody implements for
4661 // inner classes, and C++0x removes it anyway, so we only report
4662 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004663 if (!getLangOptions().CPlusPlus0x)
4664 if (const RecordType *RT = T->getAs<RecordType>())
4665 if (RT->getDecl()->getDeclContext() == CurContext)
4666 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004667
John McCall11083da2009-09-16 22:47:08 +00004668 Decl *D;
4669 if (TempParams.size())
4670 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4671 TempParams.size(),
4672 (TemplateParameterList**) TempParams.release(),
4673 T.getTypePtr(),
4674 DS.getFriendSpecLoc());
4675 else
4676 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4677 DS.getFriendSpecLoc());
4678 D->setAccess(AS_public);
4679 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004680
John McCall11083da2009-09-16 22:47:08 +00004681 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004682}
4683
John McCall2f212b32009-09-11 21:02:39 +00004684Sema::DeclPtrTy
4685Sema::ActOnFriendFunctionDecl(Scope *S,
4686 Declarator &D,
4687 bool IsDefinition,
4688 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004689 const DeclSpec &DS = D.getDeclSpec();
4690
4691 assert(DS.isFriendSpecified());
4692 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4693
4694 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00004695 TypeSourceInfo *TInfo = 0;
4696 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00004697
4698 // C++ [class.friend]p1
4699 // A friend of a class is a function or class....
4700 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004701 // It *doesn't* see through dependent types, which is correct
4702 // according to [temp.arg.type]p3:
4703 // If a declaration acquires a function type through a
4704 // type dependent on a template-parameter and this causes
4705 // a declaration that does not use the syntactic form of a
4706 // function declarator to have a function type, the program
4707 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004708 if (!T->isFunctionType()) {
4709 Diag(Loc, diag::err_unexpected_friend);
4710
4711 // It might be worthwhile to try to recover by creating an
4712 // appropriate declaration.
4713 return DeclPtrTy();
4714 }
4715
4716 // C++ [namespace.memdef]p3
4717 // - If a friend declaration in a non-local class first declares a
4718 // class or function, the friend class or function is a member
4719 // of the innermost enclosing namespace.
4720 // - The name of the friend is not found by simple name lookup
4721 // until a matching declaration is provided in that namespace
4722 // scope (either before or after the class declaration granting
4723 // friendship).
4724 // - If a friend function is called, its name may be found by the
4725 // name lookup that considers functions from namespaces and
4726 // classes associated with the types of the function arguments.
4727 // - When looking for a prior declaration of a class or a function
4728 // declared as a friend, scopes outside the innermost enclosing
4729 // namespace scope are not considered.
4730
John McCallaa74a0c2009-08-28 07:59:38 +00004731 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4732 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004733 assert(Name);
4734
John McCall07e91c02009-08-06 02:15:43 +00004735 // The context we found the declaration in, or in which we should
4736 // create the declaration.
4737 DeclContext *DC;
4738
4739 // FIXME: handle local classes
4740
4741 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00004742 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4743 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00004744 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004745 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004746 DC = computeDeclContext(ScopeQual);
4747
4748 // FIXME: handle dependent contexts
4749 if (!DC) return DeclPtrTy();
4750
John McCall1f82f242009-11-18 22:49:29 +00004751 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004752
4753 // If searching in that context implicitly found a declaration in
4754 // a different context, treat it like it wasn't found at all.
4755 // TODO: better diagnostics for this case. Suggesting the right
4756 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00004757 // FIXME: getRepresentativeDecl() is not right here at all
4758 if (Previous.empty() ||
4759 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004760 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004761 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4762 return DeclPtrTy();
4763 }
4764
4765 // C++ [class.friend]p1: A friend of a class is a function or
4766 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004767 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004768 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4769
John McCall07e91c02009-08-06 02:15:43 +00004770 // Otherwise walk out to the nearest namespace scope looking for matches.
4771 } else {
4772 // TODO: handle local class contexts.
4773
4774 DC = CurContext;
4775 while (true) {
4776 // Skip class contexts. If someone can cite chapter and verse
4777 // for this behavior, that would be nice --- it's what GCC and
4778 // EDG do, and it seems like a reasonable intent, but the spec
4779 // really only says that checks for unqualified existing
4780 // declarations should stop at the nearest enclosing namespace,
4781 // not that they should only consider the nearest enclosing
4782 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004783 while (DC->isRecord())
4784 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004785
John McCall1f82f242009-11-18 22:49:29 +00004786 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004787
4788 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00004789 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00004790 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004791
John McCall07e91c02009-08-06 02:15:43 +00004792 if (DC->isFileContext()) break;
4793 DC = DC->getParent();
4794 }
4795
4796 // C++ [class.friend]p1: A friend of a class is a function or
4797 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004798 // C++0x changes this for both friend types and functions.
4799 // Most C++ 98 compilers do seem to give an error here, so
4800 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00004801 if (!Previous.empty() && DC->Equals(CurContext)
4802 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004803 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4804 }
4805
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004806 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004807 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004808 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4809 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4810 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004811 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004812 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4813 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004814 return DeclPtrTy();
4815 }
John McCall07e91c02009-08-06 02:15:43 +00004816 }
4817
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004818 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00004819 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004820 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004821 IsDefinition,
4822 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004823 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004824
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004825 assert(ND->getDeclContext() == DC);
4826 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004827
John McCall759e32b2009-08-31 22:39:49 +00004828 // Add the function declaration to the appropriate lookup tables,
4829 // adjusting the redeclarations list as necessary. We don't
4830 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004831 //
John McCall759e32b2009-08-31 22:39:49 +00004832 // Also update the scope-based lookup if the target context's
4833 // lookup context is in lexical scope.
4834 if (!CurContext->isDependentContext()) {
4835 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004836 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004837 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004838 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004839 }
John McCallaa74a0c2009-08-28 07:59:38 +00004840
4841 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004842 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004843 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004844 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004845 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004846
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004847 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004848}
4849
Chris Lattner83f095c2009-03-28 19:18:32 +00004850void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004851 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004852
Chris Lattner83f095c2009-03-28 19:18:32 +00004853 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004854 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4855 if (!Fn) {
4856 Diag(DelLoc, diag::err_deleted_non_function);
4857 return;
4858 }
4859 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4860 Diag(DelLoc, diag::err_deleted_decl_not_first);
4861 Diag(Prev->getLocation(), diag::note_previous_declaration);
4862 // If the declaration wasn't the first, we delete the function anyway for
4863 // recovery.
4864 }
4865 Fn->setDeleted();
4866}
Sebastian Redl4c018662009-04-27 21:33:24 +00004867
4868static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4869 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4870 ++CI) {
4871 Stmt *SubStmt = *CI;
4872 if (!SubStmt)
4873 continue;
4874 if (isa<ReturnStmt>(SubStmt))
4875 Self.Diag(SubStmt->getSourceRange().getBegin(),
4876 diag::err_return_in_constructor_handler);
4877 if (!isa<Expr>(SubStmt))
4878 SearchForReturnInStmt(Self, SubStmt);
4879 }
4880}
4881
4882void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4883 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4884 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4885 SearchForReturnInStmt(*this, Handler);
4886 }
4887}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004888
Mike Stump11289f42009-09-09 15:08:12 +00004889bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004890 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004891 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4892 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004893
4894 QualType CNewTy = Context.getCanonicalType(NewTy);
4895 QualType COldTy = Context.getCanonicalType(OldTy);
4896
Mike Stump11289f42009-09-09 15:08:12 +00004897 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004898 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004899 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004900
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004901 // Check if the return types are covariant
4902 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004903
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004904 /// Both types must be pointers or references to classes.
4905 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4906 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4907 NewClassTy = NewPT->getPointeeType();
4908 OldClassTy = OldPT->getPointeeType();
4909 }
4910 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4911 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4912 NewClassTy = NewRT->getPointeeType();
4913 OldClassTy = OldRT->getPointeeType();
4914 }
4915 }
Mike Stump11289f42009-09-09 15:08:12 +00004916
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004917 // The return types aren't either both pointers or references to a class type.
4918 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004919 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004920 diag::err_different_return_type_for_overriding_virtual_function)
4921 << New->getDeclName() << NewTy << OldTy;
4922 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004923
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004924 return true;
4925 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004926
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004927 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004928 // Check if the new class derives from the old class.
4929 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4930 Diag(New->getLocation(),
4931 diag::err_covariant_return_not_derived)
4932 << New->getDeclName() << NewTy << OldTy;
4933 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4934 return true;
4935 }
Mike Stump11289f42009-09-09 15:08:12 +00004936
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004937 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004938 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004939 diag::err_covariant_return_inaccessible_base,
4940 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4941 // FIXME: Should this point to the return type?
4942 New->getLocation(), SourceRange(), New->getDeclName())) {
4943 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4944 return true;
4945 }
4946 }
Mike Stump11289f42009-09-09 15:08:12 +00004947
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004948 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004949 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004950 Diag(New->getLocation(),
4951 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004952 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004953 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4954 return true;
4955 };
Mike Stump11289f42009-09-09 15:08:12 +00004956
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004957
4958 // The new class type must have the same or less qualifiers as the old type.
4959 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4960 Diag(New->getLocation(),
4961 diag::err_covariant_return_type_class_type_more_qualified)
4962 << New->getDeclName() << NewTy << OldTy;
4963 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4964 return true;
4965 };
Mike Stump11289f42009-09-09 15:08:12 +00004966
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004967 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004968}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004969
Alexis Hunt96d5c762009-11-21 08:43:09 +00004970bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4971 const CXXMethodDecl *Old)
4972{
4973 if (Old->hasAttr<FinalAttr>()) {
4974 Diag(New->getLocation(), diag::err_final_function_overridden)
4975 << New->getDeclName();
4976 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4977 return true;
4978 }
4979
4980 return false;
4981}
4982
Douglas Gregor21920e372009-12-01 17:24:26 +00004983/// \brief Mark the given method pure.
4984///
4985/// \param Method the method to be marked pure.
4986///
4987/// \param InitRange the source range that covers the "0" initializer.
4988bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
4989 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
4990 Method->setPure();
4991
4992 // A class is abstract if at least one function is pure virtual.
4993 Method->getParent()->setAbstract(true);
4994 return false;
4995 }
4996
4997 if (!Method->isInvalidDecl())
4998 Diag(Method->getLocation(), diag::err_non_virtual_pure)
4999 << Method->getDeclName() << InitRange;
5000 return true;
5001}
5002
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005003/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5004/// initializer for the declaration 'Dcl'.
5005/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5006/// static data member of class X, names should be looked up in the scope of
5007/// class X.
5008void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005009 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005010
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005011 Decl *D = Dcl.getAs<Decl>();
5012 // If there is no declaration, there was an error parsing it.
5013 if (D == 0)
5014 return;
5015
5016 // Check whether it is a declaration with a nested name specifier like
5017 // int foo::bar;
5018 if (!D->isOutOfLine())
5019 return;
Mike Stump11289f42009-09-09 15:08:12 +00005020
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005021 // C++ [basic.lookup.unqual]p13
5022 //
5023 // A name used in the definition of a static data member of class X
5024 // (after the qualified-id of the static member) is looked up as if the name
5025 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00005026
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005027 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00005028 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005029}
5030
5031/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5032/// initializer for the declaration 'Dcl'.
5033void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005034 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005035
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005036 Decl *D = Dcl.getAs<Decl>();
5037 // If there is no declaration, there was an error parsing it.
5038 if (D == 0)
5039 return;
5040
5041 // Check whether it is a declaration with a nested name specifier like
5042 // int foo::bar;
5043 if (!D->isOutOfLine())
5044 return;
5045
5046 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00005047 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005048}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005049
5050/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5051/// C++ if/switch/while/for statement.
5052/// e.g: "if (int x = f()) {...}"
5053Action::DeclResult
5054Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5055 // C++ 6.4p2:
5056 // The declarator shall not specify a function or an array.
5057 // The type-specifier-seq shall not contain typedef and shall not declare a
5058 // new class or enumeration.
5059 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5060 "Parser allowed 'typedef' as storage class of condition decl.");
5061
John McCallbcd03502009-12-07 02:54:59 +00005062 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005063 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005064 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005065
5066 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5067 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5068 // would be created and CXXConditionDeclExpr wants a VarDecl.
5069 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5070 << D.getSourceRange();
5071 return DeclResult();
5072 } else if (OwnedTag && OwnedTag->isDefinition()) {
5073 // The type-specifier-seq shall not declare a new class or enumeration.
5074 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5075 }
5076
5077 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5078 if (!Dcl)
5079 return DeclResult();
5080
5081 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5082 VD->setDeclaredInCondition(true);
5083 return Dcl;
5084}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005085
5086void Sema::MaybeMarkVirtualImplicitMembersReferenced(SourceLocation Loc,
5087 CXXMethodDecl *MD) {
5088 // Ignore dependent types.
5089 if (MD->isDependentContext())
5090 return;
5091
5092 CXXRecordDecl *RD = MD->getParent();
5093 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5094 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
5095
5096 if (!KeyFunction) {
5097 // This record does not have a key function, so we assume that the vtable
5098 // will be emitted when it's used by the constructor.
5099 if (!isa<CXXConstructorDecl>(MD))
5100 return;
5101 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5102 // We don't have the right key function.
5103 return;
5104 }
5105
5106 if (CXXDestructorDecl *Dtor = RD->getDestructor(Context)) {
5107 if (Dtor->isImplicit() && Dtor->isVirtual())
5108 MarkDeclarationReferenced(Loc, Dtor);
5109 }
5110
5111 // FIXME: Need to handle the virtual assignment operator here too.
5112}