blob: 37681719aaa87f376452c649a4d26c19bf70115e [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");
487 if (!CXXBaseDecl->isEmpty())
488 Class->setEmpty(false);
489 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 Class->setPolymorphic(true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000491 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
492 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
493 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000494 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
495 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000496 return 0;
497 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000498
499 // C++ [dcl.init.aggr]p1:
500 // An aggregate is [...] a class with [...] no base classes [...].
501 Class->setAggregate(false);
502 Class->setPOD(false);
503
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000504 if (Virtual) {
505 // C++ [class.ctor]p5:
506 // A constructor is trivial if its class has no virtual base classes.
507 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000508
509 // C++ [class.copy]p6:
510 // A copy constructor is trivial if its class has no virtual base classes.
511 Class->setHasTrivialCopyConstructor(false);
512
513 // C++ [class.copy]p11:
514 // A copy assignment operator is trivial if its class has no virtual
515 // base classes.
516 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000517
518 // C++0x [meta.unary.prop] is_empty:
519 // T is a class type, but not a union type, with ... no virtual base
520 // classes
521 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000522 } else {
523 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000524 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000525 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000526 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
527 Class->setHasTrivialConstructor(false);
528
529 // C++ [class.copy]p6:
530 // A copy constructor is trivial if all the direct base classes of its
531 // class have trivial copy constructors.
532 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
533 Class->setHasTrivialCopyConstructor(false);
534
535 // C++ [class.copy]p11:
536 // A copy assignment operator is trivial if all the direct base classes
537 // of its class have trivial copy assignment operators.
538 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
539 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000540 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000541
542 // C++ [class.ctor]p3:
543 // A destructor is trivial if all the direct base classes of its class
544 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000545 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
546 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000547
Douglas Gregor463421d2009-03-03 04:44:36 +0000548 // Create the base specifier.
549 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000550 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
551 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000552 Access, BaseType);
553}
554
Douglas Gregor556877c2008-04-13 21:30:24 +0000555/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
556/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000557/// example:
558/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000559/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000560Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000561Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000562 bool Virtual, AccessSpecifier Access,
563 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000564 if (!classdecl)
565 return true;
566
Douglas Gregorc40290e2009-03-09 23:48:35 +0000567 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000568 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000569 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
571 Virtual, Access,
572 BaseType, BaseLoc))
573 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000576}
Douglas Gregor556877c2008-04-13 21:30:24 +0000577
Douglas Gregor463421d2009-03-03 04:44:36 +0000578/// \brief Performs the actual work of attaching the given base class
579/// specifiers to a C++ class.
580bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
581 unsigned NumBases) {
582 if (NumBases == 0)
583 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000584
585 // Used to keep track of which base types we have already seen, so
586 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000587 // that the key is always the unqualified canonical type of the base
588 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000589 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
590
591 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000592 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000594 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000595 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000597 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000598
Douglas Gregor29a92472008-10-22 17:49:05 +0000599 if (KnownBaseTypes[NewBaseType]) {
600 // C++ [class.mi]p3:
601 // A class shall not be specified as a direct base class of a
602 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000604 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000605 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000607
608 // Delete the duplicate base class specifier; we're going to
609 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000610 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000611
612 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000613 } else {
614 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000615 KnownBaseTypes[NewBaseType] = Bases[idx];
616 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000617 }
618 }
619
620 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000621 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000622
623 // Delete the remaining (good) base class specifiers, since their
624 // data has been copied into the CXXRecordDecl.
625 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000626 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000627
628 return Invalid;
629}
630
631/// ActOnBaseSpecifiers - Attach the given base specifiers to the
632/// class, after checking whether there are any duplicate base
633/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000634void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000635 unsigned NumBases) {
636 if (!ClassDecl || !Bases || !NumBases)
637 return;
638
639 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000640 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000642}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000643
Douglas Gregor36d1b142009-10-06 17:59:45 +0000644/// \brief Determine whether the type \p Derived is a C++ class that is
645/// derived from the type \p Base.
646bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
647 if (!getLangOptions().CPlusPlus)
648 return false;
649
650 const RecordType *DerivedRT = Derived->getAs<RecordType>();
651 if (!DerivedRT)
652 return false;
653
654 const RecordType *BaseRT = Base->getAs<RecordType>();
655 if (!BaseRT)
656 return false;
657
658 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
659 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
660 return DerivedRD->isDerivedFrom(BaseRD);
661}
662
663/// \brief Determine whether the type \p Derived is a C++ class that is
664/// derived from the type \p Base.
665bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
666 if (!getLangOptions().CPlusPlus)
667 return false;
668
669 const RecordType *DerivedRT = Derived->getAs<RecordType>();
670 if (!DerivedRT)
671 return false;
672
673 const RecordType *BaseRT = Base->getAs<RecordType>();
674 if (!BaseRT)
675 return false;
676
677 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
678 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
679 return DerivedRD->isDerivedFrom(BaseRD, Paths);
680}
681
682/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
683/// conversion (where Derived and Base are class types) is
684/// well-formed, meaning that the conversion is unambiguous (and
685/// that all of the base classes are accessible). Returns true
686/// and emits a diagnostic if the code is ill-formed, returns false
687/// otherwise. Loc is the location where this routine should point to
688/// if there is an error, and Range is the source range to highlight
689/// if there is an error.
690bool
691Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
692 unsigned InaccessibleBaseID,
693 unsigned AmbigiousBaseConvID,
694 SourceLocation Loc, SourceRange Range,
695 DeclarationName Name) {
696 // First, determine whether the path from Derived to Base is
697 // ambiguous. This is slightly more expensive than checking whether
698 // the Derived to Base conversion exists, because here we need to
699 // explore multiple paths to determine if there is an ambiguity.
700 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
701 /*DetectVirtual=*/false);
702 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
703 assert(DerivationOkay &&
704 "Can only be used with a derived-to-base conversion");
705 (void)DerivationOkay;
706
707 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000708 if (InaccessibleBaseID == 0)
709 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000710 // Check that the base class can be accessed.
711 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
712 Name);
713 }
714
715 // We know that the derived-to-base conversion is ambiguous, and
716 // we're going to produce a diagnostic. Perform the derived-to-base
717 // search just one more time to compute all of the possible paths so
718 // that we can print them out. This is more expensive than any of
719 // the previous derived-to-base checks we've done, but at this point
720 // performance isn't as much of an issue.
721 Paths.clear();
722 Paths.setRecordingPaths(true);
723 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
724 assert(StillOkay && "Can only be used with a derived-to-base conversion");
725 (void)StillOkay;
726
727 // Build up a textual representation of the ambiguous paths, e.g.,
728 // D -> B -> A, that will be used to illustrate the ambiguous
729 // conversions in the diagnostic. We only print one of the paths
730 // to each base class subobject.
731 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
732
733 Diag(Loc, AmbigiousBaseConvID)
734 << Derived << Base << PathDisplayStr << Range << Name;
735 return true;
736}
737
738bool
739Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000740 SourceLocation Loc, SourceRange Range,
741 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000742 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000743 IgnoreAccess ? 0 :
744 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000745 diag::err_ambiguous_derived_to_base_conv,
746 Loc, Range, DeclarationName());
747}
748
749
750/// @brief Builds a string representing ambiguous paths from a
751/// specific derived class to different subobjects of the same base
752/// class.
753///
754/// This function builds a string that can be used in error messages
755/// to show the different paths that one can take through the
756/// inheritance hierarchy to go from the derived class to different
757/// subobjects of a base class. The result looks something like this:
758/// @code
759/// struct D -> struct B -> struct A
760/// struct D -> struct C -> struct A
761/// @endcode
762std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
763 std::string PathDisplayStr;
764 std::set<unsigned> DisplayedPaths;
765 for (CXXBasePaths::paths_iterator Path = Paths.begin();
766 Path != Paths.end(); ++Path) {
767 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
768 // We haven't displayed a path to this particular base
769 // class subobject yet.
770 PathDisplayStr += "\n ";
771 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
772 for (CXXBasePath::const_iterator Element = Path->begin();
773 Element != Path->end(); ++Element)
774 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
775 }
776 }
777
778 return PathDisplayStr;
779}
780
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000781//===----------------------------------------------------------------------===//
782// C++ class member Handling
783//===----------------------------------------------------------------------===//
784
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000785/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
786/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
787/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000788/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000789Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000790Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000791 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000792 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
793 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000794 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000795 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000796 Expr *BitWidth = static_cast<Expr*>(BW);
797 Expr *Init = static_cast<Expr*>(InitExpr);
798 SourceLocation Loc = D.getIdentifierLoc();
799
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000800 bool isFunc = D.isFunctionDeclarator();
801
John McCall07e91c02009-08-06 02:15:43 +0000802 assert(!DS.isFriendSpecified());
803
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000804 // C++ 9.2p6: A member shall not be declared to have automatic storage
805 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000806 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
807 // data members and cannot be applied to names declared const or static,
808 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000809 switch (DS.getStorageClassSpec()) {
810 case DeclSpec::SCS_unspecified:
811 case DeclSpec::SCS_typedef:
812 case DeclSpec::SCS_static:
813 // FALL THROUGH.
814 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000815 case DeclSpec::SCS_mutable:
816 if (isFunc) {
817 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000818 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000819 else
Chris Lattner3b054132008-11-19 05:08:23 +0000820 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000821
Sebastian Redl8071edb2008-11-17 23:24:37 +0000822 // FIXME: It would be nicer if the keyword was ignored only for this
823 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000824 D.getMutableDeclSpec().ClearStorageClassSpecs();
825 } else {
826 QualType T = GetTypeForDeclarator(D, S);
827 diag::kind err = static_cast<diag::kind>(0);
828 if (T->isReferenceType())
829 err = diag::err_mutable_reference;
830 else if (T.isConstQualified())
831 err = diag::err_mutable_const;
832 if (err != 0) {
833 if (DS.getStorageClassSpecLoc().isValid())
834 Diag(DS.getStorageClassSpecLoc(), err);
835 else
836 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000837 // FIXME: It would be nicer if the keyword was ignored only for this
838 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000839 D.getMutableDeclSpec().ClearStorageClassSpecs();
840 }
841 }
842 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000843 default:
844 if (DS.getStorageClassSpecLoc().isValid())
845 Diag(DS.getStorageClassSpecLoc(),
846 diag::err_storageclass_invalid_for_member);
847 else
848 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
849 D.getMutableDeclSpec().ClearStorageClassSpecs();
850 }
851
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000852 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000853 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000854 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000855 // Check also for this case:
856 //
857 // typedef int f();
858 // f a;
859 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000860 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000861 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000862 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000863
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000864 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
865 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000866 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000867
868 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000869 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000870 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000871 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
872 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000873 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000874 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000875 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000876 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000877 if (!Member) {
878 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000879 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000880 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000881
882 // Non-instance-fields can't have a bitfield.
883 if (BitWidth) {
884 if (Member->isInvalidDecl()) {
885 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000886 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000887 // C++ 9.6p3: A bit-field shall not be a static member.
888 // "static member 'A' cannot be a bit-field"
889 Diag(Loc, diag::err_static_not_bitfield)
890 << Name << BitWidth->getSourceRange();
891 } else if (isa<TypedefDecl>(Member)) {
892 // "typedef member 'x' cannot be a bit-field"
893 Diag(Loc, diag::err_typedef_not_bitfield)
894 << Name << BitWidth->getSourceRange();
895 } else {
896 // A function typedef ("typedef int f(); f a;").
897 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
898 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000899 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000900 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000901 }
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattnerd26760a2009-03-05 23:01:03 +0000903 DeleteExpr(BitWidth);
904 BitWidth = 0;
905 Member->setInvalidDecl();
906 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000907
908 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000909
Douglas Gregor3447e762009-08-20 22:52:58 +0000910 // If we have declared a member function template, set the access of the
911 // templated declaration as well.
912 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
913 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000914 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915
Douglas Gregor92751d42008-11-17 22:58:34 +0000916 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000917
Douglas Gregor0c880302009-03-11 23:00:04 +0000918 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000919 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000920 if (Deleted) // FIXME: Source location is not very good.
921 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000922
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000923 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000924 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000925 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000926 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000927 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000928}
929
Douglas Gregore8381c02008-11-05 04:29:56 +0000930/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000931Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000932Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000933 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000934 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000935 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000936 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000937 SourceLocation IdLoc,
938 SourceLocation LParenLoc,
939 ExprTy **Args, unsigned NumArgs,
940 SourceLocation *CommaLocs,
941 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000942 if (!ConstructorD)
943 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000944
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000945 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000946
947 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000948 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000949 if (!Constructor) {
950 // The user wrote a constructor initializer on a function that is
951 // not a C++ constructor. Ignore the error for now, because we may
952 // have more member initializers coming; we'll diagnose it just
953 // once in ActOnMemInitializers.
954 return true;
955 }
956
957 CXXRecordDecl *ClassDecl = Constructor->getParent();
958
959 // C++ [class.base.init]p2:
960 // Names in a mem-initializer-id are looked up in the scope of the
961 // constructor’s class and, if not found in that scope, are looked
962 // up in the scope containing the constructor’s
963 // definition. [Note: if the constructor’s class contains a member
964 // with the same name as a direct or virtual base class of the
965 // class, a mem-initializer-id naming the member or base class and
966 // composed of a single identifier refers to the class member. A
967 // mem-initializer-id for the hidden base class may be specified
968 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000969 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000970 // Look for a member, first.
971 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000972 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000973 = ClassDecl->lookup(MemberOrBase);
974 if (Result.first != Result.second)
975 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000976
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000977 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000978
Eli Friedman8e1433b2009-07-29 19:44:27 +0000979 if (Member)
980 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000981 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000982 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000983 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000984 QualType BaseType;
985
986 DeclaratorInfo *DInfo = 0;
987 if (TemplateTypeTy)
988 BaseType = GetTypeFromParser(TemplateTypeTy, &DInfo);
989 else
990 BaseType = QualType::getFromOpaquePtr(getTypeName(*MemberOrBase, IdLoc,
991 S, &SS));
992 if (BaseType.isNull())
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000993 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
994 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000995
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000996 if (!DInfo)
997 DInfo = Context.getTrivialDeclaratorInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000998
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000999 return BuildBaseInitializer(BaseType, DInfo, (Expr **)Args, NumArgs,
1000 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001001}
1002
John McCalle22a04a2009-11-04 23:02:40 +00001003/// Checks an initializer expression for use of uninitialized fields, such as
1004/// containing the field that is being initialized. Returns true if there is an
1005/// uninitialized field was used an updates the SourceLocation parameter; false
1006/// otherwise.
1007static bool InitExprContainsUninitializedFields(const Stmt* S,
1008 const FieldDecl* LhsField,
1009 SourceLocation* L) {
1010 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1011 if (ME) {
1012 const NamedDecl* RhsField = ME->getMemberDecl();
1013 if (RhsField == LhsField) {
1014 // Initializing a field with itself. Throw a warning.
1015 // But wait; there are exceptions!
1016 // Exception #1: The field may not belong to this record.
1017 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1018 const Expr* base = ME->getBase();
1019 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1020 // Even though the field matches, it does not belong to this record.
1021 return false;
1022 }
1023 // None of the exceptions triggered; return true to indicate an
1024 // uninitialized field was used.
1025 *L = ME->getMemberLoc();
1026 return true;
1027 }
1028 }
1029 bool found = false;
1030 for (Stmt::const_child_iterator it = S->child_begin();
1031 it != S->child_end() && found == false;
1032 ++it) {
1033 if (isa<CallExpr>(S)) {
1034 // Do not descend into function calls or constructors, as the use
1035 // of an uninitialized field may be valid. One would have to inspect
1036 // the contents of the function/ctor to determine if it is safe or not.
1037 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1038 // may be safe, depending on what the function/ctor does.
1039 continue;
1040 }
1041 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1042 }
1043 return found;
1044}
1045
Eli Friedman8e1433b2009-07-29 19:44:27 +00001046Sema::MemInitResult
1047Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1048 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001049 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001050 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001051 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1052 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1053 ExprTemporaries.clear();
1054
John McCalle22a04a2009-11-04 23:02:40 +00001055 // Diagnose value-uses of fields to initialize themselves, e.g.
1056 // foo(foo)
1057 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001058 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001059 for (unsigned i = 0; i < NumArgs; ++i) {
1060 SourceLocation L;
1061 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1062 // FIXME: Return true in the case when other fields are used before being
1063 // uninitialized. For example, let this field be the i'th field. When
1064 // initializing the i'th field, throw a warning if any of the >= i'th
1065 // fields are used, as they are not yet initialized.
1066 // Right now we are only handling the case where the i'th field uses
1067 // itself in its initializer.
1068 Diag(L, diag::warn_field_is_uninit);
1069 }
1070 }
1071
Eli Friedman8e1433b2009-07-29 19:44:27 +00001072 bool HasDependentArg = false;
1073 for (unsigned i = 0; i < NumArgs; i++)
1074 HasDependentArg |= Args[i]->isTypeDependent();
1075
1076 CXXConstructorDecl *C = 0;
1077 QualType FieldType = Member->getType();
1078 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1079 FieldType = Array->getElementType();
1080 if (FieldType->isDependentType()) {
1081 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001082 } else if (FieldType->isRecordType()) {
1083 // Member is a record (struct/union/class), so pass the initializer
1084 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001085 if (!HasDependentArg) {
1086 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1087
1088 C = PerformInitializationByConstructor(FieldType,
1089 MultiExprArg(*this,
1090 (void**)Args,
1091 NumArgs),
1092 IdLoc,
1093 SourceRange(IdLoc, RParenLoc),
1094 Member->getDeclName(), IK_Direct,
1095 ConstructorArgs);
1096
1097 if (C) {
1098 // Take over the constructor arguments as our own.
1099 NumArgs = ConstructorArgs.size();
1100 Args = (Expr **)ConstructorArgs.take();
1101 }
1102 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001103 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001104 // The member type is not a record type (or an array of record
1105 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001106 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001107 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1108 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001109 Expr *NewExp;
1110 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001111 if (FieldType->isReferenceType()) {
1112 Diag(IdLoc, diag::err_null_intialized_reference_member)
1113 << Member->getDeclName();
1114 return Diag(Member->getLocation(), diag::note_declared_at);
1115 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001116 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1117 NumArgs = 1;
1118 }
1119 else
1120 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001121 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1122 return true;
1123 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001124 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001125
1126 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1127 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1128 ExprTemporaries.clear();
1129
Eli Friedman8e1433b2009-07-29 19:44:27 +00001130 // FIXME: Perform direct initialization of the member.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001131 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1132 C, LParenLoc, (Expr **)Args,
1133 NumArgs, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001134}
1135
1136Sema::MemInitResult
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001137Sema::BuildBaseInitializer(QualType BaseType, DeclaratorInfo *BaseDInfo,
1138 Expr **Args, unsigned NumArgs,
1139 SourceLocation LParenLoc, SourceLocation RParenLoc,
1140 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001141 bool HasDependentArg = false;
1142 for (unsigned i = 0; i < NumArgs; i++)
1143 HasDependentArg |= Args[i]->isTypeDependent();
1144
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001145 SourceLocation BaseLoc = BaseDInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001146 if (!BaseType->isDependentType()) {
1147 if (!BaseType->isRecordType())
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001148 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1149 << BaseType << BaseDInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001150
1151 // C++ [class.base.init]p2:
1152 // [...] Unless the mem-initializer-id names a nonstatic data
1153 // member of the constructor’s class or a direct or virtual base
1154 // of that class, the mem-initializer is ill-formed. A
1155 // mem-initializer-list can initialize a base class using any
1156 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001157
Eli Friedman8e1433b2009-07-29 19:44:27 +00001158 // First, check for a direct base class.
1159 const CXXBaseSpecifier *DirectBaseSpec = 0;
1160 for (CXXRecordDecl::base_class_const_iterator Base =
1161 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001162 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001163 // We found a direct base of this type. That's what we're
1164 // initializing.
1165 DirectBaseSpec = &*Base;
1166 break;
1167 }
1168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
Eli Friedman8e1433b2009-07-29 19:44:27 +00001170 // Check for a virtual base class.
1171 // FIXME: We might be able to short-circuit this if we know in advance that
1172 // there are no virtual bases.
1173 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1174 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1175 // We haven't found a base yet; search the class hierarchy for a
1176 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001177 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1178 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001179 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001180 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001181 Path != Paths.end(); ++Path) {
1182 if (Path->back().Base->isVirtual()) {
1183 VirtualBaseSpec = Path->back().Base;
1184 break;
1185 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001186 }
1187 }
1188 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001189
1190 // C++ [base.class.init]p2:
1191 // If a mem-initializer-id is ambiguous because it designates both
1192 // a direct non-virtual base class and an inherited virtual base
1193 // class, the mem-initializer is ill-formed.
1194 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001195 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1196 << BaseType << BaseDInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001197 // C++ [base.class.init]p2:
1198 // Unless the mem-initializer-id names a nonstatic data membeer of the
1199 // constructor's class ot a direst or virtual base of that class, the
1200 // mem-initializer is ill-formed.
1201 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001202 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1203 << BaseType << ClassDecl->getNameAsCString()
1204 << BaseDInfo->getTypeLoc().getSourceRange();
Douglas Gregore8381c02008-11-05 04:29:56 +00001205 }
1206
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001207 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001208 if (!BaseType->isDependentType() && !HasDependentArg) {
1209 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001210 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001211 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1212
1213 C = PerformInitializationByConstructor(BaseType,
1214 MultiExprArg(*this,
1215 (void**)Args, NumArgs),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001216 BaseLoc,
1217 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001218 Name, IK_Direct,
1219 ConstructorArgs);
1220 if (C) {
1221 // Take over the constructor arguments as our own.
1222 NumArgs = ConstructorArgs.size();
1223 Args = (Expr **)ConstructorArgs.take();
1224 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001225 }
1226
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001227 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1228 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1229 ExprTemporaries.clear();
1230
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001231 return new (Context) CXXBaseOrMemberInitializer(Context, BaseDInfo, C,
1232 LParenLoc, (Expr **)Args,
1233 NumArgs, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001234}
1235
Eli Friedman9cf6b592009-11-09 19:20:36 +00001236bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001237Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001238 CXXBaseOrMemberInitializer **Initializers,
1239 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001240 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001241 // We need to build the initializer AST according to order of construction
1242 // and not what user specified in the Initializers list.
1243 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1244 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1245 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1246 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001247 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001248
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001249 for (unsigned i = 0; i < NumInitializers; i++) {
1250 CXXBaseOrMemberInitializer *Member = Initializers[i];
1251 if (Member->isBaseInitializer()) {
1252 if (Member->getBaseClass()->isDependentType())
1253 HasDependentBaseInit = true;
1254 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1255 } else {
1256 AllBaseFields[Member->getMember()] = Member;
1257 }
1258 }
Mike Stump11289f42009-09-09 15:08:12 +00001259
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001260 if (HasDependentBaseInit) {
1261 // FIXME. This does not preserve the ordering of the initializers.
1262 // Try (with -Wreorder)
1263 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001264 // template<class X> struct B : A<X> {
1265 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001266 // int x1;
1267 // };
1268 // B<int> x;
1269 // On seeing one dependent type, we should essentially exit this routine
1270 // while preserving user-declared initializer list. When this routine is
1271 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001272 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001273
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001274 // If we have a dependent base initialization, we can't determine the
1275 // association between initializers and bases; just dump the known
1276 // initializers into the list, and don't try to deal with other bases.
1277 for (unsigned i = 0; i < NumInitializers; i++) {
1278 CXXBaseOrMemberInitializer *Member = Initializers[i];
1279 if (Member->isBaseInitializer())
1280 AllToInit.push_back(Member);
1281 }
1282 } else {
1283 // Push virtual bases before others.
1284 for (CXXRecordDecl::base_class_iterator VBase =
1285 ClassDecl->vbases_begin(),
1286 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1287 if (VBase->getType()->isDependentType())
1288 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001289 if (CXXBaseOrMemberInitializer *Value
1290 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001291 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001292 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001293 else {
Mike Stump11289f42009-09-09 15:08:12 +00001294 CXXRecordDecl *VBaseDecl =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001295 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001296 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001297 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001298 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001299 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1300 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1301 << 0 << VBase->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001302 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001303 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001304 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001305 continue;
1306 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001307
Anders Carlsson561f7932009-10-29 15:46:07 +00001308 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1309 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1310 Constructor->getLocation(), CtorArgs))
1311 continue;
1312
1313 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1314
Anders Carlssonbdd12402009-11-13 20:11:49 +00001315 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001316 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1317 // necessary.
1318 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001319 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001320 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001321 new (Context) CXXBaseOrMemberInitializer(Context,
1322 Context.getTrivialDeclaratorInfo(VBase->getType(),
1323 SourceLocation()),
1324 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001325 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001326 CtorArgs.takeAs<Expr>(),
1327 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001328 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001329 AllToInit.push_back(Member);
1330 }
1331 }
Mike Stump11289f42009-09-09 15:08:12 +00001332
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001333 for (CXXRecordDecl::base_class_iterator Base =
1334 ClassDecl->bases_begin(),
1335 E = ClassDecl->bases_end(); Base != E; ++Base) {
1336 // Virtuals are in the virtual base list and already constructed.
1337 if (Base->isVirtual())
1338 continue;
1339 // Skip dependent types.
1340 if (Base->getType()->isDependentType())
1341 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001342 if (CXXBaseOrMemberInitializer *Value
1343 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001344 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001345 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001346 else {
Mike Stump11289f42009-09-09 15:08:12 +00001347 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001348 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001349 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001350 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001351 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001352 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1353 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1354 << 0 << Base->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001355 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001356 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001357 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001358 continue;
1359 }
1360
1361 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1362 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1363 Constructor->getLocation(), CtorArgs))
1364 continue;
1365
1366 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001367
Anders Carlssonbdd12402009-11-13 20:11:49 +00001368 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001369 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1370 // necessary.
1371 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001372 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001373 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001374 new (Context) CXXBaseOrMemberInitializer(Context,
1375 Context.getTrivialDeclaratorInfo(Base->getType(),
1376 SourceLocation()),
1377 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001378 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001379 CtorArgs.takeAs<Expr>(),
1380 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001381 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001382 AllToInit.push_back(Member);
1383 }
1384 }
1385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001387 // non-static data members.
1388 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1389 E = ClassDecl->field_end(); Field != E; ++Field) {
1390 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001391 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001392 Field->getType()->getAs<RecordType>()) {
1393 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001394 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001395 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001396 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1397 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1398 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1399 // set to the anonymous union data member used in the initializer
1400 // list.
1401 Value->setMember(*Field);
1402 Value->setAnonUnionMember(*FA);
1403 AllToInit.push_back(Value);
1404 break;
1405 }
1406 }
1407 }
1408 continue;
1409 }
1410 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1411 AllToInit.push_back(Value);
1412 continue;
1413 }
Mike Stump11289f42009-09-09 15:08:12 +00001414
Eli Friedmand7686ef2009-11-09 01:05:47 +00001415 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001416 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001417
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001418 QualType FT = Context.getBaseElementType((*Field)->getType());
1419 if (const RecordType* RT = FT->getAs<RecordType>()) {
1420 CXXConstructorDecl *Ctor =
1421 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001422 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001423 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1424 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1425 << 1 << (*Field)->getDeclName();
1426 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregore7488b92009-12-01 16:58:18 +00001427 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001428 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001429 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001430 continue;
1431 }
Eli Friedman22683fe2009-11-16 23:07:59 +00001432
1433 if (FT.isConstQualified() && Ctor->isTrivial()) {
1434 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1435 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1436 << 1 << (*Field)->getDeclName();
1437 Diag((*Field)->getLocation(), diag::note_declared_at);
1438 HadError = true;
1439 }
1440
1441 // Don't create initializers for trivial constructors, since they don't
1442 // actually need to be run.
1443 if (Ctor->isTrivial())
1444 continue;
1445
Anders Carlsson561f7932009-10-29 15:46:07 +00001446 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1447 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1448 Constructor->getLocation(), CtorArgs))
1449 continue;
1450
Anders Carlssonbdd12402009-11-13 20:11:49 +00001451 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1452 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1453 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001454 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001455 new (Context) CXXBaseOrMemberInitializer(Context,
1456 *Field, SourceLocation(),
1457 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001458 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001459 CtorArgs.takeAs<Expr>(),
1460 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001461 SourceLocation());
1462
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001463 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001464 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001465 }
1466 else if (FT->isReferenceType()) {
1467 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001468 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1469 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001470 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001471 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001472 }
1473 else if (FT.isConstQualified()) {
1474 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001475 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1476 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001477 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001478 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001479 }
1480 }
Mike Stump11289f42009-09-09 15:08:12 +00001481
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001482 NumInitializers = AllToInit.size();
1483 if (NumInitializers > 0) {
1484 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1485 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1486 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001487
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001488 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1489 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1490 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1491 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001492
1493 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001494}
1495
Eli Friedman952c15d2009-07-21 19:28:10 +00001496static void *GetKeyForTopLevelField(FieldDecl *Field) {
1497 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001498 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001499 if (RT->getDecl()->isAnonymousStructOrUnion())
1500 return static_cast<void *>(RT->getDecl());
1501 }
1502 return static_cast<void *>(Field);
1503}
1504
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001505static void *GetKeyForBase(QualType BaseType) {
1506 if (const RecordType *RT = BaseType->getAs<RecordType>())
1507 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001508
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001509 assert(0 && "Unexpected base type!");
1510 return 0;
1511}
1512
Mike Stump11289f42009-09-09 15:08:12 +00001513static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001514 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001515 // For fields injected into the class via declaration of an anonymous union,
1516 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001517 if (Member->isMemberInitializer()) {
1518 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001519
Eli Friedmand7686ef2009-11-09 01:05:47 +00001520 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001521 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001522 // in AnonUnionMember field.
1523 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1524 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001525 if (Field->getDeclContext()->isRecord()) {
1526 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1527 if (RD->isAnonymousStructOrUnion())
1528 return static_cast<void *>(RD);
1529 }
1530 return static_cast<void *>(Field);
1531 }
Mike Stump11289f42009-09-09 15:08:12 +00001532
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001533 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001534}
1535
John McCallc90f6d72009-11-04 23:13:52 +00001536/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001537void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001538 SourceLocation ColonLoc,
1539 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001540 if (!ConstructorDecl)
1541 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001542
1543 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001544
1545 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001546 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001547
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001548 if (!Constructor) {
1549 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1550 return;
1551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001553 if (!Constructor->isDependentContext()) {
1554 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1555 bool err = false;
1556 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001557 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001558 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1559 void *KeyToMember = GetKeyForMember(Member);
1560 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1561 if (!PrevMember) {
1562 PrevMember = Member;
1563 continue;
1564 }
1565 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001566 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001567 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001568 << Field->getNameAsString()
1569 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001570 else {
1571 Type *BaseClass = Member->getBaseClass();
1572 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001573 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001574 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001575 << QualType(BaseClass, 0)
1576 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001577 }
1578 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1579 << 0;
1580 err = true;
1581 }
Mike Stump11289f42009-09-09 15:08:12 +00001582
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001583 if (err)
1584 return;
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Eli Friedmand7686ef2009-11-09 01:05:47 +00001587 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001588 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001589 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001590
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001591 if (Constructor->isDependentContext())
1592 return;
Mike Stump11289f42009-09-09 15:08:12 +00001593
1594 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001595 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001596 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001597 Diagnostic::Ignored)
1598 return;
Mike Stump11289f42009-09-09 15:08:12 +00001599
Anders Carlssone0eebb32009-08-27 05:45:01 +00001600 // Also issue warning if order of ctor-initializer list does not match order
1601 // of 1) base class declarations and 2) order of non-static data members.
1602 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001603
Anders Carlssone0eebb32009-08-27 05:45:01 +00001604 CXXRecordDecl *ClassDecl
1605 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1606 // Push virtual bases before others.
1607 for (CXXRecordDecl::base_class_iterator VBase =
1608 ClassDecl->vbases_begin(),
1609 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001610 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001611
Anders Carlssone0eebb32009-08-27 05:45:01 +00001612 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1613 E = ClassDecl->bases_end(); Base != E; ++Base) {
1614 // Virtuals are alread in the virtual base list and are constructed
1615 // first.
1616 if (Base->isVirtual())
1617 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001618 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001619 }
Mike Stump11289f42009-09-09 15:08:12 +00001620
Anders Carlssone0eebb32009-08-27 05:45:01 +00001621 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1622 E = ClassDecl->field_end(); Field != E; ++Field)
1623 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001624
Anders Carlssone0eebb32009-08-27 05:45:01 +00001625 int Last = AllBaseOrMembers.size();
1626 int curIndex = 0;
1627 CXXBaseOrMemberInitializer *PrevMember = 0;
1628 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001629 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001630 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1631 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001632
Anders Carlssone0eebb32009-08-27 05:45:01 +00001633 for (; curIndex < Last; curIndex++)
1634 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1635 break;
1636 if (curIndex == Last) {
1637 assert(PrevMember && "Member not in member list?!");
1638 // Initializer as specified in ctor-initializer list is out of order.
1639 // Issue a warning diagnostic.
1640 if (PrevMember->isBaseInitializer()) {
1641 // Diagnostics is for an initialized base class.
1642 Type *BaseClass = PrevMember->getBaseClass();
1643 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001644 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001645 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001646 } else {
1647 FieldDecl *Field = PrevMember->getMember();
1648 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001649 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001650 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001651 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001652 // Also the note!
1653 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001654 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001655 diag::note_fieldorbase_initialized_here) << 0
1656 << Field->getNameAsString();
1657 else {
1658 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001659 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001660 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001661 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001662 }
1663 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001664 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001665 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001666 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001667 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001668 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001669}
1670
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001671void
Anders Carlssondee9a302009-11-17 04:44:12 +00001672Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1673 // Ignore dependent destructors.
1674 if (Destructor->isDependentContext())
1675 return;
1676
1677 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001678
Anders Carlssondee9a302009-11-17 04:44:12 +00001679 // Non-static data members.
1680 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1681 E = ClassDecl->field_end(); I != E; ++I) {
1682 FieldDecl *Field = *I;
1683
1684 QualType FieldType = Context.getBaseElementType(Field->getType());
1685
1686 const RecordType* RT = FieldType->getAs<RecordType>();
1687 if (!RT)
1688 continue;
1689
1690 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1691 if (FieldClassDecl->hasTrivialDestructor())
1692 continue;
1693
1694 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1695 MarkDeclarationReferenced(Destructor->getLocation(),
1696 const_cast<CXXDestructorDecl*>(Dtor));
1697 }
1698
1699 // Bases.
1700 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1701 E = ClassDecl->bases_end(); Base != E; ++Base) {
1702 // Ignore virtual bases.
1703 if (Base->isVirtual())
1704 continue;
1705
1706 // Ignore trivial destructors.
1707 CXXRecordDecl *BaseClassDecl
1708 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1709 if (BaseClassDecl->hasTrivialDestructor())
1710 continue;
1711
1712 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1713 MarkDeclarationReferenced(Destructor->getLocation(),
1714 const_cast<CXXDestructorDecl*>(Dtor));
1715 }
1716
1717 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001718 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1719 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001720 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001721 CXXRecordDecl *BaseClassDecl
1722 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1723 if (BaseClassDecl->hasTrivialDestructor())
1724 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001725
1726 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1727 MarkDeclarationReferenced(Destructor->getLocation(),
1728 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001729 }
1730}
1731
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001732void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001733 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001734 return;
Mike Stump11289f42009-09-09 15:08:12 +00001735
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001736 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001737
1738 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001739 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001740 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001741}
1742
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001743namespace {
1744 /// PureVirtualMethodCollector - traverses a class and its superclasses
1745 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001746 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001747 ASTContext &Context;
1748
Sebastian Redlb7d64912009-03-22 21:28:55 +00001749 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001750 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001751
1752 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001753 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001754
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001755 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001756
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001757 public:
Mike Stump11289f42009-09-09 15:08:12 +00001758 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001759 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001760
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001761 MethodList List;
1762 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001764 // Copy the temporary list to methods, and make sure to ignore any
1765 // null entries.
1766 for (size_t i = 0, e = List.size(); i != e; ++i) {
1767 if (List[i])
1768 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001769 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001772 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001773
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001774 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1775 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001776 };
Mike Stump11289f42009-09-09 15:08:12 +00001777
1778 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001779 MethodList& Methods) {
1780 // First, collect the pure virtual methods for the base classes.
1781 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1782 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001783 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001784 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001785 if (BaseDecl && BaseDecl->isAbstract())
1786 Collect(BaseDecl, Methods);
1787 }
1788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001790 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001791 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001792
Anders Carlsson3c012712009-05-17 00:00:05 +00001793 MethodSetTy OverriddenMethods;
1794 size_t MethodsSize = Methods.size();
1795
Mike Stump11289f42009-09-09 15:08:12 +00001796 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001797 i != e; ++i) {
1798 // Traverse the record, looking for methods.
1799 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001800 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001801 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001802 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001803
Anders Carlsson700179432009-10-18 19:34:08 +00001804 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001805 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1806 E = MD->end_overridden_methods(); I != E; ++I) {
1807 // Keep track of the overridden methods.
1808 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001809 }
1810 }
1811 }
Mike Stump11289f42009-09-09 15:08:12 +00001812
1813 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001814 // overridden.
1815 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1816 if (OverriddenMethods.count(Methods[i]))
1817 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001820 }
1821}
Douglas Gregore8381c02008-11-05 04:29:56 +00001822
Anders Carlssoneabf7702009-08-27 00:13:57 +00001823
Mike Stump11289f42009-09-09 15:08:12 +00001824bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001825 unsigned DiagID, AbstractDiagSelID SelID,
1826 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001827 if (SelID == -1)
1828 return RequireNonAbstractType(Loc, T,
1829 PDiag(DiagID), CurrentRD);
1830 else
1831 return RequireNonAbstractType(Loc, T,
1832 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001833}
1834
Anders Carlssoneabf7702009-08-27 00:13:57 +00001835bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1836 const PartialDiagnostic &PD,
1837 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001838 if (!getLangOptions().CPlusPlus)
1839 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001840
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001841 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001842 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001843 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001844
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001845 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001846 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001847 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001848 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001849
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001850 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001851 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001854 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001855 if (!RT)
1856 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001857
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001858 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1859 if (!RD)
1860 return false;
1861
Anders Carlssonb57738b2009-03-24 17:23:42 +00001862 if (CurrentRD && CurrentRD != RD)
1863 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001864
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001865 if (!RD->isAbstract())
1866 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001867
Anders Carlssoneabf7702009-08-27 00:13:57 +00001868 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001869
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001870 // Check if we've already emitted the list of pure virtual functions for this
1871 // class.
1872 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1873 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001874
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001875 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001876
1877 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001878 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1879 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001880
1881 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001882 MD->getDeclName();
1883 }
1884
1885 if (!PureVirtualClassDiagSet)
1886 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1887 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001888
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001889 return true;
1890}
1891
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001892namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001893 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001894 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1895 Sema &SemaRef;
1896 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001897
Anders Carlssonb57738b2009-03-24 17:23:42 +00001898 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001899 bool Invalid = false;
1900
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001901 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1902 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001903 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001904
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001905 return Invalid;
1906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907
Anders Carlssonb57738b2009-03-24 17:23:42 +00001908 public:
1909 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1910 : SemaRef(SemaRef), AbstractClass(ac) {
1911 Visit(SemaRef.Context.getTranslationUnitDecl());
1912 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001913
Anders Carlssonb57738b2009-03-24 17:23:42 +00001914 bool VisitFunctionDecl(const FunctionDecl *FD) {
1915 if (FD->isThisDeclarationADefinition()) {
1916 // No need to do the check if we're in a definition, because it requires
1917 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001918 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001919 return VisitDeclContext(FD);
1920 }
Mike Stump11289f42009-09-09 15:08:12 +00001921
Anders Carlssonb57738b2009-03-24 17:23:42 +00001922 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001923 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001924 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001925 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1926 diag::err_abstract_type_in_decl,
1927 Sema::AbstractReturnType,
1928 AbstractClass);
1929
Mike Stump11289f42009-09-09 15:08:12 +00001930 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001931 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001932 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001933 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001934 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001935 VD->getOriginalType(),
1936 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001937 Sema::AbstractParamType,
1938 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001939 }
1940
1941 return Invalid;
1942 }
Mike Stump11289f42009-09-09 15:08:12 +00001943
Anders Carlssonb57738b2009-03-24 17:23:42 +00001944 bool VisitDecl(const Decl* D) {
1945 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1946 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001947
Anders Carlssonb57738b2009-03-24 17:23:42 +00001948 return false;
1949 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001950 };
1951}
1952
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001953void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001954 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001955 SourceLocation LBrac,
1956 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001957 if (!TagDecl)
1958 return;
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001960 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001961 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001962 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001963 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001964
Chris Lattner83f095c2009-03-28 19:18:32 +00001965 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001966 if (!RD->isAbstract()) {
1967 // Collect all the pure virtual methods and see if this is an abstract
1968 // class after all.
1969 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001970 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001971 RD->setAbstract(true);
1972 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
1974 if (RD->isAbstract())
Douglas Gregor120f6a62009-11-17 06:14:37 +00001975 (void)AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001976
Douglas Gregor3c74d412009-10-14 20:14:33 +00001977 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001978 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001979}
1980
Douglas Gregor05379422008-11-03 17:51:48 +00001981/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1982/// special functions, such as the default constructor, copy
1983/// constructor, or destructor, to the given C++ class (C++
1984/// [special]p1). This routine can only be executed just before the
1985/// definition of the class is complete.
1986void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001987 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001988 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001989
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001990 // FIXME: Implicit declarations have exception specifications, which are
1991 // the union of the specifications of the implicitly called functions.
1992
Douglas Gregor05379422008-11-03 17:51:48 +00001993 if (!ClassDecl->hasUserDeclaredConstructor()) {
1994 // C++ [class.ctor]p5:
1995 // A default constructor for a class X is a constructor of class X
1996 // that can be called without an argument. If there is no
1997 // user-declared constructor for class X, a default constructor is
1998 // implicitly declared. An implicitly-declared default constructor
1999 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002000 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002001 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002002 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002003 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002004 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002005 Context.getFunctionType(Context.VoidTy,
2006 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002007 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002008 /*isExplicit=*/false,
2009 /*isInline=*/true,
2010 /*isImplicitlyDeclared=*/true);
2011 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002012 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002013 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002014 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002015 }
2016
2017 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2018 // C++ [class.copy]p4:
2019 // If the class definition does not explicitly declare a copy
2020 // constructor, one is declared implicitly.
2021
2022 // C++ [class.copy]p5:
2023 // The implicitly-declared copy constructor for a class X will
2024 // have the form
2025 //
2026 // X::X(const X&)
2027 //
2028 // if
2029 bool HasConstCopyConstructor = true;
2030
2031 // -- each direct or virtual base class B of X has a copy
2032 // constructor whose first parameter is of type const B& or
2033 // const volatile B&, and
2034 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2035 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2036 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002038 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002039 = BaseClassDecl->hasConstCopyConstructor(Context);
2040 }
2041
2042 // -- for all the nonstatic data members of X that are of a
2043 // class type M (or array thereof), each such class type
2044 // has a copy constructor whose first parameter is of type
2045 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002046 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2047 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002048 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002049 QualType FieldType = (*Field)->getType();
2050 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2051 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002052 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002053 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002054 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002055 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002056 = FieldClassDecl->hasConstCopyConstructor(Context);
2057 }
2058 }
2059
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002060 // Otherwise, the implicitly declared copy constructor will have
2061 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002062 //
2063 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002064 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002065 if (HasConstCopyConstructor)
2066 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002067 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002068
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002069 // An implicitly-declared copy constructor is an inline public
2070 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002071 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002072 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002073 CXXConstructorDecl *CopyConstructor
2074 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002075 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002076 Context.getFunctionType(Context.VoidTy,
2077 &ArgType, 1,
2078 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002079 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002080 /*isExplicit=*/false,
2081 /*isInline=*/true,
2082 /*isImplicitlyDeclared=*/true);
2083 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002084 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002085 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002086
2087 // Add the parameter to the constructor.
2088 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2089 ClassDecl->getLocation(),
2090 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002091 ArgType, /*DInfo=*/0,
2092 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002093 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002094 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002095 }
2096
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002097 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2098 // Note: The following rules are largely analoguous to the copy
2099 // constructor rules. Note that virtual bases are not taken into account
2100 // for determining the argument type of the operator. Note also that
2101 // operators taking an object instead of a reference are allowed.
2102 //
2103 // C++ [class.copy]p10:
2104 // If the class definition does not explicitly declare a copy
2105 // assignment operator, one is declared implicitly.
2106 // The implicitly-defined copy assignment operator for a class X
2107 // will have the form
2108 //
2109 // X& X::operator=(const X&)
2110 //
2111 // if
2112 bool HasConstCopyAssignment = true;
2113
2114 // -- each direct base class B of X has a copy assignment operator
2115 // whose parameter is of type const B&, const volatile B& or B,
2116 // and
2117 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2118 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002119 assert(!Base->getType()->isDependentType() &&
2120 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002121 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002122 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002123 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002124 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002125 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002126 }
2127
2128 // -- for all the nonstatic data members of X that are of a class
2129 // type M (or array thereof), each such class type has a copy
2130 // assignment operator whose parameter is of type const M&,
2131 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002132 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2133 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002134 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002135 QualType FieldType = (*Field)->getType();
2136 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2137 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002138 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002139 const CXXRecordDecl *FieldClassDecl
2140 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002141 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002142 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002143 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002144 }
2145 }
2146
2147 // Otherwise, the implicitly declared copy assignment operator will
2148 // have the form
2149 //
2150 // X& X::operator=(X&)
2151 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002152 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002153 if (HasConstCopyAssignment)
2154 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002155 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002156
2157 // An implicitly-declared copy assignment operator is an inline public
2158 // member of its class.
2159 DeclarationName Name =
2160 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2161 CXXMethodDecl *CopyAssignment =
2162 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2163 Context.getFunctionType(RetType, &ArgType, 1,
2164 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002165 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002166 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002167 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002168 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002169 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002170
2171 // Add the parameter to the operator.
2172 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2173 ClassDecl->getLocation(),
2174 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002175 ArgType, /*DInfo=*/0,
2176 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002177 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002178
2179 // Don't call addedAssignmentOperator. There is no way to distinguish an
2180 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002181 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002182 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002183 }
2184
Douglas Gregor1349b452008-12-15 21:24:18 +00002185 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002186 // C++ [class.dtor]p2:
2187 // If a class has no user-declared destructor, a destructor is
2188 // declared implicitly. An implicitly-declared destructor is an
2189 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002190 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002191 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002192 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002193 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002194 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002195 Context.getFunctionType(Context.VoidTy,
2196 0, 0, false, 0),
2197 /*isInline=*/true,
2198 /*isImplicitlyDeclared=*/true);
2199 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002200 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002201 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002202 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002203
2204 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002205 }
Douglas Gregor05379422008-11-03 17:51:48 +00002206}
2207
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002208void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002209 Decl *D = TemplateD.getAs<Decl>();
2210 if (!D)
2211 return;
2212
2213 TemplateParameterList *Params = 0;
2214 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2215 Params = Template->getTemplateParameters();
2216 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2217 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2218 Params = PartialSpec->getTemplateParameters();
2219 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002220 return;
2221
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002222 for (TemplateParameterList::iterator Param = Params->begin(),
2223 ParamEnd = Params->end();
2224 Param != ParamEnd; ++Param) {
2225 NamedDecl *Named = cast<NamedDecl>(*Param);
2226 if (Named->getDeclName()) {
2227 S->AddDecl(DeclPtrTy::make(Named));
2228 IdResolver.AddDecl(Named);
2229 }
2230 }
2231}
2232
Douglas Gregor4d87df52008-12-16 21:30:33 +00002233/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2234/// parsing a top-level (non-nested) C++ class, and we are now
2235/// parsing those parts of the given Method declaration that could
2236/// not be parsed earlier (C++ [class.mem]p2), such as default
2237/// arguments. This action should enter the scope of the given
2238/// Method declaration as if we had just parsed the qualified method
2239/// name. However, it should not bring the parameters into scope;
2240/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002241void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002242 if (!MethodD)
2243 return;
Mike Stump11289f42009-09-09 15:08:12 +00002244
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002245 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002246
Douglas Gregor4d87df52008-12-16 21:30:33 +00002247 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002248 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002249 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002250 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2251 SS.setScopeRep(
2252 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002253 ActOnCXXEnterDeclaratorScope(S, SS);
2254}
2255
2256/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2257/// C++ method declaration. We're (re-)introducing the given
2258/// function parameter into scope for use in parsing later parts of
2259/// the method declaration. For example, we could see an
2260/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002261void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002262 if (!ParamD)
2263 return;
Mike Stump11289f42009-09-09 15:08:12 +00002264
Chris Lattner83f095c2009-03-28 19:18:32 +00002265 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002266
2267 // If this parameter has an unparsed default argument, clear it out
2268 // to make way for the parsed default argument.
2269 if (Param->hasUnparsedDefaultArg())
2270 Param->setDefaultArg(0);
2271
Chris Lattner83f095c2009-03-28 19:18:32 +00002272 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002273 if (Param->getDeclName())
2274 IdResolver.AddDecl(Param);
2275}
2276
2277/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2278/// processing the delayed method declaration for Method. The method
2279/// declaration is now considered finished. There may be a separate
2280/// ActOnStartOfFunctionDef action later (not necessarily
2281/// immediately!) for this method, if it was also defined inside the
2282/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002283void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002284 if (!MethodD)
2285 return;
Mike Stump11289f42009-09-09 15:08:12 +00002286
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002287 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Chris Lattner83f095c2009-03-28 19:18:32 +00002289 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002290 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002291 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002292 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2293 SS.setScopeRep(
2294 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002295 ActOnCXXExitDeclaratorScope(S, SS);
2296
2297 // Now that we have our default arguments, check the constructor
2298 // again. It could produce additional diagnostics or affect whether
2299 // the class has implicitly-declared destructors, among other
2300 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002301 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2302 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002303
2304 // Check the default arguments, which we may have added.
2305 if (!Method->isInvalidDecl())
2306 CheckCXXDefaultArguments(Method);
2307}
2308
Douglas Gregor831c93f2008-11-05 20:51:48 +00002309/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002310/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002311/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002312/// emit diagnostics and set the invalid bit to true. In any case, the type
2313/// will be updated to reflect a well-formed type for the constructor and
2314/// returned.
2315QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2316 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002317 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002318
2319 // C++ [class.ctor]p3:
2320 // A constructor shall not be virtual (10.3) or static (9.4). A
2321 // constructor can be invoked for a const, volatile or const
2322 // volatile object. A constructor shall not be declared const,
2323 // volatile, or const volatile (9.3.2).
2324 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002325 if (!D.isInvalidType())
2326 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2327 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2328 << SourceRange(D.getIdentifierLoc());
2329 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002330 }
2331 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002332 if (!D.isInvalidType())
2333 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2334 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2335 << SourceRange(D.getIdentifierLoc());
2336 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002337 SC = FunctionDecl::None;
2338 }
Mike Stump11289f42009-09-09 15:08:12 +00002339
Chris Lattner38378bf2009-04-25 08:28:21 +00002340 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2341 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002342 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002343 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2344 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002345 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002346 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2347 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002348 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002349 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2350 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002351 }
Mike Stump11289f42009-09-09 15:08:12 +00002352
Douglas Gregor831c93f2008-11-05 20:51:48 +00002353 // Rebuild the function type "R" without any type qualifiers (in
2354 // case any of the errors above fired) and with "void" as the
2355 // return type, since constructors don't have return types. We
2356 // *always* have to do this, because GetTypeForDeclarator will
2357 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002358 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002359 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2360 Proto->getNumArgs(),
2361 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002362}
2363
Douglas Gregor4d87df52008-12-16 21:30:33 +00002364/// CheckConstructor - Checks a fully-formed constructor for
2365/// well-formedness, issuing any diagnostics required. Returns true if
2366/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002367void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002368 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002369 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2370 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002371 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002372
2373 // C++ [class.copy]p3:
2374 // A declaration of a constructor for a class X is ill-formed if
2375 // its first parameter is of type (optionally cv-qualified) X and
2376 // either there are no other parameters or else all other
2377 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002378 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002379 ((Constructor->getNumParams() == 1) ||
2380 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002381 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2382 Constructor->getTemplateSpecializationKind()
2383 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002384 QualType ParamType = Constructor->getParamDecl(0)->getType();
2385 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2386 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002387 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2388 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002389 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002390
2391 // FIXME: Rather that making the constructor invalid, we should endeavor
2392 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002393 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002394 }
2395 }
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregor4d87df52008-12-16 21:30:33 +00002397 // Notify the class that we've added a constructor.
2398 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002399}
2400
Anders Carlsson26a807d2009-11-30 21:24:50 +00002401/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2402/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002403bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002404 CXXRecordDecl *RD = Destructor->getParent();
2405
2406 if (Destructor->isVirtual()) {
2407 SourceLocation Loc;
2408
2409 if (!Destructor->isImplicit())
2410 Loc = Destructor->getLocation();
2411 else
2412 Loc = RD->getLocation();
2413
2414 // If we have a virtual destructor, look up the deallocation function
2415 FunctionDecl *OperatorDelete = 0;
2416 DeclarationName Name =
2417 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002418 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002419 return true;
2420
2421 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002422 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002423
2424 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002425}
2426
Mike Stump11289f42009-09-09 15:08:12 +00002427static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002428FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2429 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2430 FTI.ArgInfo[0].Param &&
2431 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2432}
2433
Douglas Gregor831c93f2008-11-05 20:51:48 +00002434/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2435/// the well-formednes of the destructor declarator @p D with type @p
2436/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002437/// emit diagnostics and set the declarator to invalid. Even if this happens,
2438/// will be updated to reflect a well-formed type for the destructor and
2439/// returned.
2440QualType Sema::CheckDestructorDeclarator(Declarator &D,
2441 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002442 // C++ [class.dtor]p1:
2443 // [...] A typedef-name that names a class is a class-name
2444 // (7.1.3); however, a typedef-name that names a class shall not
2445 // be used as the identifier in the declarator for a destructor
2446 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002447 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002448 if (isa<TypedefType>(DeclaratorType)) {
2449 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002450 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002451 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002452 }
2453
2454 // C++ [class.dtor]p2:
2455 // A destructor is used to destroy objects of its class type. A
2456 // destructor takes no parameters, and no return type can be
2457 // specified for it (not even void). The address of a destructor
2458 // shall not be taken. A destructor shall not be static. A
2459 // destructor can be invoked for a const, volatile or const
2460 // volatile object. A destructor shall not be declared const,
2461 // volatile or const volatile (9.3.2).
2462 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002463 if (!D.isInvalidType())
2464 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2465 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2466 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002467 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002468 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002469 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002470 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002471 // Destructors don't have return types, but the parser will
2472 // happily parse something like:
2473 //
2474 // class X {
2475 // float ~X();
2476 // };
2477 //
2478 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002479 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2480 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2481 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002482 }
Mike Stump11289f42009-09-09 15:08:12 +00002483
Chris Lattner38378bf2009-04-25 08:28:21 +00002484 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2485 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002486 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002487 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2488 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002489 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002490 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2491 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002492 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002493 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2494 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002495 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002496 }
2497
2498 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002499 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002500 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2501
2502 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002503 FTI.freeArgs();
2504 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002505 }
2506
Mike Stump11289f42009-09-09 15:08:12 +00002507 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002508 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002509 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002510 D.setInvalidType();
2511 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002512
2513 // Rebuild the function type "R" without any type qualifiers or
2514 // parameters (in case any of the errors above fired) and with
2515 // "void" as the return type, since destructors don't have return
2516 // types. We *always* have to do this, because GetTypeForDeclarator
2517 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002518 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002519}
2520
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002521/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2522/// well-formednes of the conversion function declarator @p D with
2523/// type @p R. If there are any errors in the declarator, this routine
2524/// will emit diagnostics and return true. Otherwise, it will return
2525/// false. Either way, the type @p R will be updated to reflect a
2526/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002527void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002528 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002529 // C++ [class.conv.fct]p1:
2530 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002531 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002532 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002533 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002534 if (!D.isInvalidType())
2535 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2536 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2537 << SourceRange(D.getIdentifierLoc());
2538 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002539 SC = FunctionDecl::None;
2540 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002541 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002542 // Conversion functions don't have return types, but the parser will
2543 // happily parse something like:
2544 //
2545 // class X {
2546 // float operator bool();
2547 // };
2548 //
2549 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002550 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2551 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2552 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002553 }
2554
2555 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002556 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002557 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2558
2559 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002560 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002561 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002562 }
2563
Mike Stump11289f42009-09-09 15:08:12 +00002564 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002565 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002566 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002567 D.setInvalidType();
2568 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002569
2570 // C++ [class.conv.fct]p4:
2571 // The conversion-type-id shall not represent a function type nor
2572 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002573 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002574 if (ConvType->isArrayType()) {
2575 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2576 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002577 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002578 } else if (ConvType->isFunctionType()) {
2579 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2580 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002581 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002582 }
2583
2584 // Rebuild the function type "R" without any parameters (in case any
2585 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002586 // return type.
2587 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002588 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002589
Douglas Gregor5fb53972009-01-14 15:45:31 +00002590 // C++0x explicit conversion operators.
2591 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002592 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002593 diag::warn_explicit_conversion_functions)
2594 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002595}
2596
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002597/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2598/// the declaration of the given C++ conversion function. This routine
2599/// is responsible for recording the conversion function in the C++
2600/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002601Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002602 assert(Conversion && "Expected to receive a conversion function declaration");
2603
Douglas Gregor4287b372008-12-12 08:25:50 +00002604 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002605
2606 // Make sure we aren't redeclaring the conversion function.
2607 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002608
2609 // C++ [class.conv.fct]p1:
2610 // [...] A conversion function is never used to convert a
2611 // (possibly cv-qualified) object to the (possibly cv-qualified)
2612 // same object type (or a reference to it), to a (possibly
2613 // cv-qualified) base class of that type (or a reference to it),
2614 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002615 // FIXME: Suppress this warning if the conversion function ends up being a
2616 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002617 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002618 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002619 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002620 ConvType = ConvTypeRef->getPointeeType();
2621 if (ConvType->isRecordType()) {
2622 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2623 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002624 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002625 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002626 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002627 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002628 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002629 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002630 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002631 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002632 }
2633
Douglas Gregor1dc98262008-12-26 15:00:45 +00002634 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002635 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002636 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002637 = Conversion->getDescribedFunctionTemplate())
2638 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCalld14a8642009-11-21 08:51:07 +00002639 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2640 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002641 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002642 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002643 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002644 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002645 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002646 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002647
Chris Lattner83f095c2009-03-28 19:18:32 +00002648 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002649}
2650
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002651//===----------------------------------------------------------------------===//
2652// Namespace Handling
2653//===----------------------------------------------------------------------===//
2654
2655/// ActOnStartNamespaceDef - This is called at the start of a namespace
2656/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002657Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2658 SourceLocation IdentLoc,
2659 IdentifierInfo *II,
2660 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002661 NamespaceDecl *Namespc =
2662 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2663 Namespc->setLBracLoc(LBrace);
2664
2665 Scope *DeclRegionScope = NamespcScope->getParent();
2666
2667 if (II) {
2668 // C++ [namespace.def]p2:
2669 // The identifier in an original-namespace-definition shall not have been
2670 // previously defined in the declarative region in which the
2671 // original-namespace-definition appears. The identifier in an
2672 // original-namespace-definition is the name of the namespace. Subsequently
2673 // in that declarative region, it is treated as an original-namespace-name.
2674
John McCall9f3059a2009-10-09 21:13:30 +00002675 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002676 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002677 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002678
Douglas Gregor91f84212008-12-11 16:49:14 +00002679 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2680 // This is an extended namespace definition.
2681 // Attach this namespace decl to the chain of extended namespace
2682 // definitions.
2683 OrigNS->setNextNamespace(Namespc);
2684 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002685
Mike Stump11289f42009-09-09 15:08:12 +00002686 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002687 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002688 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002689 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002690 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002691 } else if (PrevDecl) {
2692 // This is an invalid name redefinition.
2693 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2694 << Namespc->getDeclName();
2695 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2696 Namespc->setInvalidDecl();
2697 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002698 } else if (II->isStr("std") &&
2699 CurContext->getLookupContext()->isTranslationUnit()) {
2700 // This is the first "real" definition of the namespace "std", so update
2701 // our cache of the "std" namespace to point at this definition.
2702 if (StdNamespace) {
2703 // We had already defined a dummy namespace "std". Link this new
2704 // namespace definition to the dummy namespace "std".
2705 StdNamespace->setNextNamespace(Namespc);
2706 StdNamespace->setLocation(IdentLoc);
2707 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2708 }
2709
2710 // Make our StdNamespace cache point at the first real definition of the
2711 // "std" namespace.
2712 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002713 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002714
2715 PushOnScopeChains(Namespc, DeclRegionScope);
2716 } else {
John McCall4fa53422009-10-01 00:25:31 +00002717 // Anonymous namespaces.
2718
2719 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2720 // behaves as if it were replaced by
2721 // namespace unique { /* empty body */ }
2722 // using namespace unique;
2723 // namespace unique { namespace-body }
2724 // where all occurrences of 'unique' in a translation unit are
2725 // replaced by the same identifier and this identifier differs
2726 // from all other identifiers in the entire program.
2727
2728 // We just create the namespace with an empty name and then add an
2729 // implicit using declaration, just like the standard suggests.
2730 //
2731 // CodeGen enforces the "universally unique" aspect by giving all
2732 // declarations semantically contained within an anonymous
2733 // namespace internal linkage.
2734
2735 assert(Namespc->isAnonymousNamespace());
2736 CurContext->addDecl(Namespc);
2737
2738 UsingDirectiveDecl* UD
2739 = UsingDirectiveDecl::Create(Context, CurContext,
2740 /* 'using' */ LBrace,
2741 /* 'namespace' */ SourceLocation(),
2742 /* qualifier */ SourceRange(),
2743 /* NNS */ NULL,
2744 /* identifier */ SourceLocation(),
2745 Namespc,
2746 /* Ancestor */ CurContext);
2747 UD->setImplicit();
2748 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002749 }
2750
2751 // Although we could have an invalid decl (i.e. the namespace name is a
2752 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002753 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2754 // for the namespace has the declarations that showed up in that particular
2755 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002756 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002757 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002758}
2759
Sebastian Redla6602e92009-11-23 15:34:23 +00002760/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2761/// is a namespace alias, returns the namespace it points to.
2762static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2763 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2764 return AD->getNamespace();
2765 return dyn_cast_or_null<NamespaceDecl>(D);
2766}
2767
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002768/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2769/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002770void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2771 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002772 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2773 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2774 Namespc->setRBracLoc(RBrace);
2775 PopDeclContext();
2776}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002777
Chris Lattner83f095c2009-03-28 19:18:32 +00002778Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2779 SourceLocation UsingLoc,
2780 SourceLocation NamespcLoc,
2781 const CXXScopeSpec &SS,
2782 SourceLocation IdentLoc,
2783 IdentifierInfo *NamespcName,
2784 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002785 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2786 assert(NamespcName && "Invalid NamespcName.");
2787 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002788 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002789
Douglas Gregor889ceb72009-02-03 19:21:40 +00002790 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002791
Douglas Gregor34074322009-01-14 22:20:51 +00002792 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002793 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2794 LookupParsedName(R, S, &SS);
2795 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002796 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002797
John McCall9f3059a2009-10-09 21:13:30 +00002798 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002799 NamedDecl *Named = R.getFoundDecl();
2800 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2801 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002802 // C++ [namespace.udir]p1:
2803 // A using-directive specifies that the names in the nominated
2804 // namespace can be used in the scope in which the
2805 // using-directive appears after the using-directive. During
2806 // unqualified name lookup (3.4.1), the names appear as if they
2807 // were declared in the nearest enclosing namespace which
2808 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002809 // namespace. [Note: in this context, "contains" means "contains
2810 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002811
2812 // Find enclosing context containing both using-directive and
2813 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002814 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002815 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2816 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2817 CommonAncestor = CommonAncestor->getParent();
2818
Sebastian Redla6602e92009-11-23 15:34:23 +00002819 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002820 SS.getRange(),
2821 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00002822 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002823 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002824 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002825 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002826 }
2827
Douglas Gregor889ceb72009-02-03 19:21:40 +00002828 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002829 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002830 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002831}
2832
2833void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2834 // If scope has associated entity, then using directive is at namespace
2835 // or translation unit scope. We add UsingDirectiveDecls, into
2836 // it's lookup structure.
2837 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002838 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002839 else
2840 // Otherwise it is block-sope. using-directives will affect lookup
2841 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002842 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002843}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002844
Douglas Gregorfec52632009-06-20 00:51:54 +00002845
2846Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002847 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002848 SourceLocation UsingLoc,
2849 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002850 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002851 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002852 bool IsTypeName,
2853 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002854 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002855
Douglas Gregor220f4272009-11-04 16:30:06 +00002856 switch (Name.getKind()) {
2857 case UnqualifiedId::IK_Identifier:
2858 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00002859 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00002860 case UnqualifiedId::IK_ConversionFunctionId:
2861 break;
2862
2863 case UnqualifiedId::IK_ConstructorName:
2864 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2865 << SS.getRange();
2866 return DeclPtrTy();
2867
2868 case UnqualifiedId::IK_DestructorName:
2869 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2870 << SS.getRange();
2871 return DeclPtrTy();
2872
2873 case UnqualifiedId::IK_TemplateId:
2874 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2875 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2876 return DeclPtrTy();
2877 }
2878
2879 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3f746822009-11-17 05:59:44 +00002880 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002881 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002882 TargetName, AttrList,
2883 /* IsInstantiation */ false,
2884 IsTypeName, TypenameLoc);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002885 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002886 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002887 UD->setAccess(AS);
2888 }
Mike Stump11289f42009-09-09 15:08:12 +00002889
Anders Carlsson696a3f12009-08-28 05:40:36 +00002890 return DeclPtrTy::make(UD);
2891}
2892
John McCall3f746822009-11-17 05:59:44 +00002893/// Builds a shadow declaration corresponding to a 'using' declaration.
2894static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2895 AccessSpecifier AS,
2896 UsingDecl *UD, NamedDecl *Orig) {
2897 // FIXME: diagnose hiding, collisions
2898
2899 // If we resolved to another shadow declaration, just coalesce them.
2900 if (isa<UsingShadowDecl>(Orig)) {
2901 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2902 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2903 }
2904
2905 UsingShadowDecl *Shadow
2906 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2907 UD->getLocation(), UD, Orig);
2908 UD->addShadowDecl(Shadow);
2909
2910 if (S)
2911 SemaRef.PushOnScopeChains(Shadow, S);
2912 else
2913 SemaRef.CurContext->addDecl(Shadow);
2914 Shadow->setAccess(AS);
2915
2916 return Shadow;
2917}
2918
John McCalle61f2ba2009-11-18 02:36:19 +00002919/// Builds a using declaration.
2920///
2921/// \param IsInstantiation - Whether this call arises from an
2922/// instantiation of an unresolved using declaration. We treat
2923/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00002924NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2925 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002926 const CXXScopeSpec &SS,
2927 SourceLocation IdentLoc,
2928 DeclarationName Name,
2929 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002930 bool IsInstantiation,
2931 bool IsTypeName,
2932 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002933 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2934 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002935
Anders Carlssonf038fc22009-08-28 05:49:21 +00002936 // FIXME: We ignore attributes for now.
2937 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002938
Anders Carlsson59140b32009-08-28 03:16:11 +00002939 if (SS.isEmpty()) {
2940 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002941 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
2944 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002945 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2946
John McCall84c16cf2009-11-12 03:15:40 +00002947 DeclContext *LookupContext = computeDeclContext(SS);
2948 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00002949 if (IsTypeName) {
2950 return UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2951 UsingLoc, TypenameLoc,
2952 SS.getRange(), NNS,
2953 IdentLoc, Name);
2954 } else {
2955 return UnresolvedUsingValueDecl::Create(Context, CurContext,
2956 UsingLoc, SS.getRange(), NNS,
2957 IdentLoc, Name);
2958 }
Anders Carlssonf038fc22009-08-28 05:49:21 +00002959 }
Mike Stump11289f42009-09-09 15:08:12 +00002960
Anders Carlsson59140b32009-08-28 03:16:11 +00002961 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2962 // C++0x N2914 [namespace.udecl]p3:
2963 // A using-declaration used as a member-declaration shall refer to a member
2964 // of a base class of the class being defined, shall refer to a member of an
2965 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002966 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002967 // a member of a base class of the class being defined.
John McCall3f746822009-11-17 05:59:44 +00002968
John McCall84c16cf2009-11-12 03:15:40 +00002969 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2970 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlsson59140b32009-08-28 03:16:11 +00002971 Diag(SS.getRange().getBegin(),
2972 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2973 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002974 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002975 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002976 } else {
2977 // C++0x N2914 [namespace.udecl]p8:
2978 // A using-declaration for a class member shall be a member-declaration.
John McCall84c16cf2009-11-12 03:15:40 +00002979 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002980 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002981 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002982 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002983 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002984 }
2985
John McCall3f746822009-11-17 05:59:44 +00002986 // Look up the target name. Unlike most lookups, we do not want to
2987 // hide tag declarations: tag names are visible through the using
2988 // declaration even if hidden by ordinary names.
John McCall27b18f82009-11-17 02:14:36 +00002989 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00002990
2991 // We don't hide tags behind ordinary decls if we're in a
2992 // non-dependent context, but in a dependent context, this is
2993 // important for the stability of two-phase lookup.
2994 if (!IsInstantiation)
2995 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00002996
John McCall27b18f82009-11-17 02:14:36 +00002997 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00002998
John McCall9f3059a2009-10-09 21:13:30 +00002999 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003000 Diag(IdentLoc, diag::err_no_member)
3001 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003002 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00003003 }
3004
John McCall3f746822009-11-17 05:59:44 +00003005 if (R.isAmbiguous())
3006 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003007
John McCalle61f2ba2009-11-18 02:36:19 +00003008 if (IsTypeName) {
3009 // If we asked for a typename and got a non-type decl, error out.
3010 if (R.getResultKind() != LookupResult::Found
3011 || !isa<TypeDecl>(R.getFoundDecl())) {
3012 Diag(IdentLoc, diag::err_using_typename_non_type);
3013 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3014 Diag((*I)->getUnderlyingDecl()->getLocation(),
3015 diag::note_using_decl_target);
3016 return 0;
3017 }
3018 } else {
3019 // If we asked for a non-typename and we got a type, error out,
3020 // but only if this is an instantiation of an unresolved using
3021 // decl. Otherwise just silently find the type name.
3022 if (IsInstantiation &&
3023 R.getResultKind() == LookupResult::Found &&
3024 isa<TypeDecl>(R.getFoundDecl())) {
3025 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3026 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3027 return 0;
3028 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003029 }
3030
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003031 // C++0x N2914 [namespace.udecl]p6:
3032 // A using-declaration shall not name a namespace.
John McCall3f746822009-11-17 05:59:44 +00003033 if (R.getResultKind() == LookupResult::Found
3034 && isa<NamespaceDecl>(R.getFoundDecl())) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003035 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3036 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003037 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003038 }
Mike Stump11289f42009-09-09 15:08:12 +00003039
John McCall3f746822009-11-17 05:59:44 +00003040 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc,
3041 SS.getRange(), UsingLoc, NNS, Name,
3042 IsTypeName);
3043
3044 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3045 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3046
3047 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003048}
3049
Mike Stump11289f42009-09-09 15:08:12 +00003050Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003051 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003052 SourceLocation AliasLoc,
3053 IdentifierInfo *Alias,
3054 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003055 SourceLocation IdentLoc,
3056 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003057
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003058 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003059 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3060 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003061
Anders Carlssondca83c42009-03-28 06:23:46 +00003062 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003063 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003064 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003065 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003066 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003067 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003068 if (!R.isAmbiguous() && !R.empty() &&
3069 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003070 return DeclPtrTy();
3071 }
Mike Stump11289f42009-09-09 15:08:12 +00003072
Anders Carlssondca83c42009-03-28 06:23:46 +00003073 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3074 diag::err_redefinition_different_kind;
3075 Diag(AliasLoc, DiagID) << Alias;
3076 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003077 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003078 }
3079
John McCall27b18f82009-11-17 02:14:36 +00003080 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003081 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003082
John McCall9f3059a2009-10-09 21:13:30 +00003083 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003084 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003085 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003086 }
Mike Stump11289f42009-09-09 15:08:12 +00003087
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003088 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003089 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3090 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003091 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003092 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003093
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003094 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003095 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003096}
3097
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003098void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3099 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003100 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3101 !Constructor->isUsed()) &&
3102 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003103
Eli Friedman9cf6b592009-11-09 19:20:36 +00003104 CXXRecordDecl *ClassDecl
3105 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3106 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003107
Eli Friedman9cf6b592009-11-09 19:20:36 +00003108 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003109 Diag(CurrentLocation, diag::note_member_synthesized_at)
3110 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003111 Constructor->setInvalidDecl();
3112 } else {
3113 Constructor->setUsed();
3114 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00003115
3116 MaybeMarkVirtualImplicitMembersReferenced(CurrentLocation, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003117}
3118
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003119void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003120 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003121 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3122 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003123 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003124 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3125 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003126 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003127 // implicitly defined, all the implicitly-declared default destructors
3128 // for its base class and its non-static data members shall have been
3129 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003130 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3131 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003132 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003133 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003134 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003135 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003136 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3137 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3138 else
Mike Stump11289f42009-09-09 15:08:12 +00003139 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003140 "DefineImplicitDestructor - missing dtor in a base class");
3141 }
3142 }
Mike Stump11289f42009-09-09 15:08:12 +00003143
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003144 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3145 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003146 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3147 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3148 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003149 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003150 CXXRecordDecl *FieldClassDecl
3151 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3152 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003153 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003154 const_cast<CXXDestructorDecl*>(
3155 FieldClassDecl->getDestructor(Context)))
3156 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3157 else
Mike Stump11289f42009-09-09 15:08:12 +00003158 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003159 "DefineImplicitDestructor - missing dtor in class of a data member");
3160 }
3161 }
3162 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003163
3164 // FIXME: If CheckDestructor fails, we should emit a note about where the
3165 // implicit destructor was needed.
3166 if (CheckDestructor(Destructor)) {
3167 Diag(CurrentLocation, diag::note_member_synthesized_at)
3168 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3169
3170 Destructor->setInvalidDecl();
3171 return;
3172 }
3173
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003174 Destructor->setUsed();
3175}
3176
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003177void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3178 CXXMethodDecl *MethodDecl) {
3179 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3180 MethodDecl->getOverloadedOperator() == OO_Equal &&
3181 !MethodDecl->isUsed()) &&
3182 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003183
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003184 CXXRecordDecl *ClassDecl
3185 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003186
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003187 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003188 // Before the implicitly-declared copy assignment operator for a class is
3189 // implicitly defined, all implicitly-declared copy assignment operators
3190 // for its direct base classes and its nonstatic data members shall have
3191 // been implicitly defined.
3192 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003193 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3194 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003195 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003196 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003197 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003198 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3199 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3200 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003201 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3202 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003203 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3204 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3205 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003206 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003207 CXXRecordDecl *FieldClassDecl
3208 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003209 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003210 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3211 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003212 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003213 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003214 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3215 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003216 Diag(CurrentLocation, diag::note_first_required_here);
3217 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003218 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003219 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003220 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3221 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003222 Diag(CurrentLocation, diag::note_first_required_here);
3223 err = true;
3224 }
3225 }
3226 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003227 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003228}
3229
3230CXXMethodDecl *
3231Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3232 CXXRecordDecl *ClassDecl) {
3233 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3234 QualType RHSType(LHSType);
3235 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003236 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003237 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003238 RHSType = Context.getCVRQualifiedType(RHSType,
3239 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003240 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3241 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003242 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003243 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3244 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003245 SourceLocation()));
3246 Expr *Args[2] = { &*LHS, &*RHS };
3247 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003248 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003249 CandidateSet);
3250 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003251 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003252 ClassDecl->getLocation(), Best) == OR_Success)
3253 return cast<CXXMethodDecl>(Best->Function);
3254 assert(false &&
3255 "getAssignOperatorMethod - copy assignment operator method not found");
3256 return 0;
3257}
3258
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003259void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3260 CXXConstructorDecl *CopyConstructor,
3261 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003262 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003263 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3264 !CopyConstructor->isUsed()) &&
3265 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003266
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003267 CXXRecordDecl *ClassDecl
3268 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3269 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003270 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003271 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003272 // implicitly defined, all the implicitly-declared copy constructors
3273 // for its base class and its non-static data members shall have been
3274 // implicitly defined.
3275 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3276 Base != ClassDecl->bases_end(); ++Base) {
3277 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003278 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003279 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003280 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003281 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003282 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003283 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3284 FieldEnd = ClassDecl->field_end();
3285 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003286 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3287 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3288 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003289 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003290 CXXRecordDecl *FieldClassDecl
3291 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003292 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003293 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003294 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003295 }
3296 }
3297 CopyConstructor->setUsed();
3298}
3299
Anders Carlsson6eb55572009-08-25 05:12:04 +00003300Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003301Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003302 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003303 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003304 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003305
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003306 // C++ [class.copy]p15:
3307 // Whenever a temporary class object is copied using a copy constructor, and
3308 // this object and the copy have the same cv-unqualified type, an
3309 // implementation is permitted to treat the original and the copy as two
3310 // different ways of referring to the same object and not perform a copy at
3311 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003312
Anders Carlsson250aada2009-08-16 05:13:48 +00003313 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003314 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003315 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003316 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3317 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003318 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3319 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3320 E = ICE->getSubExpr();
3321
Anders Carlsson250aada2009-08-16 05:13:48 +00003322 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3323 Elidable = true;
3324 }
Mike Stump11289f42009-09-09 15:08:12 +00003325
3326 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003327 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003328}
3329
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003330/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3331/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003332Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003333Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3334 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003335 MultiExprArg ExprArgs) {
3336 unsigned NumExprs = ExprArgs.size();
3337 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003338
Douglas Gregor27381f32009-11-23 12:27:39 +00003339 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003340 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3341 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003342}
3343
Anders Carlsson574315a2009-08-27 05:08:22 +00003344Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003345Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3346 QualType Ty,
3347 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003348 MultiExprArg Args,
3349 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003350 unsigned NumExprs = Args.size();
3351 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003352
Douglas Gregor27381f32009-11-23 12:27:39 +00003353 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003354 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3355 TyBeginLoc, Exprs,
3356 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003357}
3358
3359
Mike Stump11289f42009-09-09 15:08:12 +00003360bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003361 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003362 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003363 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003364 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003365 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003366 if (TempResult.isInvalid())
3367 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003368
Anders Carlsson6eb55572009-08-25 05:12:04 +00003369 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003370 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003371 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003372 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003373
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003374 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003375}
3376
Mike Stump11289f42009-09-09 15:08:12 +00003377void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003378 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003379 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003380 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003381 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003382 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003383 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003384}
3385
Mike Stump11289f42009-09-09 15:08:12 +00003386/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003387/// ActOnDeclarator, when a C++ direct initializer is present.
3388/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003389void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3390 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003391 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003392 SourceLocation *CommaLocs,
3393 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003394 unsigned NumExprs = Exprs.size();
3395 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003396 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003397
3398 // If there is no declaration, there was an error parsing it. Just ignore
3399 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003400 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003401 return;
Mike Stump11289f42009-09-09 15:08:12 +00003402
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003403 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3404 if (!VDecl) {
3405 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3406 RealDecl->setInvalidDecl();
3407 return;
3408 }
3409
Douglas Gregor402250f2009-08-26 21:14:46 +00003410 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003411 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003412 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3413 //
3414 // Clients that want to distinguish between the two forms, can check for
3415 // direct initializer using VarDecl::hasCXXDirectInitializer().
3416 // A major benefit is that clients that don't particularly care about which
3417 // exactly form was it (like the CodeGen) can handle both cases without
3418 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003419
Douglas Gregor402250f2009-08-26 21:14:46 +00003420 // If either the declaration has a dependent type or if any of the expressions
3421 // is type-dependent, we represent the initialization via a ParenListExpr for
3422 // later use during template instantiation.
3423 if (VDecl->getType()->isDependentType() ||
3424 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3425 // Let clients know that initialization was done with a direct initializer.
3426 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003427
Douglas Gregor402250f2009-08-26 21:14:46 +00003428 // Store the initialization expressions as a ParenListExpr.
3429 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003430 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003431 new (Context) ParenListExpr(Context, LParenLoc,
3432 (Expr **)Exprs.release(),
3433 NumExprs, RParenLoc));
3434 return;
3435 }
Mike Stump11289f42009-09-09 15:08:12 +00003436
Douglas Gregor402250f2009-08-26 21:14:46 +00003437
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003438 // C++ 8.5p11:
3439 // The form of initialization (using parentheses or '=') is generally
3440 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003441 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003442 QualType DeclInitType = VDecl->getType();
3443 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003444 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003445
Douglas Gregor4044d992009-03-24 16:43:20 +00003446 // FIXME: This isn't the right place to complete the type.
3447 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3448 diag::err_typecheck_decl_incomplete_type)) {
3449 VDecl->setInvalidDecl();
3450 return;
3451 }
3452
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003453 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003454 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3455
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003456 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003457 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003458 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003459 VDecl->getLocation(),
3460 SourceRange(VDecl->getLocation(),
3461 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003462 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003463 IK_Direct,
3464 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003465 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003466 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003467 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003468 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003469 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003470 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003471 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003472 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003473 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003474 return;
3475 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003476
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003477 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003478 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3479 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003480 RealDecl->setInvalidDecl();
3481 return;
3482 }
3483
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003484 // Let clients know that initialization was done with a direct initializer.
3485 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003486
3487 assert(NumExprs == 1 && "Expected 1 expression");
3488 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003489 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3490 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003491}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003492
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003493/// \brief Add the applicable constructor candidates for an initialization
3494/// by constructor.
3495static void AddConstructorInitializationCandidates(Sema &SemaRef,
3496 QualType ClassType,
3497 Expr **Args,
3498 unsigned NumArgs,
3499 Sema::InitializationKind Kind,
3500 OverloadCandidateSet &CandidateSet) {
3501 // C++ [dcl.init]p14:
3502 // If the initialization is direct-initialization, or if it is
3503 // copy-initialization where the cv-unqualified version of the
3504 // source type is the same class as, or a derived class of, the
3505 // class of the destination, constructors are considered. The
3506 // applicable constructors are enumerated (13.3.1.3), and the
3507 // best one is chosen through overload resolution (13.3). The
3508 // constructor so selected is called to initialize the object,
3509 // with the initializer expression(s) as its argument(s). If no
3510 // constructor applies, or the overload resolution is ambiguous,
3511 // the initialization is ill-formed.
3512 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3513 assert(ClassRec && "Can only initialize a class type here");
3514
3515 // FIXME: When we decide not to synthesize the implicitly-declared
3516 // constructors, we'll need to make them appear here.
3517
3518 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3519 DeclarationName ConstructorName
3520 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3521 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3522 DeclContext::lookup_const_iterator Con, ConEnd;
3523 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3524 Con != ConEnd; ++Con) {
3525 // Find the constructor (which may be a template).
3526 CXXConstructorDecl *Constructor = 0;
3527 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3528 if (ConstructorTmpl)
3529 Constructor
3530 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3531 else
3532 Constructor = cast<CXXConstructorDecl>(*Con);
3533
3534 if ((Kind == Sema::IK_Direct) ||
3535 (Kind == Sema::IK_Copy &&
3536 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3537 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3538 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00003539 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3540 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003541 Args, NumArgs, CandidateSet);
3542 else
3543 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3544 }
3545 }
3546}
3547
3548/// \brief Attempt to perform initialization by constructor
3549/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3550/// copy-initialization.
3551///
3552/// This routine determines whether initialization by constructor is possible,
3553/// but it does not emit any diagnostics in the case where the initialization
3554/// is ill-formed.
3555///
3556/// \param ClassType the type of the object being initialized, which must have
3557/// class type.
3558///
3559/// \param Args the arguments provided to initialize the object
3560///
3561/// \param NumArgs the number of arguments provided to initialize the object
3562///
3563/// \param Kind the type of initialization being performed
3564///
3565/// \returns the constructor used to initialize the object, if successful.
3566/// Otherwise, emits a diagnostic and returns NULL.
3567CXXConstructorDecl *
3568Sema::TryInitializationByConstructor(QualType ClassType,
3569 Expr **Args, unsigned NumArgs,
3570 SourceLocation Loc,
3571 InitializationKind Kind) {
3572 // Build the overload candidate set
3573 OverloadCandidateSet CandidateSet;
3574 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3575 CandidateSet);
3576
3577 // Determine whether we found a constructor we can use.
3578 OverloadCandidateSet::iterator Best;
3579 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3580 case OR_Success:
3581 case OR_Deleted:
3582 // We found a constructor. Return it.
3583 return cast<CXXConstructorDecl>(Best->Function);
3584
3585 case OR_No_Viable_Function:
3586 case OR_Ambiguous:
3587 // Overload resolution failed. Return nothing.
3588 return 0;
3589 }
3590
3591 // Silence GCC warning
3592 return 0;
3593}
3594
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003595/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3596/// may occur as part of direct-initialization or copy-initialization.
3597///
3598/// \param ClassType the type of the object being initialized, which must have
3599/// class type.
3600///
3601/// \param ArgsPtr the arguments provided to initialize the object
3602///
3603/// \param Loc the source location where the initialization occurs
3604///
3605/// \param Range the source range that covers the entire initialization
3606///
3607/// \param InitEntity the name of the entity being initialized, if known
3608///
3609/// \param Kind the type of initialization being performed
3610///
3611/// \param ConvertedArgs a vector that will be filled in with the
3612/// appropriately-converted arguments to the constructor (if initialization
3613/// succeeded).
3614///
3615/// \returns the constructor used to initialize the object, if successful.
3616/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003617CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003618Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003619 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003620 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003621 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003622 InitializationKind Kind,
3623 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003624
3625 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003626 Expr **Args = (Expr **)ArgsPtr.get();
3627 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003628 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003629 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3630 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00003631
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003632 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003633 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003634 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003635 // We found a constructor. Break out so that we can convert the arguments
3636 // appropriately.
3637 break;
Mike Stump11289f42009-09-09 15:08:12 +00003638
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003639 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003640 if (InitEntity)
3641 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003642 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003643 else
3644 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003645 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003646 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003647 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003648
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003649 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003650 if (InitEntity)
3651 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3652 else
3653 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003654 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3655 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003656
3657 case OR_Deleted:
3658 if (InitEntity)
3659 Diag(Loc, diag::err_ovl_deleted_init)
3660 << Best->Function->isDeleted()
3661 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003662 else {
3663 const CXXRecordDecl *RD =
3664 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003665 Diag(Loc, diag::err_ovl_deleted_init)
3666 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003667 << RD->getDeclName() << Range;
3668 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00003669 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3670 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003673 // Convert the arguments, fill in default arguments, etc.
3674 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3675 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3676 return 0;
3677
3678 return Constructor;
3679}
3680
3681/// \brief Given a constructor and the set of arguments provided for the
3682/// constructor, convert the arguments and add any required default arguments
3683/// to form a proper call to this constructor.
3684///
3685/// \returns true if an error occurred, false otherwise.
3686bool
3687Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3688 MultiExprArg ArgsPtr,
3689 SourceLocation Loc,
3690 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3691 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3692 unsigned NumArgs = ArgsPtr.size();
3693 Expr **Args = (Expr **)ArgsPtr.get();
3694
3695 const FunctionProtoType *Proto
3696 = Constructor->getType()->getAs<FunctionProtoType>();
3697 assert(Proto && "Constructor without a prototype?");
3698 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003699
3700 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003701 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003702 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003703 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003704 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003705
3706 VariadicCallType CallType =
3707 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3708 llvm::SmallVector<Expr *, 8> AllArgs;
3709 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3710 Proto, 0, Args, NumArgs, AllArgs,
3711 CallType);
3712 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3713 ConvertedArgs.push_back(AllArgs[i]);
3714 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003715}
3716
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003717/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3718/// determine whether they are reference-related,
3719/// reference-compatible, reference-compatible with added
3720/// qualification, or incompatible, for use in C++ initialization by
3721/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3722/// type, and the first type (T1) is the pointee type of the reference
3723/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003724Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003725Sema::CompareReferenceRelationship(SourceLocation Loc,
3726 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003727 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003728 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003729 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003730 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003731
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003732 QualType T1 = Context.getCanonicalType(OrigT1);
3733 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003734 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3735 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003736
3737 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003738 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003739 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003740 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003741 if (UnqualT1 == UnqualT2)
3742 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003743 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3744 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3745 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003746 DerivedToBase = true;
3747 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003748 return Ref_Incompatible;
3749
3750 // At this point, we know that T1 and T2 are reference-related (at
3751 // least).
3752
3753 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003754 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003755 // reference-related to T2 and cv1 is the same cv-qualification
3756 // as, or greater cv-qualification than, cv2. For purposes of
3757 // overload resolution, cases for which cv1 is greater
3758 // cv-qualification than cv2 are identified as
3759 // reference-compatible with added qualification (see 13.3.3.2).
3760 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3761 return Ref_Compatible;
3762 else if (T1.isMoreQualifiedThan(T2))
3763 return Ref_Compatible_With_Added_Qualification;
3764 else
3765 return Ref_Related;
3766}
3767
3768/// CheckReferenceInit - Check the initialization of a reference
3769/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3770/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003771/// list), and DeclType is the type of the declaration. When ICS is
3772/// non-null, this routine will compute the implicit conversion
3773/// sequence according to C++ [over.ics.ref] and will not produce any
3774/// diagnostics; when ICS is null, it will emit diagnostics when any
3775/// errors are found. Either way, a return value of true indicates
3776/// that there was a failure, a return value of false indicates that
3777/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003778///
3779/// When @p SuppressUserConversions, user-defined conversions are
3780/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003781/// When @p AllowExplicit, we also permit explicit user-defined
3782/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003783/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00003784/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3785/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00003786bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003787Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003788 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003789 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003790 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00003791 ImplicitConversionSequence *ICS,
3792 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003793 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3794
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003795 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003796 QualType T2 = Init->getType();
3797
Douglas Gregorcd695e52008-11-10 20:40:00 +00003798 // If the initializer is the address of an overloaded function, try
3799 // to resolve the overloaded function. If all goes well, T2 is the
3800 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003801 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003802 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003803 ICS != 0);
3804 if (Fn) {
3805 // Since we're performing this reference-initialization for
3806 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003807 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003808 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003809 return true;
3810
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003811 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003812 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003813
3814 T2 = Fn->getType();
3815 }
3816 }
3817
Douglas Gregor786ab212008-10-29 02:00:59 +00003818 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003819 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003820 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003821 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3822 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003823 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003824 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003825
3826 // Most paths end in a failed conversion.
3827 if (ICS)
3828 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003829
3830 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003831 // A reference to type "cv1 T1" is initialized by an expression
3832 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003833
3834 // -- If the initializer expression
3835
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003836 // Rvalue references cannot bind to lvalues (N2812).
3837 // There is absolutely no situation where they can. In particular, note that
3838 // this is ill-formed, even if B has a user-defined conversion to A&&:
3839 // B b;
3840 // A&& r = b;
3841 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3842 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003843 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003844 << Init->getSourceRange();
3845 return true;
3846 }
3847
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003848 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003849 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3850 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003851 //
3852 // Note that the bit-field check is skipped if we are just computing
3853 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003854 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003855 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003856 BindsDirectly = true;
3857
Douglas Gregor786ab212008-10-29 02:00:59 +00003858 if (ICS) {
3859 // C++ [over.ics.ref]p1:
3860 // When a parameter of reference type binds directly (8.5.3)
3861 // to an argument expression, the implicit conversion sequence
3862 // is the identity conversion, unless the argument expression
3863 // has a type that is a derived class of the parameter type,
3864 // in which case the implicit conversion sequence is a
3865 // derived-to-base Conversion (13.3.3.1).
3866 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3867 ICS->Standard.First = ICK_Identity;
3868 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3869 ICS->Standard.Third = ICK_Identity;
3870 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3871 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003872 ICS->Standard.ReferenceBinding = true;
3873 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003874 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003875 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003876
3877 // Nothing more to do: the inaccessibility/ambiguity check for
3878 // derived-to-base conversions is suppressed when we're
3879 // computing the implicit conversion sequence (C++
3880 // [over.best.ics]p2).
3881 return false;
3882 } else {
3883 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003884 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3885 if (DerivedToBase)
3886 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003887 else if(CheckExceptionSpecCompatibility(Init, T1))
3888 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003889 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003890 }
3891 }
3892
3893 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003894 // implicitly converted to an lvalue of type "cv3 T3,"
3895 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003896 // 92) (this conversion is selected by enumerating the
3897 // applicable conversion functions (13.3.1.6) and choosing
3898 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003899 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003900 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003901 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003902 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003903
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003904 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00003905 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003906 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003907 for (UnresolvedSet::iterator I = Conversions->begin(),
3908 E = Conversions->end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00003909 FunctionTemplateDecl *ConvTemplate
John McCalld14a8642009-11-21 08:51:07 +00003910 = dyn_cast<FunctionTemplateDecl>(*I);
Douglas Gregor05155d82009-08-21 23:19:43 +00003911 CXXConversionDecl *Conv;
3912 if (ConvTemplate)
3913 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3914 else
John McCalld14a8642009-11-21 08:51:07 +00003915 Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003916
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003917 // If the conversion function doesn't return a reference type,
3918 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003919 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003920 (AllowExplicit || !Conv->isExplicit())) {
3921 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003922 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003923 CandidateSet);
3924 else
3925 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3926 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003927 }
3928
3929 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003930 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003931 case OR_Success:
3932 // This is a direct binding.
3933 BindsDirectly = true;
3934
3935 if (ICS) {
3936 // C++ [over.ics.ref]p1:
3937 //
3938 // [...] If the parameter binds directly to the result of
3939 // applying a conversion function to the argument
3940 // expression, the implicit conversion sequence is a
3941 // user-defined conversion sequence (13.3.3.1.2), with the
3942 // second standard conversion sequence either an identity
3943 // conversion or, if the conversion function returns an
3944 // entity of a type that is a derived class of the parameter
3945 // type, a derived-to-base Conversion.
3946 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3947 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3948 ICS->UserDefined.After = Best->FinalConversion;
3949 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003950 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003951 assert(ICS->UserDefined.After.ReferenceBinding &&
3952 ICS->UserDefined.After.DirectBinding &&
3953 "Expected a direct reference binding!");
3954 return false;
3955 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003956 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003957 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003958 CastExpr::CK_UserDefinedConversion,
3959 cast<CXXMethodDecl>(Best->Function),
3960 Owned(Init));
3961 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003962
3963 if (CheckExceptionSpecCompatibility(Init, T1))
3964 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003965 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3966 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003967 }
3968 break;
3969
3970 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003971 if (ICS) {
3972 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3973 Cand != CandidateSet.end(); ++Cand)
3974 if (Cand->Viable)
3975 ICS->ConversionFunctionSet.push_back(Cand->Function);
3976 break;
3977 }
3978 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3979 << Init->getSourceRange();
3980 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003981 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003982
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003983 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003984 case OR_Deleted:
3985 // There was no suitable conversion, or we found a deleted
3986 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003987 break;
3988 }
3989 }
Mike Stump11289f42009-09-09 15:08:12 +00003990
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003991 if (BindsDirectly) {
3992 // C++ [dcl.init.ref]p4:
3993 // [...] In all cases where the reference-related or
3994 // reference-compatible relationship of two types is used to
3995 // establish the validity of a reference binding, and T1 is a
3996 // base class of T2, a program that necessitates such a binding
3997 // is ill-formed if T1 is an inaccessible (clause 11) or
3998 // ambiguous (10.2) base class of T2.
3999 //
4000 // Note that we only check this condition when we're allowed to
4001 // complain about errors, because we should not be checking for
4002 // ambiguity (or inaccessibility) unless the reference binding
4003 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004004 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004005 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004006 Init->getSourceRange(),
4007 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004008 else
4009 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004010 }
4011
4012 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004013 // type (i.e., cv1 shall be const), or the reference shall be an
4014 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004015 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004016 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004017 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004018 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4019 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004020 return true;
4021 }
4022
4023 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004024 // class type, and "cv1 T1" is reference-compatible with
4025 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004026 // following ways (the choice is implementation-defined):
4027 //
4028 // -- The reference is bound to the object represented by
4029 // the rvalue (see 3.10) or to a sub-object within that
4030 // object.
4031 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004032 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004033 // a constructor is called to copy the entire rvalue
4034 // object into the temporary. The reference is bound to
4035 // the temporary or to a sub-object within the
4036 // temporary.
4037 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004038 // The constructor that would be used to make the copy
4039 // shall be callable whether or not the copy is actually
4040 // done.
4041 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004042 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004043 // freedom, so we will always take the first option and never build
4044 // a temporary in this case. FIXME: We will, however, have to check
4045 // for the presence of a copy constructor in C++98/03 mode.
4046 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004047 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4048 if (ICS) {
4049 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4050 ICS->Standard.First = ICK_Identity;
4051 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4052 ICS->Standard.Third = ICK_Identity;
4053 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4054 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004055 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004056 ICS->Standard.DirectBinding = false;
4057 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004058 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004059 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004060 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4061 if (DerivedToBase)
4062 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004063 else if(CheckExceptionSpecCompatibility(Init, T1))
4064 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004065 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004066 }
4067 return false;
4068 }
4069
Eli Friedman44b83ee2009-08-05 19:21:58 +00004070 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004071 // initialized from the initializer expression using the
4072 // rules for a non-reference copy initialization (8.5). The
4073 // reference is then bound to the temporary. If T1 is
4074 // reference-related to T2, cv1 must be the same
4075 // cv-qualification as, or greater cv-qualification than,
4076 // cv2; otherwise, the program is ill-formed.
4077 if (RefRelationship == Ref_Related) {
4078 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4079 // we would be reference-compatible or reference-compatible with
4080 // added qualification. But that wasn't the case, so the reference
4081 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004082 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004083 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004084 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4085 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004086 return true;
4087 }
4088
Douglas Gregor576e98c2009-01-30 23:27:23 +00004089 // If at least one of the types is a class type, the types are not
4090 // related, and we aren't allowed any user conversions, the
4091 // reference binding fails. This case is important for breaking
4092 // recursion, since TryImplicitConversion below will attempt to
4093 // create a temporary through the use of a copy constructor.
4094 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4095 (T1->isRecordType() || T2->isRecordType())) {
4096 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004097 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00004098 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4099 return true;
4100 }
4101
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004102 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004103 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004104 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004105 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004106 // When a parameter of reference type is not bound directly to
4107 // an argument expression, the conversion sequence is the one
4108 // required to convert the argument expression to the
4109 // underlying type of the reference according to
4110 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4111 // to copy-initializing a temporary of the underlying type with
4112 // the argument expression. Any difference in top-level
4113 // cv-qualification is subsumed by the initialization itself
4114 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004115 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4116 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004117 /*ForceRValue=*/false,
4118 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004119
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004120 // Of course, that's still a reference binding.
4121 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4122 ICS->Standard.ReferenceBinding = true;
4123 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004124 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004125 ImplicitConversionSequence::UserDefinedConversion) {
4126 ICS->UserDefined.After.ReferenceBinding = true;
4127 ICS->UserDefined.After.RRefBinding = isRValRef;
4128 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004129 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4130 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004131 ImplicitConversionSequence Conversions;
4132 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4133 false, false,
4134 Conversions);
4135 if (badConversion) {
4136 if ((Conversions.ConversionKind ==
4137 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004138 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004139 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004140 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4141 for (int j = Conversions.ConversionFunctionSet.size()-1;
4142 j >= 0; j--) {
4143 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4144 Diag(Func->getLocation(), diag::err_ovl_candidate);
4145 }
4146 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004147 else {
4148 if (isRValRef)
4149 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4150 << Init->getSourceRange();
4151 else
4152 Diag(DeclLoc, diag::err_invalid_initialization)
4153 << DeclType << Init->getType() << Init->getSourceRange();
4154 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004155 }
4156 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004157 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004158}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004159
4160/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4161/// of this overloaded operator is well-formed. If so, returns false;
4162/// otherwise, emits appropriate diagnostics and returns true.
4163bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004164 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004165 "Expected an overloaded operator declaration");
4166
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004167 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4168
Mike Stump11289f42009-09-09 15:08:12 +00004169 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004170 // The allocation and deallocation functions, operator new,
4171 // operator new[], operator delete and operator delete[], are
4172 // described completely in 3.7.3. The attributes and restrictions
4173 // found in the rest of this subclause do not apply to them unless
4174 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004175 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004176 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004177 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004178
4179 if (Op == OO_New || Op == OO_Array_New) {
4180 bool ret = false;
4181 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4182 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4183 QualType T = Context.getCanonicalType((*Param)->getType());
4184 if (!T->isDependentType() && SizeTy != T) {
4185 Diag(FnDecl->getLocation(),
4186 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4187 << SizeTy;
4188 ret = true;
4189 }
4190 }
4191 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4192 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4193 return Diag(FnDecl->getLocation(),
4194 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004195 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004196 return ret;
4197 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004198
4199 // C++ [over.oper]p6:
4200 // An operator function shall either be a non-static member
4201 // function or be a non-member function and have at least one
4202 // parameter whose type is a class, a reference to a class, an
4203 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004204 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4205 if (MethodDecl->isStatic())
4206 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004207 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004208 } else {
4209 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004210 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4211 ParamEnd = FnDecl->param_end();
4212 Param != ParamEnd; ++Param) {
4213 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004214 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4215 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004216 ClassOrEnumParam = true;
4217 break;
4218 }
4219 }
4220
Douglas Gregord69246b2008-11-17 16:14:12 +00004221 if (!ClassOrEnumParam)
4222 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004223 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004224 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004225 }
4226
4227 // C++ [over.oper]p8:
4228 // An operator function cannot have default arguments (8.3.6),
4229 // except where explicitly stated below.
4230 //
Mike Stump11289f42009-09-09 15:08:12 +00004231 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004232 // (C++ [over.call]p1).
4233 if (Op != OO_Call) {
4234 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4235 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004236 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004237 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004238 diag::err_operator_overload_default_arg)
4239 << FnDecl->getDeclName();
4240 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004241 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004242 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004243 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004244 }
4245 }
4246
Douglas Gregor6cf08062008-11-10 13:38:07 +00004247 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4248 { false, false, false }
4249#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4250 , { Unary, Binary, MemberOnly }
4251#include "clang/Basic/OperatorKinds.def"
4252 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004253
Douglas Gregor6cf08062008-11-10 13:38:07 +00004254 bool CanBeUnaryOperator = OperatorUses[Op][0];
4255 bool CanBeBinaryOperator = OperatorUses[Op][1];
4256 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004257
4258 // C++ [over.oper]p8:
4259 // [...] Operator functions cannot have more or fewer parameters
4260 // than the number required for the corresponding operator, as
4261 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004262 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004263 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004264 if (Op != OO_Call &&
4265 ((NumParams == 1 && !CanBeUnaryOperator) ||
4266 (NumParams == 2 && !CanBeBinaryOperator) ||
4267 (NumParams < 1) || (NumParams > 2))) {
4268 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004269 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004270 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004271 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004272 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004273 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004274 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004275 assert(CanBeBinaryOperator &&
4276 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004277 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004278 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004279
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004280 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004281 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004282 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004283
Douglas Gregord69246b2008-11-17 16:14:12 +00004284 // Overloaded operators other than operator() cannot be variadic.
4285 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004286 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004287 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004288 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004289 }
4290
4291 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004292 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4293 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004294 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004295 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004296 }
4297
4298 // C++ [over.inc]p1:
4299 // The user-defined function called operator++ implements the
4300 // prefix and postfix ++ operator. If this function is a member
4301 // function with no parameters, or a non-member function with one
4302 // parameter of class or enumeration type, it defines the prefix
4303 // increment operator ++ for objects of that type. If the function
4304 // is a member function with one parameter (which shall be of type
4305 // int) or a non-member function with two parameters (the second
4306 // of which shall be of type int), it defines the postfix
4307 // increment operator ++ for objects of that type.
4308 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4309 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4310 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004311 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004312 ParamIsInt = BT->getKind() == BuiltinType::Int;
4313
Chris Lattner2b786902008-11-21 07:50:02 +00004314 if (!ParamIsInt)
4315 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004316 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004317 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004318 }
4319
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004320 // Notify the class if it got an assignment operator.
4321 if (Op == OO_Equal) {
4322 // Would have returned earlier otherwise.
4323 assert(isa<CXXMethodDecl>(FnDecl) &&
4324 "Overloaded = not member, but not filtered.");
4325 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4326 Method->getParent()->addedAssignmentOperator(Context, Method);
4327 }
4328
Douglas Gregord69246b2008-11-17 16:14:12 +00004329 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004330}
Chris Lattner3b024a32008-12-17 07:09:26 +00004331
Douglas Gregor07665a62009-01-05 19:45:36 +00004332/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4333/// linkage specification, including the language and (if present)
4334/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4335/// the location of the language string literal, which is provided
4336/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4337/// the '{' brace. Otherwise, this linkage specification does not
4338/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004339Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4340 SourceLocation ExternLoc,
4341 SourceLocation LangLoc,
4342 const char *Lang,
4343 unsigned StrSize,
4344 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004345 LinkageSpecDecl::LanguageIDs Language;
4346 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4347 Language = LinkageSpecDecl::lang_c;
4348 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4349 Language = LinkageSpecDecl::lang_cxx;
4350 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004351 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004352 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004353 }
Mike Stump11289f42009-09-09 15:08:12 +00004354
Chris Lattner438e5012008-12-17 07:13:27 +00004355 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004356
Douglas Gregor07665a62009-01-05 19:45:36 +00004357 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004358 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004359 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004360 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004361 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004362 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004363}
4364
Douglas Gregor07665a62009-01-05 19:45:36 +00004365/// ActOnFinishLinkageSpecification - Completely the definition of
4366/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4367/// valid, it's the position of the closing '}' brace in a linkage
4368/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004369Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4370 DeclPtrTy LinkageSpec,
4371 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004372 if (LinkageSpec)
4373 PopDeclContext();
4374 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004375}
4376
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004377/// \brief Perform semantic analysis for the variable declaration that
4378/// occurs within a C++ catch clause, returning the newly-created
4379/// variable.
4380VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004381 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004382 IdentifierInfo *Name,
4383 SourceLocation Loc,
4384 SourceRange Range) {
4385 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004386
4387 // Arrays and functions decay.
4388 if (ExDeclType->isArrayType())
4389 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4390 else if (ExDeclType->isFunctionType())
4391 ExDeclType = Context.getPointerType(ExDeclType);
4392
4393 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4394 // The exception-declaration shall not denote a pointer or reference to an
4395 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004396 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004397 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004398 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004399 Invalid = true;
4400 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004401
Sebastian Redl54c04d42008-12-22 19:15:10 +00004402 QualType BaseType = ExDeclType;
4403 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004404 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004405 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004406 BaseType = Ptr->getPointeeType();
4407 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004408 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004409 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004410 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004411 BaseType = Ref->getPointeeType();
4412 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004413 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004414 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004415 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004416 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004417 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004418
Mike Stump11289f42009-09-09 15:08:12 +00004419 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004420 RequireNonAbstractType(Loc, ExDeclType,
4421 diag::err_abstract_type_in_decl,
4422 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004423 Invalid = true;
4424
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004425 // FIXME: Need to test for ability to copy-construct and destroy the
4426 // exception variable.
4427
Sebastian Redl9b244a82008-12-22 21:35:02 +00004428 // FIXME: Need to check for abstract classes.
4429
Mike Stump11289f42009-09-09 15:08:12 +00004430 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004431 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004432
4433 if (Invalid)
4434 ExDecl->setInvalidDecl();
4435
4436 return ExDecl;
4437}
4438
4439/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4440/// handler.
4441Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004442 DeclaratorInfo *DInfo = 0;
4443 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004444
4445 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004446 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004447 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004448 // The scope should be freshly made just for us. There is just no way
4449 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004450 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004451 if (PrevDecl->isTemplateParameter()) {
4452 // Maybe we will complain about the shadowed template parameter.
4453 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004454 }
4455 }
4456
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004457 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004458 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4459 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004460 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004461 }
4462
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004463 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004464 D.getIdentifier(),
4465 D.getIdentifierLoc(),
4466 D.getDeclSpec().getSourceRange());
4467
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004468 if (Invalid)
4469 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004470
Sebastian Redl54c04d42008-12-22 19:15:10 +00004471 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004472 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004473 PushOnScopeChains(ExDecl, S);
4474 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004475 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004476
Douglas Gregor758a8692009-06-17 21:51:59 +00004477 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004478 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004479}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004480
Mike Stump11289f42009-09-09 15:08:12 +00004481Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004482 ExprArg assertexpr,
4483 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004484 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004485 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004486 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4487
Anders Carlsson54b26982009-03-14 00:33:21 +00004488 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4489 llvm::APSInt Value(32);
4490 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4491 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4492 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004493 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004494 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004495
Anders Carlsson54b26982009-03-14 00:33:21 +00004496 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004497 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004498 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004499 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004500 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004501 }
4502 }
Mike Stump11289f42009-09-09 15:08:12 +00004503
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004504 assertexpr.release();
4505 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004506 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004507 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004508
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004509 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004510 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004511}
Sebastian Redlf769df52009-03-24 22:27:57 +00004512
John McCall11083da2009-09-16 22:47:08 +00004513/// Handle a friend type declaration. This works in tandem with
4514/// ActOnTag.
4515///
4516/// Notes on friend class templates:
4517///
4518/// We generally treat friend class declarations as if they were
4519/// declaring a class. So, for example, the elaborated type specifier
4520/// in a friend declaration is required to obey the restrictions of a
4521/// class-head (i.e. no typedefs in the scope chain), template
4522/// parameters are required to match up with simple template-ids, &c.
4523/// However, unlike when declaring a template specialization, it's
4524/// okay to refer to a template specialization without an empty
4525/// template parameter declaration, e.g.
4526/// friend class A<T>::B<unsigned>;
4527/// We permit this as a special case; if there are any template
4528/// parameters present at all, require proper matching, i.e.
4529/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004530Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004531 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004532 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004533
4534 assert(DS.isFriendSpecified());
4535 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4536
John McCall11083da2009-09-16 22:47:08 +00004537 // Try to convert the decl specifier to a type. This works for
4538 // friend templates because ActOnTag never produces a ClassTemplateDecl
4539 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004540 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004541 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4542 if (TheDeclarator.isInvalidType())
4543 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004544
John McCall11083da2009-09-16 22:47:08 +00004545 // This is definitely an error in C++98. It's probably meant to
4546 // be forbidden in C++0x, too, but the specification is just
4547 // poorly written.
4548 //
4549 // The problem is with declarations like the following:
4550 // template <T> friend A<T>::foo;
4551 // where deciding whether a class C is a friend or not now hinges
4552 // on whether there exists an instantiation of A that causes
4553 // 'foo' to equal C. There are restrictions on class-heads
4554 // (which we declare (by fiat) elaborated friend declarations to
4555 // be) that makes this tractable.
4556 //
4557 // FIXME: handle "template <> friend class A<T>;", which
4558 // is possibly well-formed? Who even knows?
4559 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4560 Diag(Loc, diag::err_tagless_friend_type_template)
4561 << DS.getSourceRange();
4562 return DeclPtrTy();
4563 }
4564
John McCallaa74a0c2009-08-28 07:59:38 +00004565 // C++ [class.friend]p2:
4566 // An elaborated-type-specifier shall be used in a friend declaration
4567 // for a class.*
4568 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004569 // This is one of the rare places in Clang where it's legitimate to
4570 // ask about the "spelling" of the type.
4571 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4572 // If we evaluated the type to a record type, suggest putting
4573 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004574 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004575 RecordDecl *RD = RT->getDecl();
4576
4577 std::string InsertionText = std::string(" ") + RD->getKindName();
4578
John McCallc3987482009-10-07 23:34:25 +00004579 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4580 << (unsigned) RD->getTagKind()
4581 << T
4582 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004583 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4584 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004585 return DeclPtrTy();
4586 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004587 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4588 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004589 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004590 }
4591 }
4592
John McCallc3987482009-10-07 23:34:25 +00004593 // Enum types cannot be friends.
4594 if (T->getAs<EnumType>()) {
4595 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4596 << SourceRange(DS.getFriendSpecLoc());
4597 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004598 }
John McCallaa74a0c2009-08-28 07:59:38 +00004599
John McCallaa74a0c2009-08-28 07:59:38 +00004600 // C++98 [class.friend]p1: A friend of a class is a function
4601 // or class that is not a member of the class . . .
4602 // But that's a silly restriction which nobody implements for
4603 // inner classes, and C++0x removes it anyway, so we only report
4604 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004605 if (!getLangOptions().CPlusPlus0x)
4606 if (const RecordType *RT = T->getAs<RecordType>())
4607 if (RT->getDecl()->getDeclContext() == CurContext)
4608 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004609
John McCall11083da2009-09-16 22:47:08 +00004610 Decl *D;
4611 if (TempParams.size())
4612 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4613 TempParams.size(),
4614 (TemplateParameterList**) TempParams.release(),
4615 T.getTypePtr(),
4616 DS.getFriendSpecLoc());
4617 else
4618 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4619 DS.getFriendSpecLoc());
4620 D->setAccess(AS_public);
4621 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004622
John McCall11083da2009-09-16 22:47:08 +00004623 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004624}
4625
John McCall2f212b32009-09-11 21:02:39 +00004626Sema::DeclPtrTy
4627Sema::ActOnFriendFunctionDecl(Scope *S,
4628 Declarator &D,
4629 bool IsDefinition,
4630 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004631 const DeclSpec &DS = D.getDeclSpec();
4632
4633 assert(DS.isFriendSpecified());
4634 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4635
4636 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004637 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004638 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004639
4640 // C++ [class.friend]p1
4641 // A friend of a class is a function or class....
4642 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004643 // It *doesn't* see through dependent types, which is correct
4644 // according to [temp.arg.type]p3:
4645 // If a declaration acquires a function type through a
4646 // type dependent on a template-parameter and this causes
4647 // a declaration that does not use the syntactic form of a
4648 // function declarator to have a function type, the program
4649 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004650 if (!T->isFunctionType()) {
4651 Diag(Loc, diag::err_unexpected_friend);
4652
4653 // It might be worthwhile to try to recover by creating an
4654 // appropriate declaration.
4655 return DeclPtrTy();
4656 }
4657
4658 // C++ [namespace.memdef]p3
4659 // - If a friend declaration in a non-local class first declares a
4660 // class or function, the friend class or function is a member
4661 // of the innermost enclosing namespace.
4662 // - The name of the friend is not found by simple name lookup
4663 // until a matching declaration is provided in that namespace
4664 // scope (either before or after the class declaration granting
4665 // friendship).
4666 // - If a friend function is called, its name may be found by the
4667 // name lookup that considers functions from namespaces and
4668 // classes associated with the types of the function arguments.
4669 // - When looking for a prior declaration of a class or a function
4670 // declared as a friend, scopes outside the innermost enclosing
4671 // namespace scope are not considered.
4672
John McCallaa74a0c2009-08-28 07:59:38 +00004673 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4674 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004675 assert(Name);
4676
John McCall07e91c02009-08-06 02:15:43 +00004677 // The context we found the declaration in, or in which we should
4678 // create the declaration.
4679 DeclContext *DC;
4680
4681 // FIXME: handle local classes
4682
4683 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00004684 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4685 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00004686 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004687 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004688 DC = computeDeclContext(ScopeQual);
4689
4690 // FIXME: handle dependent contexts
4691 if (!DC) return DeclPtrTy();
4692
John McCall1f82f242009-11-18 22:49:29 +00004693 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004694
4695 // If searching in that context implicitly found a declaration in
4696 // a different context, treat it like it wasn't found at all.
4697 // TODO: better diagnostics for this case. Suggesting the right
4698 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00004699 // FIXME: getRepresentativeDecl() is not right here at all
4700 if (Previous.empty() ||
4701 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004702 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004703 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4704 return DeclPtrTy();
4705 }
4706
4707 // C++ [class.friend]p1: A friend of a class is a function or
4708 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004709 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004710 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4711
John McCall07e91c02009-08-06 02:15:43 +00004712 // Otherwise walk out to the nearest namespace scope looking for matches.
4713 } else {
4714 // TODO: handle local class contexts.
4715
4716 DC = CurContext;
4717 while (true) {
4718 // Skip class contexts. If someone can cite chapter and verse
4719 // for this behavior, that would be nice --- it's what GCC and
4720 // EDG do, and it seems like a reasonable intent, but the spec
4721 // really only says that checks for unqualified existing
4722 // declarations should stop at the nearest enclosing namespace,
4723 // not that they should only consider the nearest enclosing
4724 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004725 while (DC->isRecord())
4726 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004727
John McCall1f82f242009-11-18 22:49:29 +00004728 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004729
4730 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00004731 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00004732 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004733
John McCall07e91c02009-08-06 02:15:43 +00004734 if (DC->isFileContext()) break;
4735 DC = DC->getParent();
4736 }
4737
4738 // C++ [class.friend]p1: A friend of a class is a function or
4739 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004740 // C++0x changes this for both friend types and functions.
4741 // Most C++ 98 compilers do seem to give an error here, so
4742 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00004743 if (!Previous.empty() && DC->Equals(CurContext)
4744 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004745 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4746 }
4747
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004748 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004749 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004750 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4751 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4752 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004753 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004754 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4755 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004756 return DeclPtrTy();
4757 }
John McCall07e91c02009-08-06 02:15:43 +00004758 }
4759
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004760 bool Redeclaration = false;
John McCall1f82f242009-11-18 22:49:29 +00004761 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004762 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004763 IsDefinition,
4764 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004765 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004766
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004767 assert(ND->getDeclContext() == DC);
4768 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004769
John McCall759e32b2009-08-31 22:39:49 +00004770 // Add the function declaration to the appropriate lookup tables,
4771 // adjusting the redeclarations list as necessary. We don't
4772 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004773 //
John McCall759e32b2009-08-31 22:39:49 +00004774 // Also update the scope-based lookup if the target context's
4775 // lookup context is in lexical scope.
4776 if (!CurContext->isDependentContext()) {
4777 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004778 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004779 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004780 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004781 }
John McCallaa74a0c2009-08-28 07:59:38 +00004782
4783 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004784 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004785 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004786 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004787 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004788
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004789 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004790}
4791
Chris Lattner83f095c2009-03-28 19:18:32 +00004792void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004793 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004794
Chris Lattner83f095c2009-03-28 19:18:32 +00004795 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004796 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4797 if (!Fn) {
4798 Diag(DelLoc, diag::err_deleted_non_function);
4799 return;
4800 }
4801 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4802 Diag(DelLoc, diag::err_deleted_decl_not_first);
4803 Diag(Prev->getLocation(), diag::note_previous_declaration);
4804 // If the declaration wasn't the first, we delete the function anyway for
4805 // recovery.
4806 }
4807 Fn->setDeleted();
4808}
Sebastian Redl4c018662009-04-27 21:33:24 +00004809
4810static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4811 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4812 ++CI) {
4813 Stmt *SubStmt = *CI;
4814 if (!SubStmt)
4815 continue;
4816 if (isa<ReturnStmt>(SubStmt))
4817 Self.Diag(SubStmt->getSourceRange().getBegin(),
4818 diag::err_return_in_constructor_handler);
4819 if (!isa<Expr>(SubStmt))
4820 SearchForReturnInStmt(Self, SubStmt);
4821 }
4822}
4823
4824void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4825 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4826 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4827 SearchForReturnInStmt(*this, Handler);
4828 }
4829}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004830
Mike Stump11289f42009-09-09 15:08:12 +00004831bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004832 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004833 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4834 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004835
4836 QualType CNewTy = Context.getCanonicalType(NewTy);
4837 QualType COldTy = Context.getCanonicalType(OldTy);
4838
Mike Stump11289f42009-09-09 15:08:12 +00004839 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004840 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004842
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004843 // Check if the return types are covariant
4844 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004845
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004846 /// Both types must be pointers or references to classes.
4847 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4848 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4849 NewClassTy = NewPT->getPointeeType();
4850 OldClassTy = OldPT->getPointeeType();
4851 }
4852 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4853 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4854 NewClassTy = NewRT->getPointeeType();
4855 OldClassTy = OldRT->getPointeeType();
4856 }
4857 }
Mike Stump11289f42009-09-09 15:08:12 +00004858
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004859 // The return types aren't either both pointers or references to a class type.
4860 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004861 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004862 diag::err_different_return_type_for_overriding_virtual_function)
4863 << New->getDeclName() << NewTy << OldTy;
4864 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004865
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004866 return true;
4867 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004868
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004869 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004870 // Check if the new class derives from the old class.
4871 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4872 Diag(New->getLocation(),
4873 diag::err_covariant_return_not_derived)
4874 << New->getDeclName() << NewTy << OldTy;
4875 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4876 return true;
4877 }
Mike Stump11289f42009-09-09 15:08:12 +00004878
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004879 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004880 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004881 diag::err_covariant_return_inaccessible_base,
4882 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4883 // FIXME: Should this point to the return type?
4884 New->getLocation(), SourceRange(), New->getDeclName())) {
4885 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4886 return true;
4887 }
4888 }
Mike Stump11289f42009-09-09 15:08:12 +00004889
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004890 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004891 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004892 Diag(New->getLocation(),
4893 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004894 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004895 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4896 return true;
4897 };
Mike Stump11289f42009-09-09 15:08:12 +00004898
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004899
4900 // The new class type must have the same or less qualifiers as the old type.
4901 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4902 Diag(New->getLocation(),
4903 diag::err_covariant_return_type_class_type_more_qualified)
4904 << New->getDeclName() << NewTy << OldTy;
4905 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4906 return true;
4907 };
Mike Stump11289f42009-09-09 15:08:12 +00004908
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004909 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004910}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004911
Alexis Hunt96d5c762009-11-21 08:43:09 +00004912bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4913 const CXXMethodDecl *Old)
4914{
4915 if (Old->hasAttr<FinalAttr>()) {
4916 Diag(New->getLocation(), diag::err_final_function_overridden)
4917 << New->getDeclName();
4918 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4919 return true;
4920 }
4921
4922 return false;
4923}
4924
Douglas Gregor21920e372009-12-01 17:24:26 +00004925/// \brief Mark the given method pure.
4926///
4927/// \param Method the method to be marked pure.
4928///
4929/// \param InitRange the source range that covers the "0" initializer.
4930bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
4931 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
4932 Method->setPure();
4933
4934 // A class is abstract if at least one function is pure virtual.
4935 Method->getParent()->setAbstract(true);
4936 return false;
4937 }
4938
4939 if (!Method->isInvalidDecl())
4940 Diag(Method->getLocation(), diag::err_non_virtual_pure)
4941 << Method->getDeclName() << InitRange;
4942 return true;
4943}
4944
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004945/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4946/// initializer for the declaration 'Dcl'.
4947/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4948/// static data member of class X, names should be looked up in the scope of
4949/// class X.
4950void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004951 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004952
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004953 Decl *D = Dcl.getAs<Decl>();
4954 // If there is no declaration, there was an error parsing it.
4955 if (D == 0)
4956 return;
4957
4958 // Check whether it is a declaration with a nested name specifier like
4959 // int foo::bar;
4960 if (!D->isOutOfLine())
4961 return;
Mike Stump11289f42009-09-09 15:08:12 +00004962
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004963 // C++ [basic.lookup.unqual]p13
4964 //
4965 // A name used in the definition of a static data member of class X
4966 // (after the qualified-id of the static member) is looked up as if the name
4967 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004968
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004969 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004970 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004971}
4972
4973/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4974/// initializer for the declaration 'Dcl'.
4975void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004976 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004977
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004978 Decl *D = Dcl.getAs<Decl>();
4979 // If there is no declaration, there was an error parsing it.
4980 if (D == 0)
4981 return;
4982
4983 // Check whether it is a declaration with a nested name specifier like
4984 // int foo::bar;
4985 if (!D->isOutOfLine())
4986 return;
4987
4988 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004989 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004990}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00004991
4992/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
4993/// C++ if/switch/while/for statement.
4994/// e.g: "if (int x = f()) {...}"
4995Action::DeclResult
4996Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
4997 // C++ 6.4p2:
4998 // The declarator shall not specify a function or an array.
4999 // The type-specifier-seq shall not contain typedef and shall not declare a
5000 // new class or enumeration.
5001 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5002 "Parser allowed 'typedef' as storage class of condition decl.");
5003
5004 DeclaratorInfo *DInfo = 0;
5005 TagDecl *OwnedTag = 0;
5006 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
5007
5008 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5009 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5010 // would be created and CXXConditionDeclExpr wants a VarDecl.
5011 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5012 << D.getSourceRange();
5013 return DeclResult();
5014 } else if (OwnedTag && OwnedTag->isDefinition()) {
5015 // The type-specifier-seq shall not declare a new class or enumeration.
5016 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5017 }
5018
5019 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5020 if (!Dcl)
5021 return DeclResult();
5022
5023 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5024 VD->setDeclaredInCondition(true);
5025 return Dcl;
5026}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005027
5028void Sema::MaybeMarkVirtualImplicitMembersReferenced(SourceLocation Loc,
5029 CXXMethodDecl *MD) {
5030 // Ignore dependent types.
5031 if (MD->isDependentContext())
5032 return;
5033
5034 CXXRecordDecl *RD = MD->getParent();
5035 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5036 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
5037
5038 if (!KeyFunction) {
5039 // This record does not have a key function, so we assume that the vtable
5040 // will be emitted when it's used by the constructor.
5041 if (!isa<CXXConstructorDecl>(MD))
5042 return;
5043 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5044 // We don't have the right key function.
5045 return;
5046 }
5047
5048 if (CXXDestructorDecl *Dtor = RD->getDestructor(Context)) {
5049 if (Dtor->isImplicit() && Dtor->isVirtual())
5050 MarkDeclarationReferenced(Loc, Dtor);
5051 }
5052
5053 // FIXME: Need to handle the virtual assignment operator here too.
5054}