blob: 6f8a4f16d3bd7bbd6005207c6c136c041e5d1dca [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:
John McCall3969e302009-12-08 07:46:18 +00002892 // C++0x inherited constructors.
2893 if (getLangOptions().CPlusPlus0x) break;
2894
Douglas Gregor220f4272009-11-04 16:30:06 +00002895 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2896 << SS.getRange();
2897 return DeclPtrTy();
2898
2899 case UnqualifiedId::IK_DestructorName:
2900 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2901 << SS.getRange();
2902 return DeclPtrTy();
2903
2904 case UnqualifiedId::IK_TemplateId:
2905 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2906 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2907 return DeclPtrTy();
2908 }
2909
2910 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00002911 if (!TargetName)
2912 return DeclPtrTy();
2913
John McCall3f746822009-11-17 05:59:44 +00002914 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002915 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002916 TargetName, AttrList,
2917 /* IsInstantiation */ false,
2918 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00002919 if (UD)
2920 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00002921
Anders Carlsson696a3f12009-08-28 05:40:36 +00002922 return DeclPtrTy::make(UD);
2923}
2924
John McCall3f746822009-11-17 05:59:44 +00002925/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00002926UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
2927 AccessSpecifier AS,
2928 UsingDecl *UD,
2929 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00002930 // FIXME: diagnose hiding, collisions
2931
2932 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00002933 NamedDecl *Target = Orig;
2934 if (isa<UsingShadowDecl>(Target)) {
2935 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
2936 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00002937 }
2938
2939 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00002940 = UsingShadowDecl::Create(Context, CurContext,
2941 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00002942 UD->addShadowDecl(Shadow);
2943
2944 if (S)
John McCall3969e302009-12-08 07:46:18 +00002945 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00002946 else
John McCall3969e302009-12-08 07:46:18 +00002947 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00002948 Shadow->setAccess(AS);
2949
John McCall3969e302009-12-08 07:46:18 +00002950 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
2951 Shadow->setInvalidDecl();
2952
2953 // If we haven't already declared the shadow decl invalid, check
2954 // whether the decl comes from a base class of the current class.
2955 // We don't have to do this in C++0x because we do the check once on
2956 // the qualifier.
2957 else if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
2958 DeclContext *OrigDC = Orig->getDeclContext();
2959
2960 // Handle enums and anonymous structs.
2961 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
2962 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
2963 while (OrigRec->isAnonymousStructOrUnion())
2964 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
2965
2966 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
2967 if (OrigDC == CurContext) {
2968 Diag(UD->getLocation(),
2969 diag::err_using_decl_nested_name_specifier_is_current_class)
2970 << UD->getNestedNameRange();
2971 Diag(Orig->getLocation(), diag::note_using_decl_target);
2972 Shadow->setInvalidDecl();
2973 return Shadow;
2974 }
2975
2976 Diag(UD->getNestedNameRange().getBegin(),
2977 diag::err_using_decl_nested_name_specifier_is_not_base_class)
2978 << UD->getTargetNestedNameDecl()
2979 << cast<CXXRecordDecl>(CurContext)
2980 << UD->getNestedNameRange();
2981 Diag(Orig->getLocation(), diag::note_using_decl_target);
2982 return Shadow;
2983 }
2984 }
2985
John McCall3f746822009-11-17 05:59:44 +00002986 return Shadow;
2987}
2988
John McCalle61f2ba2009-11-18 02:36:19 +00002989/// Builds a using declaration.
2990///
2991/// \param IsInstantiation - Whether this call arises from an
2992/// instantiation of an unresolved using declaration. We treat
2993/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00002994NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2995 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002996 const CXXScopeSpec &SS,
2997 SourceLocation IdentLoc,
2998 DeclarationName Name,
2999 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003000 bool IsInstantiation,
3001 bool IsTypeName,
3002 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003003 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3004 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003005
Anders Carlssonf038fc22009-08-28 05:49:21 +00003006 // FIXME: We ignore attributes for now.
3007 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003008
Anders Carlsson59140b32009-08-28 03:16:11 +00003009 if (SS.isEmpty()) {
3010 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003011 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003012 }
Mike Stump11289f42009-09-09 15:08:12 +00003013
3014 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003015 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3016
John McCallb96ec562009-12-04 22:46:56 +00003017 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3018 return 0;
3019
John McCall84c16cf2009-11-12 03:15:40 +00003020 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003021 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003022 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003023 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003024 // FIXME: not all declaration name kinds are legal here
3025 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3026 UsingLoc, TypenameLoc,
3027 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003028 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003029 } else {
3030 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3031 UsingLoc, SS.getRange(), NNS,
3032 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003033 }
John McCallb96ec562009-12-04 22:46:56 +00003034 } else {
3035 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3036 SS.getRange(), UsingLoc, NNS, Name,
3037 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003038 }
John McCallb96ec562009-12-04 22:46:56 +00003039 D->setAccess(AS);
3040 CurContext->addDecl(D);
3041
3042 if (!LookupContext) return D;
3043 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003044
John McCall3969e302009-12-08 07:46:18 +00003045 if (RequireCompleteDeclContext(SS)) {
3046 UD->setInvalidDecl();
3047 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003048 }
3049
John McCall3969e302009-12-08 07:46:18 +00003050 // Look up the target name.
3051
John McCall27b18f82009-11-17 02:14:36 +00003052 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003053
John McCall3969e302009-12-08 07:46:18 +00003054 // Unlike most lookups, we don't always want to hide tag
3055 // declarations: tag names are visible through the using declaration
3056 // even if hidden by ordinary names, *except* in a dependent context
3057 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003058 if (!IsInstantiation)
3059 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003060
John McCall27b18f82009-11-17 02:14:36 +00003061 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003062
John McCall9f3059a2009-10-09 21:13:30 +00003063 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003064 Diag(IdentLoc, diag::err_no_member)
3065 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003066 UD->setInvalidDecl();
3067 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003068 }
3069
John McCallb96ec562009-12-04 22:46:56 +00003070 if (R.isAmbiguous()) {
3071 UD->setInvalidDecl();
3072 return UD;
3073 }
Mike Stump11289f42009-09-09 15:08:12 +00003074
John McCalle61f2ba2009-11-18 02:36:19 +00003075 if (IsTypeName) {
3076 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003077 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003078 Diag(IdentLoc, diag::err_using_typename_non_type);
3079 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3080 Diag((*I)->getUnderlyingDecl()->getLocation(),
3081 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003082 UD->setInvalidDecl();
3083 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003084 }
3085 } else {
3086 // If we asked for a non-typename and we got a type, error out,
3087 // but only if this is an instantiation of an unresolved using
3088 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003089 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003090 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3091 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003092 UD->setInvalidDecl();
3093 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003094 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003095 }
3096
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003097 // C++0x N2914 [namespace.udecl]p6:
3098 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003099 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003100 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3101 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003102 UD->setInvalidDecl();
3103 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003104 }
Mike Stump11289f42009-09-09 15:08:12 +00003105
John McCall3f746822009-11-17 05:59:44 +00003106 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
John McCall3969e302009-12-08 07:46:18 +00003107 BuildUsingShadowDecl(S, AS, UD, *I);
John McCall3f746822009-11-17 05:59:44 +00003108
3109 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003110}
3111
John McCall3969e302009-12-08 07:46:18 +00003112
John McCallb96ec562009-12-04 22:46:56 +00003113/// Checks that the given nested-name qualifier used in a using decl
3114/// in the current context is appropriately related to the current
3115/// scope. If an error is found, diagnoses it and returns true.
3116bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3117 const CXXScopeSpec &SS,
3118 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003119 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003120
John McCall3969e302009-12-08 07:46:18 +00003121 if (!CurContext->isRecord()) {
3122 // C++03 [namespace.udecl]p3:
3123 // C++0x [namespace.udecl]p8:
3124 // A using-declaration for a class member shall be a member-declaration.
3125
3126 // If we weren't able to compute a valid scope, it must be a
3127 // dependent class scope.
3128 if (!NamedContext || NamedContext->isRecord()) {
3129 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3130 << SS.getRange();
3131 return true;
3132 }
3133
3134 // Otherwise, everything is known to be fine.
3135 return false;
3136 }
3137
3138 // The current scope is a record.
3139
3140 // If the named context is dependent, we can't decide much.
3141 if (!NamedContext) {
3142 // FIXME: in C++0x, we can diagnose if we can prove that the
3143 // nested-name-specifier does not refer to a base class, which is
3144 // still possible in some cases.
3145
3146 // Otherwise we have to conservatively report that things might be
3147 // okay.
3148 return false;
3149 }
3150
3151 if (!NamedContext->isRecord()) {
3152 // Ideally this would point at the last name in the specifier,
3153 // but we don't have that level of source info.
3154 Diag(SS.getRange().getBegin(),
3155 diag::err_using_decl_nested_name_specifier_is_not_class)
3156 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3157 return true;
3158 }
3159
3160 if (getLangOptions().CPlusPlus0x) {
3161 // C++0x [namespace.udecl]p3:
3162 // In a using-declaration used as a member-declaration, the
3163 // nested-name-specifier shall name a base class of the class
3164 // being defined.
3165
3166 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3167 cast<CXXRecordDecl>(NamedContext))) {
3168 if (CurContext == NamedContext) {
3169 Diag(NameLoc,
3170 diag::err_using_decl_nested_name_specifier_is_current_class)
3171 << SS.getRange();
3172 return true;
3173 }
3174
3175 Diag(SS.getRange().getBegin(),
3176 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3177 << (NestedNameSpecifier*) SS.getScopeRep()
3178 << cast<CXXRecordDecl>(CurContext)
3179 << SS.getRange();
3180 return true;
3181 }
3182
3183 return false;
3184 }
3185
3186 // C++03 [namespace.udecl]p4:
3187 // A using-declaration used as a member-declaration shall refer
3188 // to a member of a base class of the class being defined [etc.].
3189
3190 // Salient point: SS doesn't have to name a base class as long as
3191 // lookup only finds members from base classes. Therefore we can
3192 // diagnose here only if we can prove that that can't happen,
3193 // i.e. if the class hierarchies provably don't intersect.
3194
3195 // TODO: it would be nice if "definitely valid" results were cached
3196 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3197 // need to be repeated.
3198
3199 struct UserData {
3200 llvm::DenseSet<const CXXRecordDecl*> Bases;
3201
3202 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3203 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3204 Data->Bases.insert(Base);
3205 return true;
3206 }
3207
3208 bool hasDependentBases(const CXXRecordDecl *Class) {
3209 return !Class->forallBases(collect, this);
3210 }
3211
3212 /// Returns true if the base is dependent or is one of the
3213 /// accumulated base classes.
3214 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3215 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3216 return !Data->Bases.count(Base);
3217 }
3218
3219 bool mightShareBases(const CXXRecordDecl *Class) {
3220 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3221 }
3222 };
3223
3224 UserData Data;
3225
3226 // Returns false if we find a dependent base.
3227 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3228 return false;
3229
3230 // Returns false if the class has a dependent base or if it or one
3231 // of its bases is present in the base set of the current context.
3232 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3233 return false;
3234
3235 Diag(SS.getRange().getBegin(),
3236 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3237 << (NestedNameSpecifier*) SS.getScopeRep()
3238 << cast<CXXRecordDecl>(CurContext)
3239 << SS.getRange();
3240
3241 return true;
John McCallb96ec562009-12-04 22:46:56 +00003242}
3243
Mike Stump11289f42009-09-09 15:08:12 +00003244Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003245 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003246 SourceLocation AliasLoc,
3247 IdentifierInfo *Alias,
3248 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003249 SourceLocation IdentLoc,
3250 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003251
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003252 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003253 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3254 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003255
Anders Carlssondca83c42009-03-28 06:23:46 +00003256 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003257 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003258 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003259 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003260 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003261 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003262 if (!R.isAmbiguous() && !R.empty() &&
3263 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003264 return DeclPtrTy();
3265 }
Mike Stump11289f42009-09-09 15:08:12 +00003266
Anders Carlssondca83c42009-03-28 06:23:46 +00003267 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3268 diag::err_redefinition_different_kind;
3269 Diag(AliasLoc, DiagID) << Alias;
3270 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003271 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003272 }
3273
John McCall27b18f82009-11-17 02:14:36 +00003274 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003275 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003276
John McCall9f3059a2009-10-09 21:13:30 +00003277 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003278 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003279 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003280 }
Mike Stump11289f42009-09-09 15:08:12 +00003281
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003282 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003283 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3284 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003285 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003286 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003287
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003288 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003289 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003290}
3291
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003292void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3293 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003294 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3295 !Constructor->isUsed()) &&
3296 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003297
Eli Friedman9cf6b592009-11-09 19:20:36 +00003298 CXXRecordDecl *ClassDecl
3299 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3300 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003301
Eli Friedman9cf6b592009-11-09 19:20:36 +00003302 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003303 Diag(CurrentLocation, diag::note_member_synthesized_at)
3304 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003305 Constructor->setInvalidDecl();
3306 } else {
3307 Constructor->setUsed();
3308 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003309}
3310
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003311void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003312 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003313 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3314 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003315 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003316 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3317 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003318 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003319 // implicitly defined, all the implicitly-declared default destructors
3320 // for its base class and its non-static data members shall have been
3321 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003322 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3323 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003324 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003325 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003326 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003327 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003328 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3329 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3330 else
Mike Stump11289f42009-09-09 15:08:12 +00003331 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003332 "DefineImplicitDestructor - missing dtor in a base class");
3333 }
3334 }
Mike Stump11289f42009-09-09 15:08:12 +00003335
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003336 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3337 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003338 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3339 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3340 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003341 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003342 CXXRecordDecl *FieldClassDecl
3343 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3344 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003345 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003346 const_cast<CXXDestructorDecl*>(
3347 FieldClassDecl->getDestructor(Context)))
3348 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3349 else
Mike Stump11289f42009-09-09 15:08:12 +00003350 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003351 "DefineImplicitDestructor - missing dtor in class of a data member");
3352 }
3353 }
3354 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003355
3356 // FIXME: If CheckDestructor fails, we should emit a note about where the
3357 // implicit destructor was needed.
3358 if (CheckDestructor(Destructor)) {
3359 Diag(CurrentLocation, diag::note_member_synthesized_at)
3360 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3361
3362 Destructor->setInvalidDecl();
3363 return;
3364 }
3365
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003366 Destructor->setUsed();
3367}
3368
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003369void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3370 CXXMethodDecl *MethodDecl) {
3371 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3372 MethodDecl->getOverloadedOperator() == OO_Equal &&
3373 !MethodDecl->isUsed()) &&
3374 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003375
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003376 CXXRecordDecl *ClassDecl
3377 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003378
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003379 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003380 // Before the implicitly-declared copy assignment operator for a class is
3381 // implicitly defined, all implicitly-declared copy assignment operators
3382 // for its direct base classes and its nonstatic data members shall have
3383 // been implicitly defined.
3384 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003385 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3386 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003387 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003389 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003390 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3391 BaseClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003392 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3393 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003394 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3395 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003396 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3397 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3398 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003399 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003400 CXXRecordDecl *FieldClassDecl
3401 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003402 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003403 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3404 FieldClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003405 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003406 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003407 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003408 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3409 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003410 Diag(CurrentLocation, diag::note_first_required_here);
3411 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003412 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003413 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003414 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3415 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003416 Diag(CurrentLocation, diag::note_first_required_here);
3417 err = true;
3418 }
3419 }
3420 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003421 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003422}
3423
3424CXXMethodDecl *
Anders Carlssonefa47322009-12-09 03:01:51 +00003425Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3426 ParmVarDecl *ParmDecl,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003427 CXXRecordDecl *ClassDecl) {
3428 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3429 QualType RHSType(LHSType);
3430 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003431 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003432 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003433 RHSType = Context.getCVRQualifiedType(RHSType,
3434 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003435 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003436 LHSType,
3437 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003438 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003439 RHSType,
3440 CurrentLocation));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003441 Expr *Args[2] = { &*LHS, &*RHS };
3442 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003443 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003444 CandidateSet);
3445 OverloadCandidateSet::iterator Best;
Anders Carlssonefa47322009-12-09 03:01:51 +00003446 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003447 return cast<CXXMethodDecl>(Best->Function);
3448 assert(false &&
3449 "getAssignOperatorMethod - copy assignment operator method not found");
3450 return 0;
3451}
3452
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003453void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3454 CXXConstructorDecl *CopyConstructor,
3455 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003456 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003457 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3458 !CopyConstructor->isUsed()) &&
3459 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003460
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003461 CXXRecordDecl *ClassDecl
3462 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3463 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003464 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003465 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003466 // implicitly defined, all the implicitly-declared copy constructors
3467 // for its base class and its non-static data members shall have been
3468 // implicitly defined.
3469 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3470 Base != ClassDecl->bases_end(); ++Base) {
3471 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003472 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003473 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003474 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003475 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003476 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003477 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3478 FieldEnd = ClassDecl->field_end();
3479 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003480 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3481 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3482 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003483 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003484 CXXRecordDecl *FieldClassDecl
3485 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003486 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003487 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003488 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003489 }
3490 }
3491 CopyConstructor->setUsed();
3492}
3493
Anders Carlsson6eb55572009-08-25 05:12:04 +00003494Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003495Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003496 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003497 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003498 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003499
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003500 // C++ [class.copy]p15:
3501 // Whenever a temporary class object is copied using a copy constructor, and
3502 // this object and the copy have the same cv-unqualified type, an
3503 // implementation is permitted to treat the original and the copy as two
3504 // different ways of referring to the same object and not perform a copy at
3505 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003506
Anders Carlsson250aada2009-08-16 05:13:48 +00003507 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003508 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003509 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003510 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3511 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003512 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3513 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3514 E = ICE->getSubExpr();
Eli Friedmaneddf1212009-12-06 09:26:33 +00003515
3516 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3517 Elidable = !CE->getCallReturnType()->isReferenceType();
3518 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson250aada2009-08-16 05:13:48 +00003519 Elidable = true;
3520 }
Mike Stump11289f42009-09-09 15:08:12 +00003521
3522 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003523 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003524}
3525
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003526/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3527/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003528Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003529Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3530 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003531 MultiExprArg ExprArgs) {
3532 unsigned NumExprs = ExprArgs.size();
3533 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregor27381f32009-11-23 12:27:39 +00003535 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003536 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3537 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003538}
3539
Anders Carlsson574315a2009-08-27 05:08:22 +00003540Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003541Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3542 QualType Ty,
3543 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003544 MultiExprArg Args,
3545 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003546 unsigned NumExprs = Args.size();
3547 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003548
Douglas Gregor27381f32009-11-23 12:27:39 +00003549 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003550 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3551 TyBeginLoc, Exprs,
3552 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003553}
3554
3555
Mike Stump11289f42009-09-09 15:08:12 +00003556bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003557 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003558 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003559 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003560 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003561 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003562 if (TempResult.isInvalid())
3563 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003564
Anders Carlsson6eb55572009-08-25 05:12:04 +00003565 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003566 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003567 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003568 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003569
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003570 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003571}
3572
Mike Stump11289f42009-09-09 15:08:12 +00003573void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003574 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003575 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003576 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003577 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003578 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003579 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003580}
3581
Mike Stump11289f42009-09-09 15:08:12 +00003582/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003583/// ActOnDeclarator, when a C++ direct initializer is present.
3584/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003585void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3586 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003587 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003588 SourceLocation *CommaLocs,
3589 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003590 unsigned NumExprs = Exprs.size();
3591 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003592 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003593
3594 // If there is no declaration, there was an error parsing it. Just ignore
3595 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003596 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003597 return;
Mike Stump11289f42009-09-09 15:08:12 +00003598
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003599 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3600 if (!VDecl) {
3601 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3602 RealDecl->setInvalidDecl();
3603 return;
3604 }
3605
Douglas Gregor402250f2009-08-26 21:14:46 +00003606 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003607 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003608 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3609 //
3610 // Clients that want to distinguish between the two forms, can check for
3611 // direct initializer using VarDecl::hasCXXDirectInitializer().
3612 // A major benefit is that clients that don't particularly care about which
3613 // exactly form was it (like the CodeGen) can handle both cases without
3614 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003615
Douglas Gregor402250f2009-08-26 21:14:46 +00003616 // If either the declaration has a dependent type or if any of the expressions
3617 // is type-dependent, we represent the initialization via a ParenListExpr for
3618 // later use during template instantiation.
3619 if (VDecl->getType()->isDependentType() ||
3620 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3621 // Let clients know that initialization was done with a direct initializer.
3622 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003623
Douglas Gregor402250f2009-08-26 21:14:46 +00003624 // Store the initialization expressions as a ParenListExpr.
3625 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003626 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003627 new (Context) ParenListExpr(Context, LParenLoc,
3628 (Expr **)Exprs.release(),
3629 NumExprs, RParenLoc));
3630 return;
3631 }
Mike Stump11289f42009-09-09 15:08:12 +00003632
Douglas Gregor402250f2009-08-26 21:14:46 +00003633
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003634 // C++ 8.5p11:
3635 // The form of initialization (using parentheses or '=') is generally
3636 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003637 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003638 QualType DeclInitType = VDecl->getType();
3639 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003640 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003641
Douglas Gregor4044d992009-03-24 16:43:20 +00003642 // FIXME: This isn't the right place to complete the type.
3643 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3644 diag::err_typecheck_decl_incomplete_type)) {
3645 VDecl->setInvalidDecl();
3646 return;
3647 }
3648
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003649 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003650 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3651
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003652 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003653 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003654 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003655 VDecl->getLocation(),
3656 SourceRange(VDecl->getLocation(),
3657 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003658 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003659 IK_Direct,
3660 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003661 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003662 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003663 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003664 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003665 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003666 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003667 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003668 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003669 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003670 return;
3671 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003672
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003673 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003674 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3675 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003676 RealDecl->setInvalidDecl();
3677 return;
3678 }
3679
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003680 // Let clients know that initialization was done with a direct initializer.
3681 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003682
3683 assert(NumExprs == 1 && "Expected 1 expression");
3684 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003685 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3686 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003687}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003688
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003689/// \brief Add the applicable constructor candidates for an initialization
3690/// by constructor.
3691static void AddConstructorInitializationCandidates(Sema &SemaRef,
3692 QualType ClassType,
3693 Expr **Args,
3694 unsigned NumArgs,
3695 Sema::InitializationKind Kind,
3696 OverloadCandidateSet &CandidateSet) {
3697 // C++ [dcl.init]p14:
3698 // If the initialization is direct-initialization, or if it is
3699 // copy-initialization where the cv-unqualified version of the
3700 // source type is the same class as, or a derived class of, the
3701 // class of the destination, constructors are considered. The
3702 // applicable constructors are enumerated (13.3.1.3), and the
3703 // best one is chosen through overload resolution (13.3). The
3704 // constructor so selected is called to initialize the object,
3705 // with the initializer expression(s) as its argument(s). If no
3706 // constructor applies, or the overload resolution is ambiguous,
3707 // the initialization is ill-formed.
3708 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3709 assert(ClassRec && "Can only initialize a class type here");
3710
3711 // FIXME: When we decide not to synthesize the implicitly-declared
3712 // constructors, we'll need to make them appear here.
3713
3714 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3715 DeclarationName ConstructorName
3716 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3717 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3718 DeclContext::lookup_const_iterator Con, ConEnd;
3719 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3720 Con != ConEnd; ++Con) {
3721 // Find the constructor (which may be a template).
3722 CXXConstructorDecl *Constructor = 0;
3723 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3724 if (ConstructorTmpl)
3725 Constructor
3726 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3727 else
3728 Constructor = cast<CXXConstructorDecl>(*Con);
3729
3730 if ((Kind == Sema::IK_Direct) ||
3731 (Kind == Sema::IK_Copy &&
3732 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3733 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3734 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00003735 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3736 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003737 Args, NumArgs, CandidateSet);
3738 else
3739 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3740 }
3741 }
3742}
3743
3744/// \brief Attempt to perform initialization by constructor
3745/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3746/// copy-initialization.
3747///
3748/// This routine determines whether initialization by constructor is possible,
3749/// but it does not emit any diagnostics in the case where the initialization
3750/// is ill-formed.
3751///
3752/// \param ClassType the type of the object being initialized, which must have
3753/// class type.
3754///
3755/// \param Args the arguments provided to initialize the object
3756///
3757/// \param NumArgs the number of arguments provided to initialize the object
3758///
3759/// \param Kind the type of initialization being performed
3760///
3761/// \returns the constructor used to initialize the object, if successful.
3762/// Otherwise, emits a diagnostic and returns NULL.
3763CXXConstructorDecl *
3764Sema::TryInitializationByConstructor(QualType ClassType,
3765 Expr **Args, unsigned NumArgs,
3766 SourceLocation Loc,
3767 InitializationKind Kind) {
3768 // Build the overload candidate set
3769 OverloadCandidateSet CandidateSet;
3770 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3771 CandidateSet);
3772
3773 // Determine whether we found a constructor we can use.
3774 OverloadCandidateSet::iterator Best;
3775 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3776 case OR_Success:
3777 case OR_Deleted:
3778 // We found a constructor. Return it.
3779 return cast<CXXConstructorDecl>(Best->Function);
3780
3781 case OR_No_Viable_Function:
3782 case OR_Ambiguous:
3783 // Overload resolution failed. Return nothing.
3784 return 0;
3785 }
3786
3787 // Silence GCC warning
3788 return 0;
3789}
3790
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003791/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3792/// may occur as part of direct-initialization or copy-initialization.
3793///
3794/// \param ClassType the type of the object being initialized, which must have
3795/// class type.
3796///
3797/// \param ArgsPtr the arguments provided to initialize the object
3798///
3799/// \param Loc the source location where the initialization occurs
3800///
3801/// \param Range the source range that covers the entire initialization
3802///
3803/// \param InitEntity the name of the entity being initialized, if known
3804///
3805/// \param Kind the type of initialization being performed
3806///
3807/// \param ConvertedArgs a vector that will be filled in with the
3808/// appropriately-converted arguments to the constructor (if initialization
3809/// succeeded).
3810///
3811/// \returns the constructor used to initialize the object, if successful.
3812/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003813CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003814Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003815 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003816 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003817 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003818 InitializationKind Kind,
3819 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003820
3821 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003822 Expr **Args = (Expr **)ArgsPtr.get();
3823 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003824 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003825 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3826 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00003827
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003828 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003829 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003830 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003831 // We found a constructor. Break out so that we can convert the arguments
3832 // appropriately.
3833 break;
Mike Stump11289f42009-09-09 15:08:12 +00003834
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003835 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003836 if (InitEntity)
3837 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003838 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003839 else
3840 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003841 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003842 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003843 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003844
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003845 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003846 if (InitEntity)
3847 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3848 else
3849 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003850 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3851 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003852
3853 case OR_Deleted:
3854 if (InitEntity)
3855 Diag(Loc, diag::err_ovl_deleted_init)
3856 << Best->Function->isDeleted()
3857 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003858 else {
3859 const CXXRecordDecl *RD =
3860 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003861 Diag(Loc, diag::err_ovl_deleted_init)
3862 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003863 << RD->getDeclName() << Range;
3864 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00003865 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3866 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003867 }
Mike Stump11289f42009-09-09 15:08:12 +00003868
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003869 // Convert the arguments, fill in default arguments, etc.
3870 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3871 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3872 return 0;
3873
3874 return Constructor;
3875}
3876
3877/// \brief Given a constructor and the set of arguments provided for the
3878/// constructor, convert the arguments and add any required default arguments
3879/// to form a proper call to this constructor.
3880///
3881/// \returns true if an error occurred, false otherwise.
3882bool
3883Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3884 MultiExprArg ArgsPtr,
3885 SourceLocation Loc,
3886 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3887 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3888 unsigned NumArgs = ArgsPtr.size();
3889 Expr **Args = (Expr **)ArgsPtr.get();
3890
3891 const FunctionProtoType *Proto
3892 = Constructor->getType()->getAs<FunctionProtoType>();
3893 assert(Proto && "Constructor without a prototype?");
3894 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003895
3896 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003897 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003898 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003899 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003900 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003901
3902 VariadicCallType CallType =
3903 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3904 llvm::SmallVector<Expr *, 8> AllArgs;
3905 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3906 Proto, 0, Args, NumArgs, AllArgs,
3907 CallType);
3908 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3909 ConvertedArgs.push_back(AllArgs[i]);
3910 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003911}
3912
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003913/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3914/// determine whether they are reference-related,
3915/// reference-compatible, reference-compatible with added
3916/// qualification, or incompatible, for use in C++ initialization by
3917/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3918/// type, and the first type (T1) is the pointee type of the reference
3919/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003920Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003921Sema::CompareReferenceRelationship(SourceLocation Loc,
3922 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003923 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003924 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003925 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003926 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003927
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003928 QualType T1 = Context.getCanonicalType(OrigT1);
3929 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003930 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3931 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003932
3933 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003934 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003935 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003936 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003937 if (UnqualT1 == UnqualT2)
3938 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003939 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3940 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3941 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003942 DerivedToBase = true;
3943 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003944 return Ref_Incompatible;
3945
3946 // At this point, we know that T1 and T2 are reference-related (at
3947 // least).
3948
3949 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003950 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003951 // reference-related to T2 and cv1 is the same cv-qualification
3952 // as, or greater cv-qualification than, cv2. For purposes of
3953 // overload resolution, cases for which cv1 is greater
3954 // cv-qualification than cv2 are identified as
3955 // reference-compatible with added qualification (see 13.3.3.2).
3956 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3957 return Ref_Compatible;
3958 else if (T1.isMoreQualifiedThan(T2))
3959 return Ref_Compatible_With_Added_Qualification;
3960 else
3961 return Ref_Related;
3962}
3963
3964/// CheckReferenceInit - Check the initialization of a reference
3965/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3966/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003967/// list), and DeclType is the type of the declaration. When ICS is
3968/// non-null, this routine will compute the implicit conversion
3969/// sequence according to C++ [over.ics.ref] and will not produce any
3970/// diagnostics; when ICS is null, it will emit diagnostics when any
3971/// errors are found. Either way, a return value of true indicates
3972/// that there was a failure, a return value of false indicates that
3973/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003974///
3975/// When @p SuppressUserConversions, user-defined conversions are
3976/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003977/// When @p AllowExplicit, we also permit explicit user-defined
3978/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003979/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00003980/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3981/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00003982bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003983Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003984 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003985 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003986 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00003987 ImplicitConversionSequence *ICS,
3988 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003989 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3990
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003991 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003992 QualType T2 = Init->getType();
3993
Douglas Gregorcd695e52008-11-10 20:40:00 +00003994 // If the initializer is the address of an overloaded function, try
3995 // to resolve the overloaded function. If all goes well, T2 is the
3996 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003997 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003998 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003999 ICS != 0);
4000 if (Fn) {
4001 // Since we're performing this reference-initialization for
4002 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004003 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00004004 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004005 return true;
4006
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00004007 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004008 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004009
4010 T2 = Fn->getType();
4011 }
4012 }
4013
Douglas Gregor786ab212008-10-29 02:00:59 +00004014 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004015 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00004016 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00004017 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4018 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00004019 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004020 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00004021
4022 // Most paths end in a failed conversion.
4023 if (ICS)
4024 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004025
4026 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004027 // A reference to type "cv1 T1" is initialized by an expression
4028 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004029
4030 // -- If the initializer expression
4031
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004032 // Rvalue references cannot bind to lvalues (N2812).
4033 // There is absolutely no situation where they can. In particular, note that
4034 // this is ill-formed, even if B has a user-defined conversion to A&&:
4035 // B b;
4036 // A&& r = b;
4037 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4038 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004039 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004040 << Init->getSourceRange();
4041 return true;
4042 }
4043
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004044 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00004045 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4046 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00004047 //
4048 // Note that the bit-field check is skipped if we are just computing
4049 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00004050 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004051 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004052 BindsDirectly = true;
4053
Douglas Gregor786ab212008-10-29 02:00:59 +00004054 if (ICS) {
4055 // C++ [over.ics.ref]p1:
4056 // When a parameter of reference type binds directly (8.5.3)
4057 // to an argument expression, the implicit conversion sequence
4058 // is the identity conversion, unless the argument expression
4059 // has a type that is a derived class of the parameter type,
4060 // in which case the implicit conversion sequence is a
4061 // derived-to-base Conversion (13.3.3.1).
4062 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4063 ICS->Standard.First = ICK_Identity;
4064 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4065 ICS->Standard.Third = ICK_Identity;
4066 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4067 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004068 ICS->Standard.ReferenceBinding = true;
4069 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004070 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004071 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004072
4073 // Nothing more to do: the inaccessibility/ambiguity check for
4074 // derived-to-base conversions is suppressed when we're
4075 // computing the implicit conversion sequence (C++
4076 // [over.best.ics]p2).
4077 return false;
4078 } else {
4079 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004080 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4081 if (DerivedToBase)
4082 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004083 else if(CheckExceptionSpecCompatibility(Init, T1))
4084 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004085 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004086 }
4087 }
4088
4089 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00004090 // implicitly converted to an lvalue of type "cv3 T3,"
4091 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004092 // 92) (this conversion is selected by enumerating the
4093 // applicable conversion functions (13.3.1.6) and choosing
4094 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004095 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004096 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00004097 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004098 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004099
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004100 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00004101 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004102 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00004103 for (UnresolvedSet::iterator I = Conversions->begin(),
4104 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00004105 NamedDecl *D = *I;
4106 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4107 if (isa<UsingShadowDecl>(D))
4108 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4109
Mike Stump11289f42009-09-09 15:08:12 +00004110 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00004111 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00004112 CXXConversionDecl *Conv;
4113 if (ConvTemplate)
4114 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4115 else
John McCall6e9f8f62009-12-03 04:06:58 +00004116 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004117
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004118 // If the conversion function doesn't return a reference type,
4119 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004120 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00004121 (AllowExplicit || !Conv->isExplicit())) {
4122 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00004123 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4124 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004125 else
John McCall6e9f8f62009-12-03 04:06:58 +00004126 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004127 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004128 }
4129
4130 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00004131 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004132 case OR_Success:
4133 // This is a direct binding.
4134 BindsDirectly = true;
4135
4136 if (ICS) {
4137 // C++ [over.ics.ref]p1:
4138 //
4139 // [...] If the parameter binds directly to the result of
4140 // applying a conversion function to the argument
4141 // expression, the implicit conversion sequence is a
4142 // user-defined conversion sequence (13.3.3.1.2), with the
4143 // second standard conversion sequence either an identity
4144 // conversion or, if the conversion function returns an
4145 // entity of a type that is a derived class of the parameter
4146 // type, a derived-to-base Conversion.
4147 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4148 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4149 ICS->UserDefined.After = Best->FinalConversion;
4150 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004151 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004152 assert(ICS->UserDefined.After.ReferenceBinding &&
4153 ICS->UserDefined.After.DirectBinding &&
4154 "Expected a direct reference binding!");
4155 return false;
4156 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004157 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00004158 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004159 CastExpr::CK_UserDefinedConversion,
4160 cast<CXXMethodDecl>(Best->Function),
4161 Owned(Init));
4162 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00004163
4164 if (CheckExceptionSpecCompatibility(Init, T1))
4165 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004166 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4167 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004168 }
4169 break;
4170
4171 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004172 if (ICS) {
4173 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4174 Cand != CandidateSet.end(); ++Cand)
4175 if (Cand->Viable)
4176 ICS->ConversionFunctionSet.push_back(Cand->Function);
4177 break;
4178 }
4179 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4180 << Init->getSourceRange();
4181 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004182 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004183
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004184 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004185 case OR_Deleted:
4186 // There was no suitable conversion, or we found a deleted
4187 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004188 break;
4189 }
4190 }
Mike Stump11289f42009-09-09 15:08:12 +00004191
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004192 if (BindsDirectly) {
4193 // C++ [dcl.init.ref]p4:
4194 // [...] In all cases where the reference-related or
4195 // reference-compatible relationship of two types is used to
4196 // establish the validity of a reference binding, and T1 is a
4197 // base class of T2, a program that necessitates such a binding
4198 // is ill-formed if T1 is an inaccessible (clause 11) or
4199 // ambiguous (10.2) base class of T2.
4200 //
4201 // Note that we only check this condition when we're allowed to
4202 // complain about errors, because we should not be checking for
4203 // ambiguity (or inaccessibility) unless the reference binding
4204 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004205 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004206 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004207 Init->getSourceRange(),
4208 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004209 else
4210 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004211 }
4212
4213 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004214 // type (i.e., cv1 shall be const), or the reference shall be an
4215 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004216 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004217 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004218 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004219 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4220 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004221 return true;
4222 }
4223
4224 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004225 // class type, and "cv1 T1" is reference-compatible with
4226 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004227 // following ways (the choice is implementation-defined):
4228 //
4229 // -- The reference is bound to the object represented by
4230 // the rvalue (see 3.10) or to a sub-object within that
4231 // object.
4232 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004233 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004234 // a constructor is called to copy the entire rvalue
4235 // object into the temporary. The reference is bound to
4236 // the temporary or to a sub-object within the
4237 // temporary.
4238 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004239 // The constructor that would be used to make the copy
4240 // shall be callable whether or not the copy is actually
4241 // done.
4242 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004243 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004244 // freedom, so we will always take the first option and never build
4245 // a temporary in this case. FIXME: We will, however, have to check
4246 // for the presence of a copy constructor in C++98/03 mode.
4247 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004248 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4249 if (ICS) {
4250 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4251 ICS->Standard.First = ICK_Identity;
4252 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4253 ICS->Standard.Third = ICK_Identity;
4254 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4255 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004256 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004257 ICS->Standard.DirectBinding = false;
4258 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004259 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004260 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004261 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4262 if (DerivedToBase)
4263 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004264 else if(CheckExceptionSpecCompatibility(Init, T1))
4265 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004266 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004267 }
4268 return false;
4269 }
4270
Eli Friedman44b83ee2009-08-05 19:21:58 +00004271 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004272 // initialized from the initializer expression using the
4273 // rules for a non-reference copy initialization (8.5). The
4274 // reference is then bound to the temporary. If T1 is
4275 // reference-related to T2, cv1 must be the same
4276 // cv-qualification as, or greater cv-qualification than,
4277 // cv2; otherwise, the program is ill-formed.
4278 if (RefRelationship == Ref_Related) {
4279 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4280 // we would be reference-compatible or reference-compatible with
4281 // added qualification. But that wasn't the case, so the reference
4282 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004283 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004284 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004285 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4286 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004287 return true;
4288 }
4289
Douglas Gregor576e98c2009-01-30 23:27:23 +00004290 // If at least one of the types is a class type, the types are not
4291 // related, and we aren't allowed any user conversions, the
4292 // reference binding fails. This case is important for breaking
4293 // recursion, since TryImplicitConversion below will attempt to
4294 // create a temporary through the use of a copy constructor.
4295 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4296 (T1->isRecordType() || T2->isRecordType())) {
4297 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004298 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00004299 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4300 return true;
4301 }
4302
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004303 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004304 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004305 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004306 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004307 // When a parameter of reference type is not bound directly to
4308 // an argument expression, the conversion sequence is the one
4309 // required to convert the argument expression to the
4310 // underlying type of the reference according to
4311 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4312 // to copy-initializing a temporary of the underlying type with
4313 // the argument expression. Any difference in top-level
4314 // cv-qualification is subsumed by the initialization itself
4315 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004316 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4317 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004318 /*ForceRValue=*/false,
4319 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004320
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004321 // Of course, that's still a reference binding.
4322 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4323 ICS->Standard.ReferenceBinding = true;
4324 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004325 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004326 ImplicitConversionSequence::UserDefinedConversion) {
4327 ICS->UserDefined.After.ReferenceBinding = true;
4328 ICS->UserDefined.After.RRefBinding = isRValRef;
4329 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004330 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4331 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004332 ImplicitConversionSequence Conversions;
4333 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4334 false, false,
4335 Conversions);
4336 if (badConversion) {
4337 if ((Conversions.ConversionKind ==
4338 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004339 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004340 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004341 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4342 for (int j = Conversions.ConversionFunctionSet.size()-1;
4343 j >= 0; j--) {
4344 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4345 Diag(Func->getLocation(), diag::err_ovl_candidate);
4346 }
4347 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004348 else {
4349 if (isRValRef)
4350 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4351 << Init->getSourceRange();
4352 else
4353 Diag(DeclLoc, diag::err_invalid_initialization)
4354 << DeclType << Init->getType() << Init->getSourceRange();
4355 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004356 }
4357 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004358 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004359}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004360
4361/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4362/// of this overloaded operator is well-formed. If so, returns false;
4363/// otherwise, emits appropriate diagnostics and returns true.
4364bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004365 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004366 "Expected an overloaded operator declaration");
4367
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004368 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4369
Mike Stump11289f42009-09-09 15:08:12 +00004370 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004371 // The allocation and deallocation functions, operator new,
4372 // operator new[], operator delete and operator delete[], are
4373 // described completely in 3.7.3. The attributes and restrictions
4374 // found in the rest of this subclause do not apply to them unless
4375 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004376 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004377 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004378 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004379
4380 if (Op == OO_New || Op == OO_Array_New) {
4381 bool ret = false;
4382 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4383 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4384 QualType T = Context.getCanonicalType((*Param)->getType());
4385 if (!T->isDependentType() && SizeTy != T) {
4386 Diag(FnDecl->getLocation(),
4387 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4388 << SizeTy;
4389 ret = true;
4390 }
4391 }
4392 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4393 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4394 return Diag(FnDecl->getLocation(),
4395 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004396 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004397 return ret;
4398 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004399
4400 // C++ [over.oper]p6:
4401 // An operator function shall either be a non-static member
4402 // function or be a non-member function and have at least one
4403 // parameter whose type is a class, a reference to a class, an
4404 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004405 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4406 if (MethodDecl->isStatic())
4407 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004408 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004409 } else {
4410 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004411 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4412 ParamEnd = FnDecl->param_end();
4413 Param != ParamEnd; ++Param) {
4414 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004415 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4416 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004417 ClassOrEnumParam = true;
4418 break;
4419 }
4420 }
4421
Douglas Gregord69246b2008-11-17 16:14:12 +00004422 if (!ClassOrEnumParam)
4423 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004424 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004425 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004426 }
4427
4428 // C++ [over.oper]p8:
4429 // An operator function cannot have default arguments (8.3.6),
4430 // except where explicitly stated below.
4431 //
Mike Stump11289f42009-09-09 15:08:12 +00004432 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004433 // (C++ [over.call]p1).
4434 if (Op != OO_Call) {
4435 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4436 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004437 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004438 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004439 diag::err_operator_overload_default_arg)
4440 << FnDecl->getDeclName();
4441 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004442 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004443 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004444 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004445 }
4446 }
4447
Douglas Gregor6cf08062008-11-10 13:38:07 +00004448 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4449 { false, false, false }
4450#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4451 , { Unary, Binary, MemberOnly }
4452#include "clang/Basic/OperatorKinds.def"
4453 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004454
Douglas Gregor6cf08062008-11-10 13:38:07 +00004455 bool CanBeUnaryOperator = OperatorUses[Op][0];
4456 bool CanBeBinaryOperator = OperatorUses[Op][1];
4457 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004458
4459 // C++ [over.oper]p8:
4460 // [...] Operator functions cannot have more or fewer parameters
4461 // than the number required for the corresponding operator, as
4462 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004463 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004464 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004465 if (Op != OO_Call &&
4466 ((NumParams == 1 && !CanBeUnaryOperator) ||
4467 (NumParams == 2 && !CanBeBinaryOperator) ||
4468 (NumParams < 1) || (NumParams > 2))) {
4469 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004470 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004471 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004472 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004473 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004474 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004475 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004476 assert(CanBeBinaryOperator &&
4477 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004478 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004479 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004480
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004481 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004482 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004483 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004484
Douglas Gregord69246b2008-11-17 16:14:12 +00004485 // Overloaded operators other than operator() cannot be variadic.
4486 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004487 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004488 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004489 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004490 }
4491
4492 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004493 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4494 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004495 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004496 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004497 }
4498
4499 // C++ [over.inc]p1:
4500 // The user-defined function called operator++ implements the
4501 // prefix and postfix ++ operator. If this function is a member
4502 // function with no parameters, or a non-member function with one
4503 // parameter of class or enumeration type, it defines the prefix
4504 // increment operator ++ for objects of that type. If the function
4505 // is a member function with one parameter (which shall be of type
4506 // int) or a non-member function with two parameters (the second
4507 // of which shall be of type int), it defines the postfix
4508 // increment operator ++ for objects of that type.
4509 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4510 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4511 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004512 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004513 ParamIsInt = BT->getKind() == BuiltinType::Int;
4514
Chris Lattner2b786902008-11-21 07:50:02 +00004515 if (!ParamIsInt)
4516 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004517 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004518 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004519 }
4520
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004521 // Notify the class if it got an assignment operator.
4522 if (Op == OO_Equal) {
4523 // Would have returned earlier otherwise.
4524 assert(isa<CXXMethodDecl>(FnDecl) &&
4525 "Overloaded = not member, but not filtered.");
4526 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4527 Method->getParent()->addedAssignmentOperator(Context, Method);
4528 }
4529
Douglas Gregord69246b2008-11-17 16:14:12 +00004530 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004531}
Chris Lattner3b024a32008-12-17 07:09:26 +00004532
Douglas Gregor07665a62009-01-05 19:45:36 +00004533/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4534/// linkage specification, including the language and (if present)
4535/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4536/// the location of the language string literal, which is provided
4537/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4538/// the '{' brace. Otherwise, this linkage specification does not
4539/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004540Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4541 SourceLocation ExternLoc,
4542 SourceLocation LangLoc,
4543 const char *Lang,
4544 unsigned StrSize,
4545 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004546 LinkageSpecDecl::LanguageIDs Language;
4547 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4548 Language = LinkageSpecDecl::lang_c;
4549 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4550 Language = LinkageSpecDecl::lang_cxx;
4551 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004552 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004553 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004554 }
Mike Stump11289f42009-09-09 15:08:12 +00004555
Chris Lattner438e5012008-12-17 07:13:27 +00004556 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004557
Douglas Gregor07665a62009-01-05 19:45:36 +00004558 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004559 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004560 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004561 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004562 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004563 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004564}
4565
Douglas Gregor07665a62009-01-05 19:45:36 +00004566/// ActOnFinishLinkageSpecification - Completely the definition of
4567/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4568/// valid, it's the position of the closing '}' brace in a linkage
4569/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004570Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4571 DeclPtrTy LinkageSpec,
4572 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004573 if (LinkageSpec)
4574 PopDeclContext();
4575 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004576}
4577
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004578/// \brief Perform semantic analysis for the variable declaration that
4579/// occurs within a C++ catch clause, returning the newly-created
4580/// variable.
4581VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00004582 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004583 IdentifierInfo *Name,
4584 SourceLocation Loc,
4585 SourceRange Range) {
4586 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004587
4588 // Arrays and functions decay.
4589 if (ExDeclType->isArrayType())
4590 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4591 else if (ExDeclType->isFunctionType())
4592 ExDeclType = Context.getPointerType(ExDeclType);
4593
4594 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4595 // The exception-declaration shall not denote a pointer or reference to an
4596 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004597 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004598 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004599 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004600 Invalid = true;
4601 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004602
Sebastian Redl54c04d42008-12-22 19:15:10 +00004603 QualType BaseType = ExDeclType;
4604 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004605 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004606 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004607 BaseType = Ptr->getPointeeType();
4608 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004609 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004610 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004611 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004612 BaseType = Ref->getPointeeType();
4613 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004614 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004615 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004616 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004617 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004618 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004619
Mike Stump11289f42009-09-09 15:08:12 +00004620 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004621 RequireNonAbstractType(Loc, ExDeclType,
4622 diag::err_abstract_type_in_decl,
4623 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004624 Invalid = true;
4625
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004626 // FIXME: Need to test for ability to copy-construct and destroy the
4627 // exception variable.
4628
Sebastian Redl9b244a82008-12-22 21:35:02 +00004629 // FIXME: Need to check for abstract classes.
4630
Mike Stump11289f42009-09-09 15:08:12 +00004631 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCallbcd03502009-12-07 02:54:59 +00004632 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004633
4634 if (Invalid)
4635 ExDecl->setInvalidDecl();
4636
4637 return ExDecl;
4638}
4639
4640/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4641/// handler.
4642Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00004643 TypeSourceInfo *TInfo = 0;
4644 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004645
4646 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004647 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004648 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004649 // The scope should be freshly made just for us. There is just no way
4650 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004651 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004652 if (PrevDecl->isTemplateParameter()) {
4653 // Maybe we will complain about the shadowed template parameter.
4654 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004655 }
4656 }
4657
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004658 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004659 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4660 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004661 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004662 }
4663
John McCallbcd03502009-12-07 02:54:59 +00004664 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004665 D.getIdentifier(),
4666 D.getIdentifierLoc(),
4667 D.getDeclSpec().getSourceRange());
4668
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004669 if (Invalid)
4670 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004671
Sebastian Redl54c04d42008-12-22 19:15:10 +00004672 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004673 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004674 PushOnScopeChains(ExDecl, S);
4675 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004676 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004677
Douglas Gregor758a8692009-06-17 21:51:59 +00004678 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004679 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004680}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004681
Mike Stump11289f42009-09-09 15:08:12 +00004682Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004683 ExprArg assertexpr,
4684 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004685 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004686 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004687 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4688
Anders Carlsson54b26982009-03-14 00:33:21 +00004689 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4690 llvm::APSInt Value(32);
4691 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4692 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4693 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004694 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004695 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004696
Anders Carlsson54b26982009-03-14 00:33:21 +00004697 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004698 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004699 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004700 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004701 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004702 }
4703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004705 assertexpr.release();
4706 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004707 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004708 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004709
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004710 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004711 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004712}
Sebastian Redlf769df52009-03-24 22:27:57 +00004713
John McCall11083da2009-09-16 22:47:08 +00004714/// Handle a friend type declaration. This works in tandem with
4715/// ActOnTag.
4716///
4717/// Notes on friend class templates:
4718///
4719/// We generally treat friend class declarations as if they were
4720/// declaring a class. So, for example, the elaborated type specifier
4721/// in a friend declaration is required to obey the restrictions of a
4722/// class-head (i.e. no typedefs in the scope chain), template
4723/// parameters are required to match up with simple template-ids, &c.
4724/// However, unlike when declaring a template specialization, it's
4725/// okay to refer to a template specialization without an empty
4726/// template parameter declaration, e.g.
4727/// friend class A<T>::B<unsigned>;
4728/// We permit this as a special case; if there are any template
4729/// parameters present at all, require proper matching, i.e.
4730/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004731Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004732 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004733 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004734
4735 assert(DS.isFriendSpecified());
4736 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4737
John McCall11083da2009-09-16 22:47:08 +00004738 // Try to convert the decl specifier to a type. This works for
4739 // friend templates because ActOnTag never produces a ClassTemplateDecl
4740 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004741 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004742 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4743 if (TheDeclarator.isInvalidType())
4744 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004745
John McCall11083da2009-09-16 22:47:08 +00004746 // This is definitely an error in C++98. It's probably meant to
4747 // be forbidden in C++0x, too, but the specification is just
4748 // poorly written.
4749 //
4750 // The problem is with declarations like the following:
4751 // template <T> friend A<T>::foo;
4752 // where deciding whether a class C is a friend or not now hinges
4753 // on whether there exists an instantiation of A that causes
4754 // 'foo' to equal C. There are restrictions on class-heads
4755 // (which we declare (by fiat) elaborated friend declarations to
4756 // be) that makes this tractable.
4757 //
4758 // FIXME: handle "template <> friend class A<T>;", which
4759 // is possibly well-formed? Who even knows?
4760 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4761 Diag(Loc, diag::err_tagless_friend_type_template)
4762 << DS.getSourceRange();
4763 return DeclPtrTy();
4764 }
4765
John McCallaa74a0c2009-08-28 07:59:38 +00004766 // C++ [class.friend]p2:
4767 // An elaborated-type-specifier shall be used in a friend declaration
4768 // for a class.*
4769 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004770 // This is one of the rare places in Clang where it's legitimate to
4771 // ask about the "spelling" of the type.
4772 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4773 // If we evaluated the type to a record type, suggest putting
4774 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004775 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004776 RecordDecl *RD = RT->getDecl();
4777
4778 std::string InsertionText = std::string(" ") + RD->getKindName();
4779
John McCallc3987482009-10-07 23:34:25 +00004780 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4781 << (unsigned) RD->getTagKind()
4782 << T
4783 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004784 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4785 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004786 return DeclPtrTy();
4787 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004788 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4789 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004790 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004791 }
4792 }
4793
John McCallc3987482009-10-07 23:34:25 +00004794 // Enum types cannot be friends.
4795 if (T->getAs<EnumType>()) {
4796 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4797 << SourceRange(DS.getFriendSpecLoc());
4798 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004799 }
John McCallaa74a0c2009-08-28 07:59:38 +00004800
John McCallaa74a0c2009-08-28 07:59:38 +00004801 // C++98 [class.friend]p1: A friend of a class is a function
4802 // or class that is not a member of the class . . .
4803 // But that's a silly restriction which nobody implements for
4804 // inner classes, and C++0x removes it anyway, so we only report
4805 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004806 if (!getLangOptions().CPlusPlus0x)
4807 if (const RecordType *RT = T->getAs<RecordType>())
4808 if (RT->getDecl()->getDeclContext() == CurContext)
4809 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004810
John McCall11083da2009-09-16 22:47:08 +00004811 Decl *D;
4812 if (TempParams.size())
4813 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4814 TempParams.size(),
4815 (TemplateParameterList**) TempParams.release(),
4816 T.getTypePtr(),
4817 DS.getFriendSpecLoc());
4818 else
4819 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4820 DS.getFriendSpecLoc());
4821 D->setAccess(AS_public);
4822 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004823
John McCall11083da2009-09-16 22:47:08 +00004824 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004825}
4826
John McCall2f212b32009-09-11 21:02:39 +00004827Sema::DeclPtrTy
4828Sema::ActOnFriendFunctionDecl(Scope *S,
4829 Declarator &D,
4830 bool IsDefinition,
4831 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004832 const DeclSpec &DS = D.getDeclSpec();
4833
4834 assert(DS.isFriendSpecified());
4835 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4836
4837 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00004838 TypeSourceInfo *TInfo = 0;
4839 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00004840
4841 // C++ [class.friend]p1
4842 // A friend of a class is a function or class....
4843 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004844 // It *doesn't* see through dependent types, which is correct
4845 // according to [temp.arg.type]p3:
4846 // If a declaration acquires a function type through a
4847 // type dependent on a template-parameter and this causes
4848 // a declaration that does not use the syntactic form of a
4849 // function declarator to have a function type, the program
4850 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004851 if (!T->isFunctionType()) {
4852 Diag(Loc, diag::err_unexpected_friend);
4853
4854 // It might be worthwhile to try to recover by creating an
4855 // appropriate declaration.
4856 return DeclPtrTy();
4857 }
4858
4859 // C++ [namespace.memdef]p3
4860 // - If a friend declaration in a non-local class first declares a
4861 // class or function, the friend class or function is a member
4862 // of the innermost enclosing namespace.
4863 // - The name of the friend is not found by simple name lookup
4864 // until a matching declaration is provided in that namespace
4865 // scope (either before or after the class declaration granting
4866 // friendship).
4867 // - If a friend function is called, its name may be found by the
4868 // name lookup that considers functions from namespaces and
4869 // classes associated with the types of the function arguments.
4870 // - When looking for a prior declaration of a class or a function
4871 // declared as a friend, scopes outside the innermost enclosing
4872 // namespace scope are not considered.
4873
John McCallaa74a0c2009-08-28 07:59:38 +00004874 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4875 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004876 assert(Name);
4877
John McCall07e91c02009-08-06 02:15:43 +00004878 // The context we found the declaration in, or in which we should
4879 // create the declaration.
4880 DeclContext *DC;
4881
4882 // FIXME: handle local classes
4883
4884 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00004885 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4886 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00004887 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004888 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004889 DC = computeDeclContext(ScopeQual);
4890
4891 // FIXME: handle dependent contexts
4892 if (!DC) return DeclPtrTy();
4893
John McCall1f82f242009-11-18 22:49:29 +00004894 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004895
4896 // If searching in that context implicitly found a declaration in
4897 // a different context, treat it like it wasn't found at all.
4898 // TODO: better diagnostics for this case. Suggesting the right
4899 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00004900 // FIXME: getRepresentativeDecl() is not right here at all
4901 if (Previous.empty() ||
4902 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004903 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004904 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4905 return DeclPtrTy();
4906 }
4907
4908 // C++ [class.friend]p1: A friend of a class is a function or
4909 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004910 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004911 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4912
John McCall07e91c02009-08-06 02:15:43 +00004913 // Otherwise walk out to the nearest namespace scope looking for matches.
4914 } else {
4915 // TODO: handle local class contexts.
4916
4917 DC = CurContext;
4918 while (true) {
4919 // Skip class contexts. If someone can cite chapter and verse
4920 // for this behavior, that would be nice --- it's what GCC and
4921 // EDG do, and it seems like a reasonable intent, but the spec
4922 // really only says that checks for unqualified existing
4923 // declarations should stop at the nearest enclosing namespace,
4924 // not that they should only consider the nearest enclosing
4925 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004926 while (DC->isRecord())
4927 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004928
John McCall1f82f242009-11-18 22:49:29 +00004929 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004930
4931 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00004932 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00004933 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004934
John McCall07e91c02009-08-06 02:15:43 +00004935 if (DC->isFileContext()) break;
4936 DC = DC->getParent();
4937 }
4938
4939 // C++ [class.friend]p1: A friend of a class is a function or
4940 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004941 // C++0x changes this for both friend types and functions.
4942 // Most C++ 98 compilers do seem to give an error here, so
4943 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00004944 if (!Previous.empty() && DC->Equals(CurContext)
4945 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004946 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4947 }
4948
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004949 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004950 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004951 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4952 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4953 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004954 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004955 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4956 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004957 return DeclPtrTy();
4958 }
John McCall07e91c02009-08-06 02:15:43 +00004959 }
4960
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004961 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00004962 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004963 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004964 IsDefinition,
4965 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004966 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004967
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004968 assert(ND->getDeclContext() == DC);
4969 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004970
John McCall759e32b2009-08-31 22:39:49 +00004971 // Add the function declaration to the appropriate lookup tables,
4972 // adjusting the redeclarations list as necessary. We don't
4973 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004974 //
John McCall759e32b2009-08-31 22:39:49 +00004975 // Also update the scope-based lookup if the target context's
4976 // lookup context is in lexical scope.
4977 if (!CurContext->isDependentContext()) {
4978 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004979 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004980 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004981 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004982 }
John McCallaa74a0c2009-08-28 07:59:38 +00004983
4984 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004985 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004986 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004987 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004988 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004989
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004990 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004991}
4992
Chris Lattner83f095c2009-03-28 19:18:32 +00004993void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004994 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004995
Chris Lattner83f095c2009-03-28 19:18:32 +00004996 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004997 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4998 if (!Fn) {
4999 Diag(DelLoc, diag::err_deleted_non_function);
5000 return;
5001 }
5002 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5003 Diag(DelLoc, diag::err_deleted_decl_not_first);
5004 Diag(Prev->getLocation(), diag::note_previous_declaration);
5005 // If the declaration wasn't the first, we delete the function anyway for
5006 // recovery.
5007 }
5008 Fn->setDeleted();
5009}
Sebastian Redl4c018662009-04-27 21:33:24 +00005010
5011static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5012 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5013 ++CI) {
5014 Stmt *SubStmt = *CI;
5015 if (!SubStmt)
5016 continue;
5017 if (isa<ReturnStmt>(SubStmt))
5018 Self.Diag(SubStmt->getSourceRange().getBegin(),
5019 diag::err_return_in_constructor_handler);
5020 if (!isa<Expr>(SubStmt))
5021 SearchForReturnInStmt(Self, SubStmt);
5022 }
5023}
5024
5025void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5026 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5027 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5028 SearchForReturnInStmt(*this, Handler);
5029 }
5030}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005031
Mike Stump11289f42009-09-09 15:08:12 +00005032bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005033 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005034 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5035 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005036
5037 QualType CNewTy = Context.getCanonicalType(NewTy);
5038 QualType COldTy = Context.getCanonicalType(OldTy);
5039
Mike Stump11289f42009-09-09 15:08:12 +00005040 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005041 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005042 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005043
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005044 // Check if the return types are covariant
5045 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005046
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005047 /// Both types must be pointers or references to classes.
5048 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5049 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5050 NewClassTy = NewPT->getPointeeType();
5051 OldClassTy = OldPT->getPointeeType();
5052 }
5053 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5054 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5055 NewClassTy = NewRT->getPointeeType();
5056 OldClassTy = OldRT->getPointeeType();
5057 }
5058 }
Mike Stump11289f42009-09-09 15:08:12 +00005059
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005060 // The return types aren't either both pointers or references to a class type.
5061 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005062 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005063 diag::err_different_return_type_for_overriding_virtual_function)
5064 << New->getDeclName() << NewTy << OldTy;
5065 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005066
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005067 return true;
5068 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005069
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005070 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005071 // Check if the new class derives from the old class.
5072 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5073 Diag(New->getLocation(),
5074 diag::err_covariant_return_not_derived)
5075 << New->getDeclName() << NewTy << OldTy;
5076 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5077 return true;
5078 }
Mike Stump11289f42009-09-09 15:08:12 +00005079
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005080 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00005081 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005082 diag::err_covariant_return_inaccessible_base,
5083 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5084 // FIXME: Should this point to the return type?
5085 New->getLocation(), SourceRange(), New->getDeclName())) {
5086 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5087 return true;
5088 }
5089 }
Mike Stump11289f42009-09-09 15:08:12 +00005090
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005091 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005092 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005093 Diag(New->getLocation(),
5094 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005095 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005096 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5097 return true;
5098 };
Mike Stump11289f42009-09-09 15:08:12 +00005099
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005100
5101 // The new class type must have the same or less qualifiers as the old type.
5102 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5103 Diag(New->getLocation(),
5104 diag::err_covariant_return_type_class_type_more_qualified)
5105 << New->getDeclName() << NewTy << OldTy;
5106 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5107 return true;
5108 };
Mike Stump11289f42009-09-09 15:08:12 +00005109
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005110 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005111}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005112
Alexis Hunt96d5c762009-11-21 08:43:09 +00005113bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5114 const CXXMethodDecl *Old)
5115{
5116 if (Old->hasAttr<FinalAttr>()) {
5117 Diag(New->getLocation(), diag::err_final_function_overridden)
5118 << New->getDeclName();
5119 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5120 return true;
5121 }
5122
5123 return false;
5124}
5125
Douglas Gregor21920e372009-12-01 17:24:26 +00005126/// \brief Mark the given method pure.
5127///
5128/// \param Method the method to be marked pure.
5129///
5130/// \param InitRange the source range that covers the "0" initializer.
5131bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5132 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5133 Method->setPure();
5134
5135 // A class is abstract if at least one function is pure virtual.
5136 Method->getParent()->setAbstract(true);
5137 return false;
5138 }
5139
5140 if (!Method->isInvalidDecl())
5141 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5142 << Method->getDeclName() << InitRange;
5143 return true;
5144}
5145
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005146/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5147/// initializer for the declaration 'Dcl'.
5148/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5149/// static data member of class X, names should be looked up in the scope of
5150/// class X.
5151void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005152 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005153
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005154 Decl *D = Dcl.getAs<Decl>();
5155 // If there is no declaration, there was an error parsing it.
5156 if (D == 0)
5157 return;
5158
5159 // Check whether it is a declaration with a nested name specifier like
5160 // int foo::bar;
5161 if (!D->isOutOfLine())
5162 return;
Mike Stump11289f42009-09-09 15:08:12 +00005163
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005164 // C++ [basic.lookup.unqual]p13
5165 //
5166 // A name used in the definition of a static data member of class X
5167 // (after the qualified-id of the static member) is looked up as if the name
5168 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00005169
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005170 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00005171 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005172}
5173
5174/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5175/// initializer for the declaration 'Dcl'.
5176void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005177 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005178
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005179 Decl *D = Dcl.getAs<Decl>();
5180 // If there is no declaration, there was an error parsing it.
5181 if (D == 0)
5182 return;
5183
5184 // Check whether it is a declaration with a nested name specifier like
5185 // int foo::bar;
5186 if (!D->isOutOfLine())
5187 return;
5188
5189 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00005190 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005191}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005192
5193/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5194/// C++ if/switch/while/for statement.
5195/// e.g: "if (int x = f()) {...}"
5196Action::DeclResult
5197Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5198 // C++ 6.4p2:
5199 // The declarator shall not specify a function or an array.
5200 // The type-specifier-seq shall not contain typedef and shall not declare a
5201 // new class or enumeration.
5202 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5203 "Parser allowed 'typedef' as storage class of condition decl.");
5204
John McCallbcd03502009-12-07 02:54:59 +00005205 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005206 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005207 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005208
5209 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5210 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5211 // would be created and CXXConditionDeclExpr wants a VarDecl.
5212 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5213 << D.getSourceRange();
5214 return DeclResult();
5215 } else if (OwnedTag && OwnedTag->isDefinition()) {
5216 // The type-specifier-seq shall not declare a new class or enumeration.
5217 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5218 }
5219
5220 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5221 if (!Dcl)
5222 return DeclResult();
5223
5224 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5225 VD->setDeclaredInCondition(true);
5226 return Dcl;
5227}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005228
Anders Carlsson82fccd02009-12-07 08:24:59 +00005229void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5230 CXXMethodDecl *MD) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005231 // Ignore dependent types.
5232 if (MD->isDependentContext())
5233 return;
5234
5235 CXXRecordDecl *RD = MD->getParent();
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005236
5237 // Ignore classes without a vtable.
5238 if (!RD->isDynamicClass())
5239 return;
5240
Anders Carlsson82fccd02009-12-07 08:24:59 +00005241 if (!MD->isOutOfLine()) {
5242 // The only inline functions we care about are constructors. We also defer
5243 // marking the virtual members as referenced until we've reached the end
5244 // of the translation unit. We do this because we need to know the key
5245 // function of the class in order to determine the key function.
5246 if (isa<CXXConstructorDecl>(MD))
5247 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5248 return;
5249 }
5250
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005251 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005252
5253 if (!KeyFunction) {
5254 // This record does not have a key function, so we assume that the vtable
5255 // will be emitted when it's used by the constructor.
5256 if (!isa<CXXConstructorDecl>(MD))
5257 return;
5258 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5259 // We don't have the right key function.
5260 return;
5261 }
5262
Anders Carlsson82fccd02009-12-07 08:24:59 +00005263 // Mark the members as referenced.
5264 MarkVirtualMembersReferenced(Loc, RD);
5265 ClassesWithUnmarkedVirtualMembers.erase(RD);
5266}
5267
5268bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5269 if (ClassesWithUnmarkedVirtualMembers.empty())
5270 return false;
5271
5272 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5273 ClassesWithUnmarkedVirtualMembers.begin(),
5274 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5275 CXXRecordDecl *RD = i->first;
5276
5277 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5278 if (KeyFunction) {
5279 // We know that the class has a key function. If the key function was
5280 // declared in this translation unit, then it the class decl would not
5281 // have been in the ClassesWithUnmarkedVirtualMembers map.
5282 continue;
5283 }
5284
5285 SourceLocation Loc = i->second;
5286 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005287 }
5288
Anders Carlsson82fccd02009-12-07 08:24:59 +00005289 ClassesWithUnmarkedVirtualMembers.clear();
5290 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00005291}
Anders Carlsson82fccd02009-12-07 08:24:59 +00005292
5293void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5294 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5295 e = RD->method_end(); i != e; ++i) {
5296 CXXMethodDecl *MD = *i;
5297
5298 // C++ [basic.def.odr]p2:
5299 // [...] A virtual member function is used if it is not pure. [...]
5300 if (MD->isVirtual() && !MD->isPure())
5301 MarkDeclarationReferenced(Loc, MD);
5302 }
5303}
5304