blob: f97b7637451cf7ace4dabb49d9b31d2779d3715b [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"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlssonf98849e2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000030#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000031#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner58258242008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattnerb0d38442008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000049
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 public:
Mike Stump11289f42009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 };
Chris Lattner58258242008-04-10 02:22:51 +000058
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000066 }
67
Chris Lattnerb0d38442008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000093 }
Chris Lattner58258242008-04-10 02:22:51 +000094
Douglas Gregor8e12c382008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000097
Douglas Gregor97a9c812008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107}
108
Anders Carlssonc80a1272009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000112 QualType ParamType = Param->getType();
113
Anders Carlsson114056f2009-08-25 13:46:13 +0000114 if (RequireCompleteType(Param->getLocation(), Param->getType(),
115 diag::err_typecheck_decl_incomplete_type)) {
116 Param->setInvalidDecl();
117 return true;
118 }
119
Anders Carlssonc80a1272009-08-25 02:29:20 +0000120 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000128 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000129 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000130 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000131
132 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000133
Anders Carlssonc80a1272009-08-25 02:29:20 +0000134 // Okay: add the default argument to the parameter
135 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000136
Anders Carlssonc80a1272009-08-25 02:29:20 +0000137 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000139 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000140}
141
Chris Lattner58258242008-04-10 02:22:51 +0000142/// ActOnParamDefaultArgument - Check whether the default argument
143/// provided for a function parameter is well-formed. If so, attach it
144/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000145void
Mike Stump11289f42009-09-09 15:08:12 +0000146Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000147 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000148 if (!param || !defarg.get())
149 return;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Chris Lattner83f095c2009-03-28 19:18:32 +0000151 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000152 UnparsedDefaultArgLocs.erase(Param);
153
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000154 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000155 QualType ParamType = Param->getType();
156
157 // Default arguments are only permitted in C++
158 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000159 Diag(EqualLoc, diag::err_param_default_argument)
160 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000161 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000162 return;
163 }
164
Anders Carlssonf1c26952009-08-25 01:02:06 +0000165 // Check that the default argument is well-formed
166 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
167 if (DefaultArgChecker.Visit(DefaultArg.get())) {
168 Param->setInvalidDecl();
169 return;
170 }
Mike Stump11289f42009-09-09 15:08:12 +0000171
Anders Carlssonc80a1272009-08-25 02:29:20 +0000172 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000173}
174
Douglas Gregor58354032008-12-24 00:01:03 +0000175/// ActOnParamUnparsedDefaultArgument - We've seen a default
176/// argument for a function parameter, but we can't parse it yet
177/// because we're inside a class definition. Note that this default
178/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000179void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000180 SourceLocation EqualLoc,
181 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000182 if (!param)
183 return;
Mike Stump11289f42009-09-09 15:08:12 +0000184
Chris Lattner83f095c2009-03-28 19:18:32 +0000185 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000186 if (Param)
187 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000188
Anders Carlsson84613c42009-06-12 16:51:40 +0000189 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000190}
191
Douglas Gregor4d87df52008-12-16 21:30:33 +0000192/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
193/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000194void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000195 if (!param)
196 return;
Mike Stump11289f42009-09-09 15:08:12 +0000197
Anders Carlsson84613c42009-06-12 16:51:40 +0000198 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000199
Anders Carlsson84613c42009-06-12 16:51:40 +0000200 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson84613c42009-06-12 16:51:40 +0000202 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000203}
204
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000205/// CheckExtraCXXDefaultArguments - Check for any extra default
206/// arguments in the declarator, which is not a function declaration
207/// or definition and therefore is not permitted to have default
208/// arguments. This routine should be invoked for every declarator
209/// that is not a function declaration or definition.
210void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
211 // C++ [dcl.fct.default]p3
212 // A default argument expression shall be specified only in the
213 // parameter-declaration-clause of a function declaration or in a
214 // template-parameter (14.1). It shall not be specified for a
215 // parameter pack. If it is specified in a
216 // parameter-declaration-clause, it shall not occur within a
217 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000218 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000219 DeclaratorChunk &chunk = D.getTypeObject(i);
220 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000221 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
222 ParmVarDecl *Param =
223 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000224 if (Param->hasUnparsedDefaultArg()) {
225 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000226 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
227 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
228 delete Toks;
229 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000230 } else if (Param->getDefaultArg()) {
231 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
232 << Param->getDefaultArg()->getSourceRange();
233 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000234 }
235 }
236 }
237 }
238}
239
Chris Lattner199abbc2008-04-08 05:04:30 +0000240// MergeCXXFunctionDecl - Merge two declarations of the same C++
241// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000242// type. Subroutine of MergeFunctionDecl. Returns true if there was an
243// error, false otherwise.
244bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
245 bool Invalid = false;
246
Chris Lattner199abbc2008-04-08 05:04:30 +0000247 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000248 // For non-template functions, default arguments can be added in
249 // later declarations of a function in the same
250 // scope. Declarations in different scopes have completely
251 // distinct sets of default arguments. That is, declarations in
252 // inner scopes do not acquire default arguments from
253 // declarations in outer scopes, and vice versa. In a given
254 // function declaration, all parameters subsequent to a
255 // parameter with a default argument shall have default
256 // arguments supplied in this or previous declarations. A
257 // default argument shall not be redefined by a later
258 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000259 //
260 // C++ [dcl.fct.default]p6:
261 // Except for member functions of class templates, the default arguments
262 // in a member function definition that appears outside of the class
263 // definition are added to the set of default arguments provided by the
264 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000265 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
266 ParmVarDecl *OldParam = Old->getParamDecl(p);
267 ParmVarDecl *NewParam = New->getParamDecl(p);
268
Douglas Gregorc732aba2009-09-11 18:44:32 +0000269 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000270 // FIXME: If the parameter doesn't have an identifier then the location
271 // points to the '=' which means that the fixit hint won't remove any
272 // extra spaces between the type and the '='.
273 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson1566eb52009-11-10 03:32:44 +0000274 if (NewParam->getIdentifier())
275 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000276
Mike Stump11289f42009-09-09 15:08:12 +0000277 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000278 diag::err_param_default_argument_redefinition)
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000279 << NewParam->getDefaultArgRange()
280 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
281 NewParam->getLocEnd()));
Douglas Gregorc732aba2009-09-11 18:44:32 +0000282
283 // Look for the function declaration where the default argument was
284 // actually written, which may be a declaration prior to Old.
285 for (FunctionDecl *Older = Old->getPreviousDeclaration();
286 Older; Older = Older->getPreviousDeclaration()) {
287 if (!Older->getParamDecl(p)->hasDefaultArg())
288 break;
289
290 OldParam = Older->getParamDecl(p);
291 }
292
293 Diag(OldParam->getLocation(), diag::note_previous_definition)
294 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000295 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000296 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000297 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000298 if (OldParam->hasUninstantiatedDefaultArg())
299 NewParam->setUninstantiatedDefaultArg(
300 OldParam->getUninstantiatedDefaultArg());
301 else
302 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000303 } else if (NewParam->hasDefaultArg()) {
304 if (New->getDescribedFunctionTemplate()) {
305 // Paragraph 4, quoted above, only applies to non-template functions.
306 Diag(NewParam->getLocation(),
307 diag::err_param_default_argument_template_redecl)
308 << NewParam->getDefaultArgRange();
309 Diag(Old->getLocation(), diag::note_template_prev_declaration)
310 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000311 } else if (New->getTemplateSpecializationKind()
312 != TSK_ImplicitInstantiation &&
313 New->getTemplateSpecializationKind() != TSK_Undeclared) {
314 // C++ [temp.expr.spec]p21:
315 // Default function arguments shall not be specified in a declaration
316 // or a definition for one of the following explicit specializations:
317 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000318 // - the explicit specialization of a member function template;
319 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000320 // template where the class template specialization to which the
321 // member function specialization belongs is implicitly
322 // instantiated.
323 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
324 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
325 << New->getDeclName()
326 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000327 } else if (New->getDeclContext()->isDependentContext()) {
328 // C++ [dcl.fct.default]p6 (DR217):
329 // Default arguments for a member function of a class template shall
330 // be specified on the initial declaration of the member function
331 // within the class template.
332 //
333 // Reading the tea leaves a bit in DR217 and its reference to DR205
334 // leads me to the conclusion that one cannot add default function
335 // arguments for an out-of-line definition of a member function of a
336 // dependent type.
337 int WhichKind = 2;
338 if (CXXRecordDecl *Record
339 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
340 if (Record->getDescribedClassTemplate())
341 WhichKind = 0;
342 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
343 WhichKind = 1;
344 else
345 WhichKind = 2;
346 }
347
348 Diag(NewParam->getLocation(),
349 diag::err_param_default_argument_member_template_redecl)
350 << WhichKind
351 << NewParam->getDefaultArgRange();
352 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000353 }
354 }
355
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000356 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000357 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +0000358 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000359 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000360
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000361 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000362}
363
364/// CheckCXXDefaultArguments - Verify that the default arguments for a
365/// function declaration are well-formed according to C++
366/// [dcl.fct.default].
367void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
368 unsigned NumParams = FD->getNumParams();
369 unsigned p;
370
371 // Find first parameter with a default argument
372 for (p = 0; p < NumParams; ++p) {
373 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000374 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000375 break;
376 }
377
378 // C++ [dcl.fct.default]p4:
379 // In a given function declaration, all parameters
380 // subsequent to a parameter with a default argument shall
381 // have default arguments supplied in this or previous
382 // declarations. A default argument shall not be redefined
383 // by a later declaration (not even to the same value).
384 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000385 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000386 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000387 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 if (Param->isInvalidDecl())
389 /* We already complained about this parameter. */;
390 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000391 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000392 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000393 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000394 else
Mike Stump11289f42009-09-09 15:08:12 +0000395 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000396 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000397
Chris Lattner199abbc2008-04-08 05:04:30 +0000398 LastMissingDefaultArg = p;
399 }
400 }
401
402 if (LastMissingDefaultArg > 0) {
403 // Some default arguments were missing. Clear out all of the
404 // default arguments up to (and including) the last missing
405 // default argument, so that we leave the function parameters
406 // in a semantically valid state.
407 for (p = 0; p <= LastMissingDefaultArg; ++p) {
408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000409 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000410 if (!Param->hasUnparsedDefaultArg())
411 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000412 Param->setDefaultArg(0);
413 }
414 }
415 }
416}
Douglas Gregor556877c2008-04-13 21:30:24 +0000417
Douglas Gregor61956c42008-10-31 09:07:45 +0000418/// isCurrentClassName - Determine whether the identifier II is the
419/// name of the class type currently being defined. In the case of
420/// nested classes, this will only return true if II is the name of
421/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000422bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
423 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000424 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000425 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000426 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000427 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
428 } else
429 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
430
431 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000432 return &II == CurDecl->getIdentifier();
433 else
434 return false;
435}
436
Mike Stump11289f42009-09-09 15:08:12 +0000437/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000438///
439/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
440/// and returns NULL otherwise.
441CXXBaseSpecifier *
442Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
443 SourceRange SpecifierRange,
444 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000445 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000446 SourceLocation BaseLoc) {
447 // C++ [class.union]p1:
448 // A union shall not have base classes.
449 if (Class->isUnion()) {
450 Diag(Class->getLocation(), diag::err_base_clause_on_union)
451 << SpecifierRange;
452 return 0;
453 }
454
455 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000456 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000457 Class->getTagKind() == RecordDecl::TK_class,
458 Access, BaseType);
459
460 // Base specifiers must be record types.
461 if (!BaseType->isRecordType()) {
462 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
463 return 0;
464 }
465
466 // C++ [class.union]p1:
467 // A union shall not be used as a base class.
468 if (BaseType->isUnionType()) {
469 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
470 return 0;
471 }
472
473 // C++ [class.derived]p2:
474 // The class-name in a base-specifier shall not be an incompletely
475 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000476 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000477 PDiag(diag::err_incomplete_base_class)
478 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000479 return 0;
480
Eli Friedmanc96d4962009-08-15 21:55:26 +0000481 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000482 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000483 assert(BaseDecl && "Record type has no declaration");
484 BaseDecl = BaseDecl->getDefinition(Context);
485 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000486 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
487 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000488
Alexis Hunt96d5c762009-11-21 08:43:09 +0000489 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
490 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
491 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000492 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
493 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000494 return 0;
495 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000496
Eli Friedman89c038e2009-12-05 23:03:49 +0000497 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000498
499 // Create the base specifier.
500 // FIXME: Allocate via ASTContext?
501 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
502 Class->getTagKind() == RecordDecl::TK_class,
503 Access, BaseType);
504}
505
506void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
507 const CXXRecordDecl *BaseClass,
508 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000509 // A class with a non-empty base class is not empty.
510 // FIXME: Standard ref?
511 if (!BaseClass->isEmpty())
512 Class->setEmpty(false);
513
514 // C++ [class.virtual]p1:
515 // A class that [...] inherits a virtual function is called a polymorphic
516 // class.
517 if (BaseClass->isPolymorphic())
518 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000519
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 // C++ [dcl.init.aggr]p1:
521 // An aggregate is [...] a class with [...] no base classes [...].
522 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
524 // C++ [class]p4:
525 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000526 Class->setPOD(false);
527
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000528 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000529 // C++ [class.ctor]p5:
530 // A constructor is trivial if its class has no virtual base classes.
531 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000532
533 // C++ [class.copy]p6:
534 // A copy constructor is trivial if its class has no virtual base classes.
535 Class->setHasTrivialCopyConstructor(false);
536
537 // C++ [class.copy]p11:
538 // A copy assignment operator is trivial if its class has no virtual
539 // base classes.
540 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000541
542 // C++0x [meta.unary.prop] is_empty:
543 // T is a class type, but not a union type, with ... no virtual base
544 // classes
545 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000546 } else {
547 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000548 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000549 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000550 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000551 Class->setHasTrivialConstructor(false);
552
553 // C++ [class.copy]p6:
554 // A copy constructor is trivial if all the direct base classes of its
555 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000556 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000557 Class->setHasTrivialCopyConstructor(false);
558
559 // C++ [class.copy]p11:
560 // A copy assignment operator is trivial if all the direct base classes
561 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000562 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000563 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000564 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000565
566 // C++ [class.ctor]p3:
567 // A destructor is trivial if all the direct base classes of its class
568 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000569 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000570 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000571}
572
Douglas Gregor556877c2008-04-13 21:30:24 +0000573/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
574/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000575/// example:
576/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000577/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000578Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000579Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000580 bool Virtual, AccessSpecifier Access,
581 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000582 if (!classdecl)
583 return true;
584
Douglas Gregorc40290e2009-03-09 23:48:35 +0000585 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000586 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000587 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000588 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
589 Virtual, Access,
590 BaseType, BaseLoc))
591 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000592
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000594}
Douglas Gregor556877c2008-04-13 21:30:24 +0000595
Douglas Gregor463421d2009-03-03 04:44:36 +0000596/// \brief Performs the actual work of attaching the given base class
597/// specifiers to a C++ class.
598bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
599 unsigned NumBases) {
600 if (NumBases == 0)
601 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000602
603 // Used to keep track of which base types we have already seen, so
604 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000605 // that the key is always the unqualified canonical type of the base
606 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000607 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
608
609 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000611 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000612 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000613 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000614 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000615 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000616
Douglas Gregor29a92472008-10-22 17:49:05 +0000617 if (KnownBaseTypes[NewBaseType]) {
618 // C++ [class.mi]p3:
619 // A class shall not be specified as a direct base class of a
620 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000622 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000623 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000624 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000625
626 // Delete the duplicate base class specifier; we're going to
627 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000628 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000629
630 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000631 } else {
632 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000633 KnownBaseTypes[NewBaseType] = Bases[idx];
634 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000635 }
636 }
637
638 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000639 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000640
641 // Delete the remaining (good) base class specifiers, since their
642 // data has been copied into the CXXRecordDecl.
643 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000644 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000645
646 return Invalid;
647}
648
649/// ActOnBaseSpecifiers - Attach the given base specifiers to the
650/// class, after checking whether there are any duplicate base
651/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000652void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000653 unsigned NumBases) {
654 if (!ClassDecl || !Bases || !NumBases)
655 return;
656
657 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000658 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000659 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000660}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000661
Douglas Gregor36d1b142009-10-06 17:59:45 +0000662/// \brief Determine whether the type \p Derived is a C++ class that is
663/// derived from the type \p Base.
664bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
665 if (!getLangOptions().CPlusPlus)
666 return false;
667
668 const RecordType *DerivedRT = Derived->getAs<RecordType>();
669 if (!DerivedRT)
670 return false;
671
672 const RecordType *BaseRT = Base->getAs<RecordType>();
673 if (!BaseRT)
674 return false;
675
676 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
677 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
678 return DerivedRD->isDerivedFrom(BaseRD);
679}
680
681/// \brief Determine whether the type \p Derived is a C++ class that is
682/// derived from the type \p Base.
683bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
684 if (!getLangOptions().CPlusPlus)
685 return false;
686
687 const RecordType *DerivedRT = Derived->getAs<RecordType>();
688 if (!DerivedRT)
689 return false;
690
691 const RecordType *BaseRT = Base->getAs<RecordType>();
692 if (!BaseRT)
693 return false;
694
695 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
696 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
697 return DerivedRD->isDerivedFrom(BaseRD, Paths);
698}
699
700/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
701/// conversion (where Derived and Base are class types) is
702/// well-formed, meaning that the conversion is unambiguous (and
703/// that all of the base classes are accessible). Returns true
704/// and emits a diagnostic if the code is ill-formed, returns false
705/// otherwise. Loc is the location where this routine should point to
706/// if there is an error, and Range is the source range to highlight
707/// if there is an error.
708bool
709Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
710 unsigned InaccessibleBaseID,
711 unsigned AmbigiousBaseConvID,
712 SourceLocation Loc, SourceRange Range,
713 DeclarationName Name) {
714 // First, determine whether the path from Derived to Base is
715 // ambiguous. This is slightly more expensive than checking whether
716 // the Derived to Base conversion exists, because here we need to
717 // explore multiple paths to determine if there is an ambiguity.
718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
719 /*DetectVirtual=*/false);
720 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
721 assert(DerivationOkay &&
722 "Can only be used with a derived-to-base conversion");
723 (void)DerivationOkay;
724
725 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000726 if (InaccessibleBaseID == 0)
727 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000728 // Check that the base class can be accessed.
729 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
730 Name);
731 }
732
733 // We know that the derived-to-base conversion is ambiguous, and
734 // we're going to produce a diagnostic. Perform the derived-to-base
735 // search just one more time to compute all of the possible paths so
736 // that we can print them out. This is more expensive than any of
737 // the previous derived-to-base checks we've done, but at this point
738 // performance isn't as much of an issue.
739 Paths.clear();
740 Paths.setRecordingPaths(true);
741 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
742 assert(StillOkay && "Can only be used with a derived-to-base conversion");
743 (void)StillOkay;
744
745 // Build up a textual representation of the ambiguous paths, e.g.,
746 // D -> B -> A, that will be used to illustrate the ambiguous
747 // conversions in the diagnostic. We only print one of the paths
748 // to each base class subobject.
749 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
750
751 Diag(Loc, AmbigiousBaseConvID)
752 << Derived << Base << PathDisplayStr << Range << Name;
753 return true;
754}
755
756bool
757Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000758 SourceLocation Loc, SourceRange Range,
759 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000760 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000761 IgnoreAccess ? 0 :
762 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000763 diag::err_ambiguous_derived_to_base_conv,
764 Loc, Range, DeclarationName());
765}
766
767
768/// @brief Builds a string representing ambiguous paths from a
769/// specific derived class to different subobjects of the same base
770/// class.
771///
772/// This function builds a string that can be used in error messages
773/// to show the different paths that one can take through the
774/// inheritance hierarchy to go from the derived class to different
775/// subobjects of a base class. The result looks something like this:
776/// @code
777/// struct D -> struct B -> struct A
778/// struct D -> struct C -> struct A
779/// @endcode
780std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
781 std::string PathDisplayStr;
782 std::set<unsigned> DisplayedPaths;
783 for (CXXBasePaths::paths_iterator Path = Paths.begin();
784 Path != Paths.end(); ++Path) {
785 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
786 // We haven't displayed a path to this particular base
787 // class subobject yet.
788 PathDisplayStr += "\n ";
789 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
790 for (CXXBasePath::const_iterator Element = Path->begin();
791 Element != Path->end(); ++Element)
792 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
793 }
794 }
795
796 return PathDisplayStr;
797}
798
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000799//===----------------------------------------------------------------------===//
800// C++ class member Handling
801//===----------------------------------------------------------------------===//
802
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000803/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
804/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
805/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000806/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000807Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000808Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000809 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000810 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
811 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000812 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000813 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000814 Expr *BitWidth = static_cast<Expr*>(BW);
815 Expr *Init = static_cast<Expr*>(InitExpr);
816 SourceLocation Loc = D.getIdentifierLoc();
817
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000818 bool isFunc = D.isFunctionDeclarator();
819
John McCall07e91c02009-08-06 02:15:43 +0000820 assert(!DS.isFriendSpecified());
821
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000822 // C++ 9.2p6: A member shall not be declared to have automatic storage
823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
825 // data members and cannot be applied to names declared const or static,
826 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000827 switch (DS.getStorageClassSpec()) {
828 case DeclSpec::SCS_unspecified:
829 case DeclSpec::SCS_typedef:
830 case DeclSpec::SCS_static:
831 // FALL THROUGH.
832 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000833 case DeclSpec::SCS_mutable:
834 if (isFunc) {
835 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000836 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000837 else
Chris Lattner3b054132008-11-19 05:08:23 +0000838 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000839
Sebastian Redl8071edb2008-11-17 23:24:37 +0000840 // FIXME: It would be nicer if the keyword was ignored only for this
841 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000842 D.getMutableDeclSpec().ClearStorageClassSpecs();
843 } else {
844 QualType T = GetTypeForDeclarator(D, S);
845 diag::kind err = static_cast<diag::kind>(0);
846 if (T->isReferenceType())
847 err = diag::err_mutable_reference;
848 else if (T.isConstQualified())
849 err = diag::err_mutable_const;
850 if (err != 0) {
851 if (DS.getStorageClassSpecLoc().isValid())
852 Diag(DS.getStorageClassSpecLoc(), err);
853 else
854 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000855 // FIXME: It would be nicer if the keyword was ignored only for this
856 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000857 D.getMutableDeclSpec().ClearStorageClassSpecs();
858 }
859 }
860 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000861 default:
862 if (DS.getStorageClassSpecLoc().isValid())
863 Diag(DS.getStorageClassSpecLoc(),
864 diag::err_storageclass_invalid_for_member);
865 else
866 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
867 D.getMutableDeclSpec().ClearStorageClassSpecs();
868 }
869
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000870 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000871 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000872 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000873 // Check also for this case:
874 //
875 // typedef int f();
876 // f a;
877 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000878 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000879 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000880 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000881
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000882 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
883 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000884 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000885
886 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000887 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000888 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000889 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
890 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000891 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000892 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000893 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000894 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000895 if (!Member) {
896 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000897 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000898 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000899
900 // Non-instance-fields can't have a bitfield.
901 if (BitWidth) {
902 if (Member->isInvalidDecl()) {
903 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000904 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000905 // C++ 9.6p3: A bit-field shall not be a static member.
906 // "static member 'A' cannot be a bit-field"
907 Diag(Loc, diag::err_static_not_bitfield)
908 << Name << BitWidth->getSourceRange();
909 } else if (isa<TypedefDecl>(Member)) {
910 // "typedef member 'x' cannot be a bit-field"
911 Diag(Loc, diag::err_typedef_not_bitfield)
912 << Name << BitWidth->getSourceRange();
913 } else {
914 // A function typedef ("typedef int f(); f a;").
915 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
916 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000917 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000918 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000919 }
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattnerd26760a2009-03-05 23:01:03 +0000921 DeleteExpr(BitWidth);
922 BitWidth = 0;
923 Member->setInvalidDecl();
924 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000925
926 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000927
Douglas Gregor3447e762009-08-20 22:52:58 +0000928 // If we have declared a member function template, set the access of the
929 // templated declaration as well.
930 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
931 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000932 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000933
Douglas Gregor92751d42008-11-17 22:58:34 +0000934 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935
Douglas Gregor0c880302009-03-11 23:00:04 +0000936 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000937 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000938 if (Deleted) // FIXME: Source location is not very good.
939 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000940
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000941 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000942 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000943 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000944 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000945 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000946}
947
Douglas Gregore8381c02008-11-05 04:29:56 +0000948/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000949Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000950Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000951 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000952 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000953 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000954 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000955 SourceLocation IdLoc,
956 SourceLocation LParenLoc,
957 ExprTy **Args, unsigned NumArgs,
958 SourceLocation *CommaLocs,
959 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000960 if (!ConstructorD)
961 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000962
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000963 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000964
965 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000966 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000967 if (!Constructor) {
968 // The user wrote a constructor initializer on a function that is
969 // not a C++ constructor. Ignore the error for now, because we may
970 // have more member initializers coming; we'll diagnose it just
971 // once in ActOnMemInitializers.
972 return true;
973 }
974
975 CXXRecordDecl *ClassDecl = Constructor->getParent();
976
977 // C++ [class.base.init]p2:
978 // Names in a mem-initializer-id are looked up in the scope of the
979 // constructor’s class and, if not found in that scope, are looked
980 // up in the scope containing the constructor’s
981 // definition. [Note: if the constructor’s class contains a member
982 // with the same name as a direct or virtual base class of the
983 // class, a mem-initializer-id naming the member or base class and
984 // composed of a single identifier refers to the class member. A
985 // mem-initializer-id for the hidden base class may be specified
986 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000987 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000988 // Look for a member, first.
989 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000990 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000991 = ClassDecl->lookup(MemberOrBase);
992 if (Result.first != Result.second)
993 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000994
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000995 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000996
Eli Friedman8e1433b2009-07-29 19:44:27 +0000997 if (Member)
998 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000999 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001000 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001001 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001002 QualType BaseType;
1003
John McCallbcd03502009-12-07 02:54:59 +00001004 TypeSourceInfo *TInfo = 0;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001005 if (TemplateTypeTy)
John McCallbcd03502009-12-07 02:54:59 +00001006 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001007 else
1008 BaseType = QualType::getFromOpaquePtr(getTypeName(*MemberOrBase, IdLoc,
1009 S, &SS));
1010 if (BaseType.isNull())
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001011 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1012 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001013
John McCallbcd03502009-12-07 02:54:59 +00001014 if (!TInfo)
1015 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001016
John McCallbcd03502009-12-07 02:54:59 +00001017 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001018 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001019}
1020
John McCalle22a04a2009-11-04 23:02:40 +00001021/// Checks an initializer expression for use of uninitialized fields, such as
1022/// containing the field that is being initialized. Returns true if there is an
1023/// uninitialized field was used an updates the SourceLocation parameter; false
1024/// otherwise.
1025static bool InitExprContainsUninitializedFields(const Stmt* S,
1026 const FieldDecl* LhsField,
1027 SourceLocation* L) {
1028 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1029 if (ME) {
1030 const NamedDecl* RhsField = ME->getMemberDecl();
1031 if (RhsField == LhsField) {
1032 // Initializing a field with itself. Throw a warning.
1033 // But wait; there are exceptions!
1034 // Exception #1: The field may not belong to this record.
1035 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1036 const Expr* base = ME->getBase();
1037 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1038 // Even though the field matches, it does not belong to this record.
1039 return false;
1040 }
1041 // None of the exceptions triggered; return true to indicate an
1042 // uninitialized field was used.
1043 *L = ME->getMemberLoc();
1044 return true;
1045 }
1046 }
1047 bool found = false;
1048 for (Stmt::const_child_iterator it = S->child_begin();
1049 it != S->child_end() && found == false;
1050 ++it) {
1051 if (isa<CallExpr>(S)) {
1052 // Do not descend into function calls or constructors, as the use
1053 // of an uninitialized field may be valid. One would have to inspect
1054 // the contents of the function/ctor to determine if it is safe or not.
1055 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1056 // may be safe, depending on what the function/ctor does.
1057 continue;
1058 }
1059 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1060 }
1061 return found;
1062}
1063
Eli Friedman8e1433b2009-07-29 19:44:27 +00001064Sema::MemInitResult
1065Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1066 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001067 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001068 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001069 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1070 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1071 ExprTemporaries.clear();
1072
John McCalle22a04a2009-11-04 23:02:40 +00001073 // Diagnose value-uses of fields to initialize themselves, e.g.
1074 // foo(foo)
1075 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001076 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001077 for (unsigned i = 0; i < NumArgs; ++i) {
1078 SourceLocation L;
1079 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1080 // FIXME: Return true in the case when other fields are used before being
1081 // uninitialized. For example, let this field be the i'th field. When
1082 // initializing the i'th field, throw a warning if any of the >= i'th
1083 // fields are used, as they are not yet initialized.
1084 // Right now we are only handling the case where the i'th field uses
1085 // itself in its initializer.
1086 Diag(L, diag::warn_field_is_uninit);
1087 }
1088 }
1089
Eli Friedman8e1433b2009-07-29 19:44:27 +00001090 bool HasDependentArg = false;
1091 for (unsigned i = 0; i < NumArgs; i++)
1092 HasDependentArg |= Args[i]->isTypeDependent();
1093
1094 CXXConstructorDecl *C = 0;
1095 QualType FieldType = Member->getType();
1096 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1097 FieldType = Array->getElementType();
1098 if (FieldType->isDependentType()) {
1099 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001100 } else if (FieldType->isRecordType()) {
1101 // Member is a record (struct/union/class), so pass the initializer
1102 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001103 if (!HasDependentArg) {
1104 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1105
1106 C = PerformInitializationByConstructor(FieldType,
1107 MultiExprArg(*this,
1108 (void**)Args,
1109 NumArgs),
1110 IdLoc,
1111 SourceRange(IdLoc, RParenLoc),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001112 Member->getDeclName(),
1113 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001114 ConstructorArgs);
1115
1116 if (C) {
1117 // Take over the constructor arguments as our own.
1118 NumArgs = ConstructorArgs.size();
1119 Args = (Expr **)ConstructorArgs.take();
1120 }
1121 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001122 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001123 // The member type is not a record type (or an array of record
1124 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001125 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001126 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1127 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001128 Expr *NewExp;
1129 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001130 if (FieldType->isReferenceType()) {
1131 Diag(IdLoc, diag::err_null_intialized_reference_member)
1132 << Member->getDeclName();
1133 return Diag(Member->getLocation(), diag::note_declared_at);
1134 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001135 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1136 NumArgs = 1;
1137 }
1138 else
1139 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001140 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1141 return true;
1142 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001143 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001144
1145 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1146 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1147 ExprTemporaries.clear();
1148
Eli Friedman8e1433b2009-07-29 19:44:27 +00001149 // FIXME: Perform direct initialization of the member.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001150 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1151 C, LParenLoc, (Expr **)Args,
1152 NumArgs, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001153}
1154
1155Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001156Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001157 Expr **Args, unsigned NumArgs,
1158 SourceLocation LParenLoc, SourceLocation RParenLoc,
1159 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001160 bool HasDependentArg = false;
1161 for (unsigned i = 0; i < NumArgs; i++)
1162 HasDependentArg |= Args[i]->isTypeDependent();
1163
John McCallbcd03502009-12-07 02:54:59 +00001164 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001165 if (!BaseType->isDependentType()) {
1166 if (!BaseType->isRecordType())
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001167 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCallbcd03502009-12-07 02:54:59 +00001168 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001169
1170 // C++ [class.base.init]p2:
1171 // [...] Unless the mem-initializer-id names a nonstatic data
1172 // member of the constructor’s class or a direct or virtual base
1173 // of that class, the mem-initializer is ill-formed. A
1174 // mem-initializer-list can initialize a base class using any
1175 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001176
Eli Friedman8e1433b2009-07-29 19:44:27 +00001177 // First, check for a direct base class.
1178 const CXXBaseSpecifier *DirectBaseSpec = 0;
1179 for (CXXRecordDecl::base_class_const_iterator Base =
1180 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001181 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001182 // We found a direct base of this type. That's what we're
1183 // initializing.
1184 DirectBaseSpec = &*Base;
1185 break;
1186 }
1187 }
Mike Stump11289f42009-09-09 15:08:12 +00001188
Eli Friedman8e1433b2009-07-29 19:44:27 +00001189 // Check for a virtual base class.
1190 // FIXME: We might be able to short-circuit this if we know in advance that
1191 // there are no virtual bases.
1192 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1193 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1194 // We haven't found a base yet; search the class hierarchy for a
1195 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001196 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1197 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001198 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001199 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001200 Path != Paths.end(); ++Path) {
1201 if (Path->back().Base->isVirtual()) {
1202 VirtualBaseSpec = Path->back().Base;
1203 break;
1204 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001205 }
1206 }
1207 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001208
1209 // C++ [base.class.init]p2:
1210 // If a mem-initializer-id is ambiguous because it designates both
1211 // a direct non-virtual base class and an inherited virtual base
1212 // class, the mem-initializer is ill-formed.
1213 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001214 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCallbcd03502009-12-07 02:54:59 +00001215 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001216 // C++ [base.class.init]p2:
1217 // Unless the mem-initializer-id names a nonstatic data membeer of the
1218 // constructor's class ot a direst or virtual base of that class, the
1219 // mem-initializer is ill-formed.
1220 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001221 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1222 << BaseType << ClassDecl->getNameAsCString()
John McCallbcd03502009-12-07 02:54:59 +00001223 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregore8381c02008-11-05 04:29:56 +00001224 }
1225
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001226 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001227 if (!BaseType->isDependentType() && !HasDependentArg) {
1228 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001229 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001230 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1231
1232 C = PerformInitializationByConstructor(BaseType,
1233 MultiExprArg(*this,
1234 (void**)Args, NumArgs),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001235 BaseLoc,
1236 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001237 Name,
1238 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001239 ConstructorArgs);
1240 if (C) {
1241 // Take over the constructor arguments as our own.
1242 NumArgs = ConstructorArgs.size();
1243 Args = (Expr **)ConstructorArgs.take();
1244 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001245 }
1246
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001247 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1248 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1249 ExprTemporaries.clear();
1250
John McCallbcd03502009-12-07 02:54:59 +00001251 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001252 LParenLoc, (Expr **)Args,
1253 NumArgs, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001254}
1255
Eli Friedman9cf6b592009-11-09 19:20:36 +00001256bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001257Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001258 CXXBaseOrMemberInitializer **Initializers,
1259 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001260 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001261 // We need to build the initializer AST according to order of construction
1262 // and not what user specified in the Initializers list.
1263 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1264 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1265 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1266 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001267 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001268
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001269 for (unsigned i = 0; i < NumInitializers; i++) {
1270 CXXBaseOrMemberInitializer *Member = Initializers[i];
1271 if (Member->isBaseInitializer()) {
1272 if (Member->getBaseClass()->isDependentType())
1273 HasDependentBaseInit = true;
1274 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1275 } else {
1276 AllBaseFields[Member->getMember()] = Member;
1277 }
1278 }
Mike Stump11289f42009-09-09 15:08:12 +00001279
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001280 if (HasDependentBaseInit) {
1281 // FIXME. This does not preserve the ordering of the initializers.
1282 // Try (with -Wreorder)
1283 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001284 // template<class X> struct B : A<X> {
1285 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001286 // int x1;
1287 // };
1288 // B<int> x;
1289 // On seeing one dependent type, we should essentially exit this routine
1290 // while preserving user-declared initializer list. When this routine is
1291 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001292 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001293
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001294 // If we have a dependent base initialization, we can't determine the
1295 // association between initializers and bases; just dump the known
1296 // initializers into the list, and don't try to deal with other bases.
1297 for (unsigned i = 0; i < NumInitializers; i++) {
1298 CXXBaseOrMemberInitializer *Member = Initializers[i];
1299 if (Member->isBaseInitializer())
1300 AllToInit.push_back(Member);
1301 }
1302 } else {
1303 // Push virtual bases before others.
1304 for (CXXRecordDecl::base_class_iterator VBase =
1305 ClassDecl->vbases_begin(),
1306 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1307 if (VBase->getType()->isDependentType())
1308 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001309 if (CXXBaseOrMemberInitializer *Value
1310 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001311 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001312 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001313 else {
Mike Stump11289f42009-09-09 15:08:12 +00001314 CXXRecordDecl *VBaseDecl =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001315 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001316 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001317 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001318 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001319 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1320 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1321 << 0 << VBase->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001322 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001323 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001324 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001325 continue;
1326 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001327
Anders Carlsson561f7932009-10-29 15:46:07 +00001328 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1329 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1330 Constructor->getLocation(), CtorArgs))
1331 continue;
1332
1333 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1334
Anders Carlssonbdd12402009-11-13 20:11:49 +00001335 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001336 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1337 // necessary.
1338 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001339 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001340 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001341 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001342 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001343 SourceLocation()),
1344 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001345 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001346 CtorArgs.takeAs<Expr>(),
1347 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001348 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001349 AllToInit.push_back(Member);
1350 }
1351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001353 for (CXXRecordDecl::base_class_iterator Base =
1354 ClassDecl->bases_begin(),
1355 E = ClassDecl->bases_end(); Base != E; ++Base) {
1356 // Virtuals are in the virtual base list and already constructed.
1357 if (Base->isVirtual())
1358 continue;
1359 // Skip dependent types.
1360 if (Base->getType()->isDependentType())
1361 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001362 if (CXXBaseOrMemberInitializer *Value
1363 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001364 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001365 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001366 else {
Mike Stump11289f42009-09-09 15:08:12 +00001367 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001368 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001369 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001370 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001371 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001372 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1373 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1374 << 0 << Base->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001375 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001376 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001377 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001378 continue;
1379 }
1380
1381 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1382 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1383 Constructor->getLocation(), CtorArgs))
1384 continue;
1385
1386 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001387
Anders Carlssonbdd12402009-11-13 20:11:49 +00001388 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001389 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1390 // necessary.
1391 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001392 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001393 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001394 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001395 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001396 SourceLocation()),
1397 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001398 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001399 CtorArgs.takeAs<Expr>(),
1400 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001401 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001402 AllToInit.push_back(Member);
1403 }
1404 }
1405 }
Mike Stump11289f42009-09-09 15:08:12 +00001406
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001407 // non-static data members.
1408 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1409 E = ClassDecl->field_end(); Field != E; ++Field) {
1410 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001411 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001412 Field->getType()->getAs<RecordType>()) {
1413 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001414 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001415 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001416 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1417 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1418 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1419 // set to the anonymous union data member used in the initializer
1420 // list.
1421 Value->setMember(*Field);
1422 Value->setAnonUnionMember(*FA);
1423 AllToInit.push_back(Value);
1424 break;
1425 }
1426 }
1427 }
1428 continue;
1429 }
1430 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1431 AllToInit.push_back(Value);
1432 continue;
1433 }
Mike Stump11289f42009-09-09 15:08:12 +00001434
Eli Friedmand7686ef2009-11-09 01:05:47 +00001435 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001436 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001437
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001438 QualType FT = Context.getBaseElementType((*Field)->getType());
1439 if (const RecordType* RT = FT->getAs<RecordType>()) {
1440 CXXConstructorDecl *Ctor =
1441 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001442 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001443 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1444 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1445 << 1 << (*Field)->getDeclName();
1446 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregore7488b92009-12-01 16:58:18 +00001447 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001448 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001449 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001450 continue;
1451 }
Eli Friedman22683fe2009-11-16 23:07:59 +00001452
1453 if (FT.isConstQualified() && Ctor->isTrivial()) {
1454 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1455 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1456 << 1 << (*Field)->getDeclName();
1457 Diag((*Field)->getLocation(), diag::note_declared_at);
1458 HadError = true;
1459 }
1460
1461 // Don't create initializers for trivial constructors, since they don't
1462 // actually need to be run.
1463 if (Ctor->isTrivial())
1464 continue;
1465
Anders Carlsson561f7932009-10-29 15:46:07 +00001466 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1467 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1468 Constructor->getLocation(), CtorArgs))
1469 continue;
1470
Anders Carlssonbdd12402009-11-13 20:11:49 +00001471 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1472 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1473 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001474 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001475 new (Context) CXXBaseOrMemberInitializer(Context,
1476 *Field, SourceLocation(),
1477 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001478 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001479 CtorArgs.takeAs<Expr>(),
1480 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001481 SourceLocation());
1482
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001483 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001484 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001485 }
1486 else if (FT->isReferenceType()) {
1487 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001488 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1489 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001490 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001491 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001492 }
1493 else if (FT.isConstQualified()) {
1494 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001495 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1496 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001497 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001498 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001499 }
1500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001502 NumInitializers = AllToInit.size();
1503 if (NumInitializers > 0) {
1504 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1505 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1506 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001507
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001508 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1509 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1510 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1511 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001512
1513 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001514}
1515
Eli Friedman952c15d2009-07-21 19:28:10 +00001516static void *GetKeyForTopLevelField(FieldDecl *Field) {
1517 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001518 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001519 if (RT->getDecl()->isAnonymousStructOrUnion())
1520 return static_cast<void *>(RT->getDecl());
1521 }
1522 return static_cast<void *>(Field);
1523}
1524
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001525static void *GetKeyForBase(QualType BaseType) {
1526 if (const RecordType *RT = BaseType->getAs<RecordType>())
1527 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001528
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001529 assert(0 && "Unexpected base type!");
1530 return 0;
1531}
1532
Mike Stump11289f42009-09-09 15:08:12 +00001533static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001534 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001535 // For fields injected into the class via declaration of an anonymous union,
1536 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001537 if (Member->isMemberInitializer()) {
1538 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001539
Eli Friedmand7686ef2009-11-09 01:05:47 +00001540 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001541 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001542 // in AnonUnionMember field.
1543 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1544 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001545 if (Field->getDeclContext()->isRecord()) {
1546 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1547 if (RD->isAnonymousStructOrUnion())
1548 return static_cast<void *>(RD);
1549 }
1550 return static_cast<void *>(Field);
1551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001553 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001554}
1555
John McCallc90f6d72009-11-04 23:13:52 +00001556/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001557void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001558 SourceLocation ColonLoc,
1559 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001560 if (!ConstructorDecl)
1561 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001562
1563 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001564
1565 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001566 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001567
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001568 if (!Constructor) {
1569 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1570 return;
1571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001573 if (!Constructor->isDependentContext()) {
1574 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1575 bool err = false;
1576 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001577 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001578 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1579 void *KeyToMember = GetKeyForMember(Member);
1580 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1581 if (!PrevMember) {
1582 PrevMember = Member;
1583 continue;
1584 }
1585 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001586 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001587 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001588 << Field->getNameAsString()
1589 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001590 else {
1591 Type *BaseClass = Member->getBaseClass();
1592 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001593 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001594 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001595 << QualType(BaseClass, 0)
1596 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001597 }
1598 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1599 << 0;
1600 err = true;
1601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001603 if (err)
1604 return;
1605 }
Mike Stump11289f42009-09-09 15:08:12 +00001606
Eli Friedmand7686ef2009-11-09 01:05:47 +00001607 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001608 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001609 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001610
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001611 if (Constructor->isDependentContext())
1612 return;
Mike Stump11289f42009-09-09 15:08:12 +00001613
1614 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001615 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001616 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001617 Diagnostic::Ignored)
1618 return;
Mike Stump11289f42009-09-09 15:08:12 +00001619
Anders Carlssone0eebb32009-08-27 05:45:01 +00001620 // Also issue warning if order of ctor-initializer list does not match order
1621 // of 1) base class declarations and 2) order of non-static data members.
1622 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Anders Carlssone0eebb32009-08-27 05:45:01 +00001624 CXXRecordDecl *ClassDecl
1625 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1626 // Push virtual bases before others.
1627 for (CXXRecordDecl::base_class_iterator VBase =
1628 ClassDecl->vbases_begin(),
1629 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001630 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001631
Anders Carlssone0eebb32009-08-27 05:45:01 +00001632 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1633 E = ClassDecl->bases_end(); Base != E; ++Base) {
1634 // Virtuals are alread in the virtual base list and are constructed
1635 // first.
1636 if (Base->isVirtual())
1637 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001638 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001639 }
Mike Stump11289f42009-09-09 15:08:12 +00001640
Anders Carlssone0eebb32009-08-27 05:45:01 +00001641 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1642 E = ClassDecl->field_end(); Field != E; ++Field)
1643 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001644
Anders Carlssone0eebb32009-08-27 05:45:01 +00001645 int Last = AllBaseOrMembers.size();
1646 int curIndex = 0;
1647 CXXBaseOrMemberInitializer *PrevMember = 0;
1648 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001649 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001650 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1651 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001652
Anders Carlssone0eebb32009-08-27 05:45:01 +00001653 for (; curIndex < Last; curIndex++)
1654 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1655 break;
1656 if (curIndex == Last) {
1657 assert(PrevMember && "Member not in member list?!");
1658 // Initializer as specified in ctor-initializer list is out of order.
1659 // Issue a warning diagnostic.
1660 if (PrevMember->isBaseInitializer()) {
1661 // Diagnostics is for an initialized base class.
1662 Type *BaseClass = PrevMember->getBaseClass();
1663 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001664 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001665 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001666 } else {
1667 FieldDecl *Field = PrevMember->getMember();
1668 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001669 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001670 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001671 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001672 // Also the note!
1673 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001674 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001675 diag::note_fieldorbase_initialized_here) << 0
1676 << Field->getNameAsString();
1677 else {
1678 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001679 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001680 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001681 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001682 }
1683 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001684 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001685 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001686 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001687 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001688 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001689}
1690
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001691void
Anders Carlssondee9a302009-11-17 04:44:12 +00001692Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1693 // Ignore dependent destructors.
1694 if (Destructor->isDependentContext())
1695 return;
1696
1697 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001698
Anders Carlssondee9a302009-11-17 04:44:12 +00001699 // Non-static data members.
1700 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1701 E = ClassDecl->field_end(); I != E; ++I) {
1702 FieldDecl *Field = *I;
1703
1704 QualType FieldType = Context.getBaseElementType(Field->getType());
1705
1706 const RecordType* RT = FieldType->getAs<RecordType>();
1707 if (!RT)
1708 continue;
1709
1710 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1711 if (FieldClassDecl->hasTrivialDestructor())
1712 continue;
1713
1714 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1715 MarkDeclarationReferenced(Destructor->getLocation(),
1716 const_cast<CXXDestructorDecl*>(Dtor));
1717 }
1718
1719 // Bases.
1720 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1721 E = ClassDecl->bases_end(); Base != E; ++Base) {
1722 // Ignore virtual bases.
1723 if (Base->isVirtual())
1724 continue;
1725
1726 // Ignore trivial destructors.
1727 CXXRecordDecl *BaseClassDecl
1728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1729 if (BaseClassDecl->hasTrivialDestructor())
1730 continue;
1731
1732 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1733 MarkDeclarationReferenced(Destructor->getLocation(),
1734 const_cast<CXXDestructorDecl*>(Dtor));
1735 }
1736
1737 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001738 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1739 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001740 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001741 CXXRecordDecl *BaseClassDecl
1742 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1743 if (BaseClassDecl->hasTrivialDestructor())
1744 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001745
1746 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1747 MarkDeclarationReferenced(Destructor->getLocation(),
1748 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001749 }
1750}
1751
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001752void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001753 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001754 return;
Mike Stump11289f42009-09-09 15:08:12 +00001755
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001756 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001757
1758 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001759 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001760 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001761}
1762
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001763namespace {
1764 /// PureVirtualMethodCollector - traverses a class and its superclasses
1765 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001766 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001767 ASTContext &Context;
1768
Sebastian Redlb7d64912009-03-22 21:28:55 +00001769 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001770 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001771
1772 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001773 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001774
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001775 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001776
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001777 public:
Mike Stump11289f42009-09-09 15:08:12 +00001778 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001779 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001780
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001781 MethodList List;
1782 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001783
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001784 // Copy the temporary list to methods, and make sure to ignore any
1785 // null entries.
1786 for (size_t i = 0, e = List.size(); i != e; ++i) {
1787 if (List[i])
1788 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001789 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001790 }
Mike Stump11289f42009-09-09 15:08:12 +00001791
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001792 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001793
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001794 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1795 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001796 };
Mike Stump11289f42009-09-09 15:08:12 +00001797
1798 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001799 MethodList& Methods) {
1800 // First, collect the pure virtual methods for the base classes.
1801 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1802 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001803 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001804 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001805 if (BaseDecl && BaseDecl->isAbstract())
1806 Collect(BaseDecl, Methods);
1807 }
1808 }
Mike Stump11289f42009-09-09 15:08:12 +00001809
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001810 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001811 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Anders Carlsson3c012712009-05-17 00:00:05 +00001813 MethodSetTy OverriddenMethods;
1814 size_t MethodsSize = Methods.size();
1815
Mike Stump11289f42009-09-09 15:08:12 +00001816 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001817 i != e; ++i) {
1818 // Traverse the record, looking for methods.
1819 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001820 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001821 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001822 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001823
Anders Carlsson700179432009-10-18 19:34:08 +00001824 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001825 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1826 E = MD->end_overridden_methods(); I != E; ++I) {
1827 // Keep track of the overridden methods.
1828 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001829 }
1830 }
1831 }
Mike Stump11289f42009-09-09 15:08:12 +00001832
1833 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001834 // overridden.
1835 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1836 if (OverriddenMethods.count(Methods[i]))
1837 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001840 }
1841}
Douglas Gregore8381c02008-11-05 04:29:56 +00001842
Anders Carlssoneabf7702009-08-27 00:13:57 +00001843
Mike Stump11289f42009-09-09 15:08:12 +00001844bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001845 unsigned DiagID, AbstractDiagSelID SelID,
1846 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001847 if (SelID == -1)
1848 return RequireNonAbstractType(Loc, T,
1849 PDiag(DiagID), CurrentRD);
1850 else
1851 return RequireNonAbstractType(Loc, T,
1852 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001853}
1854
Anders Carlssoneabf7702009-08-27 00:13:57 +00001855bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1856 const PartialDiagnostic &PD,
1857 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001858 if (!getLangOptions().CPlusPlus)
1859 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001860
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001861 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001862 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001863 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001864
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001865 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001866 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001868 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001869
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001870 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001871 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001874 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001875 if (!RT)
1876 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001877
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001878 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1879 if (!RD)
1880 return false;
1881
Anders Carlssonb57738b2009-03-24 17:23:42 +00001882 if (CurrentRD && CurrentRD != RD)
1883 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001884
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001885 if (!RD->isAbstract())
1886 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001887
Anders Carlssoneabf7702009-08-27 00:13:57 +00001888 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001889
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001890 // Check if we've already emitted the list of pure virtual functions for this
1891 // class.
1892 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1893 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001894
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001895 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001896
1897 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001898 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1899 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001900
1901 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001902 MD->getDeclName();
1903 }
1904
1905 if (!PureVirtualClassDiagSet)
1906 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1907 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001908
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001909 return true;
1910}
1911
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001912namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001913 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001914 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1915 Sema &SemaRef;
1916 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001917
Anders Carlssonb57738b2009-03-24 17:23:42 +00001918 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001919 bool Invalid = false;
1920
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001921 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1922 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001923 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001924
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001925 return Invalid;
1926 }
Mike Stump11289f42009-09-09 15:08:12 +00001927
Anders Carlssonb57738b2009-03-24 17:23:42 +00001928 public:
1929 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1930 : SemaRef(SemaRef), AbstractClass(ac) {
1931 Visit(SemaRef.Context.getTranslationUnitDecl());
1932 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001933
Anders Carlssonb57738b2009-03-24 17:23:42 +00001934 bool VisitFunctionDecl(const FunctionDecl *FD) {
1935 if (FD->isThisDeclarationADefinition()) {
1936 // No need to do the check if we're in a definition, because it requires
1937 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001938 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001939 return VisitDeclContext(FD);
1940 }
Mike Stump11289f42009-09-09 15:08:12 +00001941
Anders Carlssonb57738b2009-03-24 17:23:42 +00001942 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001943 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001944 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001945 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1946 diag::err_abstract_type_in_decl,
1947 Sema::AbstractReturnType,
1948 AbstractClass);
1949
Mike Stump11289f42009-09-09 15:08:12 +00001950 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001951 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001952 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001953 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001954 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001955 VD->getOriginalType(),
1956 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001957 Sema::AbstractParamType,
1958 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001959 }
1960
1961 return Invalid;
1962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Anders Carlssonb57738b2009-03-24 17:23:42 +00001964 bool VisitDecl(const Decl* D) {
1965 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1966 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Anders Carlssonb57738b2009-03-24 17:23:42 +00001968 return false;
1969 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001970 };
1971}
1972
Douglas Gregorc99f1552009-12-03 18:33:45 +00001973/// \brief Perform semantic checks on a class definition that has been
1974/// completing, introducing implicitly-declared members, checking for
1975/// abstract types, etc.
1976void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1977 if (!Record || Record->isInvalidDecl())
1978 return;
1979
1980 if (!Record->isAbstract()) {
1981 // Collect all the pure virtual methods and see if this is an abstract
1982 // class after all.
1983 PureVirtualMethodCollector Collector(Context, Record);
1984 if (!Collector.empty())
1985 Record->setAbstract(true);
1986 }
1987
1988 if (Record->isAbstract())
1989 (void)AbstractClassUsageDiagnoser(*this, Record);
1990
1991 if (!Record->isDependentType() && !Record->isInvalidDecl())
1992 AddImplicitlyDeclaredMembersToClass(Record);
1993}
1994
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001995void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001996 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001997 SourceLocation LBrac,
1998 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001999 if (!TagDecl)
2000 return;
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002002 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002003
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002004 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002005 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00002006 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00002007
Douglas Gregorc99f1552009-12-03 18:33:45 +00002008 CheckCompletedCXXClass(
2009 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002010}
2011
Douglas Gregor05379422008-11-03 17:51:48 +00002012/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2013/// special functions, such as the default constructor, copy
2014/// constructor, or destructor, to the given C++ class (C++
2015/// [special]p1). This routine can only be executed just before the
2016/// definition of the class is complete.
2017void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002018 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002019 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002020
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002021 // FIXME: Implicit declarations have exception specifications, which are
2022 // the union of the specifications of the implicitly called functions.
2023
Douglas Gregor05379422008-11-03 17:51:48 +00002024 if (!ClassDecl->hasUserDeclaredConstructor()) {
2025 // C++ [class.ctor]p5:
2026 // A default constructor for a class X is a constructor of class X
2027 // that can be called without an argument. If there is no
2028 // user-declared constructor for class X, a default constructor is
2029 // implicitly declared. An implicitly-declared default constructor
2030 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002031 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002032 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002033 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002034 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002035 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002036 Context.getFunctionType(Context.VoidTy,
2037 0, 0, false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002038 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002039 /*isExplicit=*/false,
2040 /*isInline=*/true,
2041 /*isImplicitlyDeclared=*/true);
2042 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002043 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002044 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002045 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002046 }
2047
2048 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2049 // C++ [class.copy]p4:
2050 // If the class definition does not explicitly declare a copy
2051 // constructor, one is declared implicitly.
2052
2053 // C++ [class.copy]p5:
2054 // The implicitly-declared copy constructor for a class X will
2055 // have the form
2056 //
2057 // X::X(const X&)
2058 //
2059 // if
2060 bool HasConstCopyConstructor = true;
2061
2062 // -- each direct or virtual base class B of X has a copy
2063 // constructor whose first parameter is of type const B& or
2064 // const volatile B&, and
2065 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2066 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2067 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002068 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002069 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002070 = BaseClassDecl->hasConstCopyConstructor(Context);
2071 }
2072
2073 // -- for all the nonstatic data members of X that are of a
2074 // class type M (or array thereof), each such class type
2075 // has a copy constructor whose first parameter is of type
2076 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002077 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2078 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002079 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002080 QualType FieldType = (*Field)->getType();
2081 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2082 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002083 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002084 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002085 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002086 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002087 = FieldClassDecl->hasConstCopyConstructor(Context);
2088 }
2089 }
2090
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002091 // Otherwise, the implicitly declared copy constructor will have
2092 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002093 //
2094 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002095 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002096 if (HasConstCopyConstructor)
2097 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002098 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002099
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002100 // An implicitly-declared copy constructor is an inline public
2101 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002102 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002103 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002104 CXXConstructorDecl *CopyConstructor
2105 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002106 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002107 Context.getFunctionType(Context.VoidTy,
2108 &ArgType, 1,
2109 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002110 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002111 /*isExplicit=*/false,
2112 /*isInline=*/true,
2113 /*isImplicitlyDeclared=*/true);
2114 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002115 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002116 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002117
2118 // Add the parameter to the constructor.
2119 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2120 ClassDecl->getLocation(),
2121 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002122 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002123 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002124 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002125 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002126 }
2127
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002128 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2129 // Note: The following rules are largely analoguous to the copy
2130 // constructor rules. Note that virtual bases are not taken into account
2131 // for determining the argument type of the operator. Note also that
2132 // operators taking an object instead of a reference are allowed.
2133 //
2134 // C++ [class.copy]p10:
2135 // If the class definition does not explicitly declare a copy
2136 // assignment operator, one is declared implicitly.
2137 // The implicitly-defined copy assignment operator for a class X
2138 // will have the form
2139 //
2140 // X& X::operator=(const X&)
2141 //
2142 // if
2143 bool HasConstCopyAssignment = true;
2144
2145 // -- each direct base class B of X has a copy assignment operator
2146 // whose parameter is of type const B&, const volatile B& or B,
2147 // and
2148 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2149 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002150 assert(!Base->getType()->isDependentType() &&
2151 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002152 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002153 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002154 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002155 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002156 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002157 }
2158
2159 // -- for all the nonstatic data members of X that are of a class
2160 // type M (or array thereof), each such class type has a copy
2161 // assignment operator whose parameter is of type const M&,
2162 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002163 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2164 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002165 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002166 QualType FieldType = (*Field)->getType();
2167 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2168 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002169 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002170 const CXXRecordDecl *FieldClassDecl
2171 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002172 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002173 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002174 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002175 }
2176 }
2177
2178 // Otherwise, the implicitly declared copy assignment operator will
2179 // have the form
2180 //
2181 // X& X::operator=(X&)
2182 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002183 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002184 if (HasConstCopyAssignment)
2185 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002186 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002187
2188 // An implicitly-declared copy assignment operator is an inline public
2189 // member of its class.
2190 DeclarationName Name =
2191 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2192 CXXMethodDecl *CopyAssignment =
2193 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2194 Context.getFunctionType(RetType, &ArgType, 1,
2195 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002196 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002197 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002198 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002199 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002200 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002201
2202 // Add the parameter to the operator.
2203 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2204 ClassDecl->getLocation(),
2205 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002206 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002207 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002208 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002209
2210 // Don't call addedAssignmentOperator. There is no way to distinguish an
2211 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002212 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002213 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002214 }
2215
Douglas Gregor1349b452008-12-15 21:24:18 +00002216 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002217 // C++ [class.dtor]p2:
2218 // If a class has no user-declared destructor, a destructor is
2219 // declared implicitly. An implicitly-declared destructor is an
2220 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002221 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002222 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002223 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002224 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002225 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002226 Context.getFunctionType(Context.VoidTy,
2227 0, 0, false, 0),
2228 /*isInline=*/true,
2229 /*isImplicitlyDeclared=*/true);
2230 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002231 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002232 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002233 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002234
2235 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002236 }
Douglas Gregor05379422008-11-03 17:51:48 +00002237}
2238
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002239void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002240 Decl *D = TemplateD.getAs<Decl>();
2241 if (!D)
2242 return;
2243
2244 TemplateParameterList *Params = 0;
2245 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2246 Params = Template->getTemplateParameters();
2247 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2248 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2249 Params = PartialSpec->getTemplateParameters();
2250 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002251 return;
2252
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002253 for (TemplateParameterList::iterator Param = Params->begin(),
2254 ParamEnd = Params->end();
2255 Param != ParamEnd; ++Param) {
2256 NamedDecl *Named = cast<NamedDecl>(*Param);
2257 if (Named->getDeclName()) {
2258 S->AddDecl(DeclPtrTy::make(Named));
2259 IdResolver.AddDecl(Named);
2260 }
2261 }
2262}
2263
Douglas Gregor4d87df52008-12-16 21:30:33 +00002264/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2265/// parsing a top-level (non-nested) C++ class, and we are now
2266/// parsing those parts of the given Method declaration that could
2267/// not be parsed earlier (C++ [class.mem]p2), such as default
2268/// arguments. This action should enter the scope of the given
2269/// Method declaration as if we had just parsed the qualified method
2270/// name. However, it should not bring the parameters into scope;
2271/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002272void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002273 if (!MethodD)
2274 return;
Mike Stump11289f42009-09-09 15:08:12 +00002275
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002276 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002277
Douglas Gregor4d87df52008-12-16 21:30:33 +00002278 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002279 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002280 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002281 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2282 SS.setScopeRep(
2283 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002284 ActOnCXXEnterDeclaratorScope(S, SS);
2285}
2286
2287/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2288/// C++ method declaration. We're (re-)introducing the given
2289/// function parameter into scope for use in parsing later parts of
2290/// the method declaration. For example, we could see an
2291/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002292void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002293 if (!ParamD)
2294 return;
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattner83f095c2009-03-28 19:18:32 +00002296 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002297
2298 // If this parameter has an unparsed default argument, clear it out
2299 // to make way for the parsed default argument.
2300 if (Param->hasUnparsedDefaultArg())
2301 Param->setDefaultArg(0);
2302
Chris Lattner83f095c2009-03-28 19:18:32 +00002303 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002304 if (Param->getDeclName())
2305 IdResolver.AddDecl(Param);
2306}
2307
2308/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2309/// processing the delayed method declaration for Method. The method
2310/// declaration is now considered finished. There may be a separate
2311/// ActOnStartOfFunctionDef action later (not necessarily
2312/// immediately!) for this method, if it was also defined inside the
2313/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002314void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002315 if (!MethodD)
2316 return;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002318 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002319
Chris Lattner83f095c2009-03-28 19:18:32 +00002320 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002321 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002322 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002323 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2324 SS.setScopeRep(
2325 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002326 ActOnCXXExitDeclaratorScope(S, SS);
2327
2328 // Now that we have our default arguments, check the constructor
2329 // again. It could produce additional diagnostics or affect whether
2330 // the class has implicitly-declared destructors, among other
2331 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002332 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2333 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002334
2335 // Check the default arguments, which we may have added.
2336 if (!Method->isInvalidDecl())
2337 CheckCXXDefaultArguments(Method);
2338}
2339
Douglas Gregor831c93f2008-11-05 20:51:48 +00002340/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002341/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002342/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002343/// emit diagnostics and set the invalid bit to true. In any case, the type
2344/// will be updated to reflect a well-formed type for the constructor and
2345/// returned.
2346QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2347 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002348 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002349
2350 // C++ [class.ctor]p3:
2351 // A constructor shall not be virtual (10.3) or static (9.4). A
2352 // constructor can be invoked for a const, volatile or const
2353 // volatile object. A constructor shall not be declared const,
2354 // volatile, or const volatile (9.3.2).
2355 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002356 if (!D.isInvalidType())
2357 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2358 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2359 << SourceRange(D.getIdentifierLoc());
2360 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002361 }
2362 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002363 if (!D.isInvalidType())
2364 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2365 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2366 << SourceRange(D.getIdentifierLoc());
2367 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002368 SC = FunctionDecl::None;
2369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370
Chris Lattner38378bf2009-04-25 08:28:21 +00002371 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2372 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002373 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002374 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2375 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002376 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002377 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2378 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002379 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002380 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2381 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002382 }
Mike Stump11289f42009-09-09 15:08:12 +00002383
Douglas Gregor831c93f2008-11-05 20:51:48 +00002384 // Rebuild the function type "R" without any type qualifiers (in
2385 // case any of the errors above fired) and with "void" as the
2386 // return type, since constructors don't have return types. We
2387 // *always* have to do this, because GetTypeForDeclarator will
2388 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002389 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002390 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2391 Proto->getNumArgs(),
2392 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002393}
2394
Douglas Gregor4d87df52008-12-16 21:30:33 +00002395/// CheckConstructor - Checks a fully-formed constructor for
2396/// well-formedness, issuing any diagnostics required. Returns true if
2397/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002398void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002399 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002400 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2401 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002402 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002403
2404 // C++ [class.copy]p3:
2405 // A declaration of a constructor for a class X is ill-formed if
2406 // its first parameter is of type (optionally cv-qualified) X and
2407 // either there are no other parameters or else all other
2408 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002409 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002410 ((Constructor->getNumParams() == 1) ||
2411 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002412 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2413 Constructor->getTemplateSpecializationKind()
2414 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002415 QualType ParamType = Constructor->getParamDecl(0)->getType();
2416 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2417 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002418 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2419 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002420 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002421
2422 // FIXME: Rather that making the constructor invalid, we should endeavor
2423 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002424 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002425 }
2426 }
Mike Stump11289f42009-09-09 15:08:12 +00002427
Douglas Gregor4d87df52008-12-16 21:30:33 +00002428 // Notify the class that we've added a constructor.
2429 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002430}
2431
Anders Carlsson26a807d2009-11-30 21:24:50 +00002432/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2433/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002434bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002435 CXXRecordDecl *RD = Destructor->getParent();
2436
2437 if (Destructor->isVirtual()) {
2438 SourceLocation Loc;
2439
2440 if (!Destructor->isImplicit())
2441 Loc = Destructor->getLocation();
2442 else
2443 Loc = RD->getLocation();
2444
2445 // If we have a virtual destructor, look up the deallocation function
2446 FunctionDecl *OperatorDelete = 0;
2447 DeclarationName Name =
2448 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002449 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002450 return true;
2451
2452 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002453 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002454
2455 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002456}
2457
Mike Stump11289f42009-09-09 15:08:12 +00002458static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002459FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2460 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2461 FTI.ArgInfo[0].Param &&
2462 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2463}
2464
Douglas Gregor831c93f2008-11-05 20:51:48 +00002465/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2466/// the well-formednes of the destructor declarator @p D with type @p
2467/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002468/// emit diagnostics and set the declarator to invalid. Even if this happens,
2469/// will be updated to reflect a well-formed type for the destructor and
2470/// returned.
2471QualType Sema::CheckDestructorDeclarator(Declarator &D,
2472 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002473 // C++ [class.dtor]p1:
2474 // [...] A typedef-name that names a class is a class-name
2475 // (7.1.3); however, a typedef-name that names a class shall not
2476 // be used as the identifier in the declarator for a destructor
2477 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002478 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002479 if (isa<TypedefType>(DeclaratorType)) {
2480 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002481 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002482 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002483 }
2484
2485 // C++ [class.dtor]p2:
2486 // A destructor is used to destroy objects of its class type. A
2487 // destructor takes no parameters, and no return type can be
2488 // specified for it (not even void). The address of a destructor
2489 // shall not be taken. A destructor shall not be static. A
2490 // destructor can be invoked for a const, volatile or const
2491 // volatile object. A destructor shall not be declared const,
2492 // volatile or const volatile (9.3.2).
2493 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002494 if (!D.isInvalidType())
2495 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2496 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2497 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002498 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002499 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002500 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002501 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002502 // Destructors don't have return types, but the parser will
2503 // happily parse something like:
2504 //
2505 // class X {
2506 // float ~X();
2507 // };
2508 //
2509 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002510 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2511 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2512 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002513 }
Mike Stump11289f42009-09-09 15:08:12 +00002514
Chris Lattner38378bf2009-04-25 08:28:21 +00002515 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2516 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002517 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002518 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2519 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002520 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002521 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2522 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002523 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002524 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2525 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002526 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002527 }
2528
2529 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002530 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002531 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2532
2533 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002534 FTI.freeArgs();
2535 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002536 }
2537
Mike Stump11289f42009-09-09 15:08:12 +00002538 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002539 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002540 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002541 D.setInvalidType();
2542 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002543
2544 // Rebuild the function type "R" without any type qualifiers or
2545 // parameters (in case any of the errors above fired) and with
2546 // "void" as the return type, since destructors don't have return
2547 // types. We *always* have to do this, because GetTypeForDeclarator
2548 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002549 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002550}
2551
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002552/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2553/// well-formednes of the conversion function declarator @p D with
2554/// type @p R. If there are any errors in the declarator, this routine
2555/// will emit diagnostics and return true. Otherwise, it will return
2556/// false. Either way, the type @p R will be updated to reflect a
2557/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002558void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002559 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002560 // C++ [class.conv.fct]p1:
2561 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002562 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002563 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002564 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002565 if (!D.isInvalidType())
2566 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2567 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2568 << SourceRange(D.getIdentifierLoc());
2569 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002570 SC = FunctionDecl::None;
2571 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002572 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002573 // Conversion functions don't have return types, but the parser will
2574 // happily parse something like:
2575 //
2576 // class X {
2577 // float operator bool();
2578 // };
2579 //
2580 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002581 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2582 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2583 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002584 }
2585
2586 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002587 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002588 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2589
2590 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002591 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002592 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002593 }
2594
Mike Stump11289f42009-09-09 15:08:12 +00002595 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002596 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002597 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002598 D.setInvalidType();
2599 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002600
2601 // C++ [class.conv.fct]p4:
2602 // The conversion-type-id shall not represent a function type nor
2603 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002604 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002605 if (ConvType->isArrayType()) {
2606 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2607 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002608 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002609 } else if (ConvType->isFunctionType()) {
2610 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2611 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002612 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002613 }
2614
2615 // Rebuild the function type "R" without any parameters (in case any
2616 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002617 // return type.
2618 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002619 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002620
Douglas Gregor5fb53972009-01-14 15:45:31 +00002621 // C++0x explicit conversion operators.
2622 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002623 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002624 diag::warn_explicit_conversion_functions)
2625 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002626}
2627
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002628/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2629/// the declaration of the given C++ conversion function. This routine
2630/// is responsible for recording the conversion function in the C++
2631/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002632Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002633 assert(Conversion && "Expected to receive a conversion function declaration");
2634
Douglas Gregor4287b372008-12-12 08:25:50 +00002635 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002636
2637 // Make sure we aren't redeclaring the conversion function.
2638 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002639
2640 // C++ [class.conv.fct]p1:
2641 // [...] A conversion function is never used to convert a
2642 // (possibly cv-qualified) object to the (possibly cv-qualified)
2643 // same object type (or a reference to it), to a (possibly
2644 // cv-qualified) base class of that type (or a reference to it),
2645 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002646 // FIXME: Suppress this warning if the conversion function ends up being a
2647 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002648 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002649 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002650 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002651 ConvType = ConvTypeRef->getPointeeType();
2652 if (ConvType->isRecordType()) {
2653 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2654 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002655 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002656 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002657 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002658 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002659 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002660 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002661 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002662 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002663 }
2664
Douglas Gregor1dc98262008-12-26 15:00:45 +00002665 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002666 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002667 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002668 = Conversion->getDescribedFunctionTemplate())
2669 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCalld14a8642009-11-21 08:51:07 +00002670 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2671 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002672 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002673 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002674 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002675 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002676 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002677 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002678
Chris Lattner83f095c2009-03-28 19:18:32 +00002679 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002680}
2681
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002682//===----------------------------------------------------------------------===//
2683// Namespace Handling
2684//===----------------------------------------------------------------------===//
2685
2686/// ActOnStartNamespaceDef - This is called at the start of a namespace
2687/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002688Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2689 SourceLocation IdentLoc,
2690 IdentifierInfo *II,
2691 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002692 NamespaceDecl *Namespc =
2693 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2694 Namespc->setLBracLoc(LBrace);
2695
2696 Scope *DeclRegionScope = NamespcScope->getParent();
2697
2698 if (II) {
2699 // C++ [namespace.def]p2:
2700 // The identifier in an original-namespace-definition shall not have been
2701 // previously defined in the declarative region in which the
2702 // original-namespace-definition appears. The identifier in an
2703 // original-namespace-definition is the name of the namespace. Subsequently
2704 // in that declarative region, it is treated as an original-namespace-name.
2705
John McCall9f3059a2009-10-09 21:13:30 +00002706 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002707 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002708 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002709
Douglas Gregor91f84212008-12-11 16:49:14 +00002710 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2711 // This is an extended namespace definition.
2712 // Attach this namespace decl to the chain of extended namespace
2713 // definitions.
2714 OrigNS->setNextNamespace(Namespc);
2715 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002716
Mike Stump11289f42009-09-09 15:08:12 +00002717 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002718 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002719 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002720 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002721 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002722 } else if (PrevDecl) {
2723 // This is an invalid name redefinition.
2724 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2725 << Namespc->getDeclName();
2726 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2727 Namespc->setInvalidDecl();
2728 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002729 } else if (II->isStr("std") &&
2730 CurContext->getLookupContext()->isTranslationUnit()) {
2731 // This is the first "real" definition of the namespace "std", so update
2732 // our cache of the "std" namespace to point at this definition.
2733 if (StdNamespace) {
2734 // We had already defined a dummy namespace "std". Link this new
2735 // namespace definition to the dummy namespace "std".
2736 StdNamespace->setNextNamespace(Namespc);
2737 StdNamespace->setLocation(IdentLoc);
2738 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2739 }
2740
2741 // Make our StdNamespace cache point at the first real definition of the
2742 // "std" namespace.
2743 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002744 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002745
2746 PushOnScopeChains(Namespc, DeclRegionScope);
2747 } else {
John McCall4fa53422009-10-01 00:25:31 +00002748 // Anonymous namespaces.
2749
2750 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2751 // behaves as if it were replaced by
2752 // namespace unique { /* empty body */ }
2753 // using namespace unique;
2754 // namespace unique { namespace-body }
2755 // where all occurrences of 'unique' in a translation unit are
2756 // replaced by the same identifier and this identifier differs
2757 // from all other identifiers in the entire program.
2758
2759 // We just create the namespace with an empty name and then add an
2760 // implicit using declaration, just like the standard suggests.
2761 //
2762 // CodeGen enforces the "universally unique" aspect by giving all
2763 // declarations semantically contained within an anonymous
2764 // namespace internal linkage.
2765
2766 assert(Namespc->isAnonymousNamespace());
2767 CurContext->addDecl(Namespc);
2768
2769 UsingDirectiveDecl* UD
2770 = UsingDirectiveDecl::Create(Context, CurContext,
2771 /* 'using' */ LBrace,
2772 /* 'namespace' */ SourceLocation(),
2773 /* qualifier */ SourceRange(),
2774 /* NNS */ NULL,
2775 /* identifier */ SourceLocation(),
2776 Namespc,
2777 /* Ancestor */ CurContext);
2778 UD->setImplicit();
2779 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002780 }
2781
2782 // Although we could have an invalid decl (i.e. the namespace name is a
2783 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002784 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2785 // for the namespace has the declarations that showed up in that particular
2786 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002787 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002788 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002789}
2790
Sebastian Redla6602e92009-11-23 15:34:23 +00002791/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2792/// is a namespace alias, returns the namespace it points to.
2793static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2794 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2795 return AD->getNamespace();
2796 return dyn_cast_or_null<NamespaceDecl>(D);
2797}
2798
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002799/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2800/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002801void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2802 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002803 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2804 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2805 Namespc->setRBracLoc(RBrace);
2806 PopDeclContext();
2807}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002808
Chris Lattner83f095c2009-03-28 19:18:32 +00002809Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2810 SourceLocation UsingLoc,
2811 SourceLocation NamespcLoc,
2812 const CXXScopeSpec &SS,
2813 SourceLocation IdentLoc,
2814 IdentifierInfo *NamespcName,
2815 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002816 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2817 assert(NamespcName && "Invalid NamespcName.");
2818 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002819 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002820
Douglas Gregor889ceb72009-02-03 19:21:40 +00002821 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002822
Douglas Gregor34074322009-01-14 22:20:51 +00002823 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002824 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2825 LookupParsedName(R, S, &SS);
2826 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002827 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002828
John McCall9f3059a2009-10-09 21:13:30 +00002829 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002830 NamedDecl *Named = R.getFoundDecl();
2831 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2832 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002833 // C++ [namespace.udir]p1:
2834 // A using-directive specifies that the names in the nominated
2835 // namespace can be used in the scope in which the
2836 // using-directive appears after the using-directive. During
2837 // unqualified name lookup (3.4.1), the names appear as if they
2838 // were declared in the nearest enclosing namespace which
2839 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002840 // namespace. [Note: in this context, "contains" means "contains
2841 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002842
2843 // Find enclosing context containing both using-directive and
2844 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002845 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002846 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2847 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2848 CommonAncestor = CommonAncestor->getParent();
2849
Sebastian Redla6602e92009-11-23 15:34:23 +00002850 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002851 SS.getRange(),
2852 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00002853 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002854 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002855 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002856 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002857 }
2858
Douglas Gregor889ceb72009-02-03 19:21:40 +00002859 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002860 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002861 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002862}
2863
2864void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2865 // If scope has associated entity, then using directive is at namespace
2866 // or translation unit scope. We add UsingDirectiveDecls, into
2867 // it's lookup structure.
2868 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002869 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002870 else
2871 // Otherwise it is block-sope. using-directives will affect lookup
2872 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002873 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002874}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002875
Douglas Gregorfec52632009-06-20 00:51:54 +00002876
2877Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002878 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002879 SourceLocation UsingLoc,
2880 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002881 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002882 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002883 bool IsTypeName,
2884 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002885 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002886
Douglas Gregor220f4272009-11-04 16:30:06 +00002887 switch (Name.getKind()) {
2888 case UnqualifiedId::IK_Identifier:
2889 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00002890 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00002891 case UnqualifiedId::IK_ConversionFunctionId:
2892 break;
2893
2894 case UnqualifiedId::IK_ConstructorName:
John McCall3969e302009-12-08 07:46:18 +00002895 // C++0x inherited constructors.
2896 if (getLangOptions().CPlusPlus0x) break;
2897
Douglas Gregor220f4272009-11-04 16:30:06 +00002898 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2899 << SS.getRange();
2900 return DeclPtrTy();
2901
2902 case UnqualifiedId::IK_DestructorName:
2903 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2904 << SS.getRange();
2905 return DeclPtrTy();
2906
2907 case UnqualifiedId::IK_TemplateId:
2908 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2909 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2910 return DeclPtrTy();
2911 }
2912
2913 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00002914 if (!TargetName)
2915 return DeclPtrTy();
2916
John McCall3f746822009-11-17 05:59:44 +00002917 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002918 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002919 TargetName, AttrList,
2920 /* IsInstantiation */ false,
2921 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00002922 if (UD)
2923 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00002924
Anders Carlsson696a3f12009-08-28 05:40:36 +00002925 return DeclPtrTy::make(UD);
2926}
2927
John McCall84d87672009-12-10 09:41:52 +00002928/// Determines whether to create a using shadow decl for a particular
2929/// decl, given the set of decls existing prior to this using lookup.
2930bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
2931 const LookupResult &Previous) {
2932 // Diagnose finding a decl which is not from a base class of the
2933 // current class. We do this now because there are cases where this
2934 // function will silently decide not to build a shadow decl, which
2935 // will pre-empt further diagnostics.
2936 //
2937 // We don't need to do this in C++0x because we do the check once on
2938 // the qualifier.
2939 //
2940 // FIXME: diagnose the following if we care enough:
2941 // struct A { int foo; };
2942 // struct B : A { using A::foo; };
2943 // template <class T> struct C : A {};
2944 // template <class T> struct D : C<T> { using B::foo; } // <---
2945 // This is invalid (during instantiation) in C++03 because B::foo
2946 // resolves to the using decl in B, which is not a base class of D<T>.
2947 // We can't diagnose it immediately because C<T> is an unknown
2948 // specialization. The UsingShadowDecl in D<T> then points directly
2949 // to A::foo, which will look well-formed when we instantiate.
2950 // The right solution is to not collapse the shadow-decl chain.
2951 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
2952 DeclContext *OrigDC = Orig->getDeclContext();
2953
2954 // Handle enums and anonymous structs.
2955 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
2956 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
2957 while (OrigRec->isAnonymousStructOrUnion())
2958 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
2959
2960 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
2961 if (OrigDC == CurContext) {
2962 Diag(Using->getLocation(),
2963 diag::err_using_decl_nested_name_specifier_is_current_class)
2964 << Using->getNestedNameRange();
2965 Diag(Orig->getLocation(), diag::note_using_decl_target);
2966 return true;
2967 }
2968
2969 Diag(Using->getNestedNameRange().getBegin(),
2970 diag::err_using_decl_nested_name_specifier_is_not_base_class)
2971 << Using->getTargetNestedNameDecl()
2972 << cast<CXXRecordDecl>(CurContext)
2973 << Using->getNestedNameRange();
2974 Diag(Orig->getLocation(), diag::note_using_decl_target);
2975 return true;
2976 }
2977 }
2978
2979 if (Previous.empty()) return false;
2980
2981 NamedDecl *Target = Orig;
2982 if (isa<UsingShadowDecl>(Target))
2983 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
2984
2985 if (Target->isFunctionOrFunctionTemplate()) {
2986 FunctionDecl *FD;
2987 if (isa<FunctionTemplateDecl>(Target))
2988 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
2989 else
2990 FD = cast<FunctionDecl>(Target);
2991
2992 NamedDecl *OldDecl = 0;
2993 switch (CheckOverload(FD, Previous, OldDecl)) {
2994 case Ovl_Overload:
2995 return false;
2996
2997 case Ovl_NonFunction:
2998 Diag(Using->getLocation(), diag::err_using_decl_conflict)
2999 << 0 // target decl is a function
3000 << 1; // other decl is not a function
3001 break;
3002
3003 // We found a decl with the exact signature.
3004 case Ovl_Match:
3005 if (isa<UsingShadowDecl>(OldDecl)) {
3006 // Silently ignore the possible conflict.
3007 return false;
3008 }
3009
3010 // If we're in a record, we want to hide the target, so we
3011 // return true (without a diagnostic) to tell the caller not to
3012 // build a shadow decl.
3013 if (CurContext->isRecord())
3014 return true;
3015
3016 // If we're not in a record, this is an error.
3017 Diag(Using->getLocation(), diag::err_using_decl_conflict)
3018 << 0 // target decl is a function
3019 << 0; // other decl is a function
3020 break;
3021 }
3022
3023 Diag(Target->getLocation(), diag::note_using_decl_target);
3024 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3025 return true;
3026 }
3027
3028 // Target is not a function.
3029
3030 // If the target happens to be one of the previous declarations, we
3031 // don't have a conflict.
3032 NamedDecl *NonTag = 0, *Tag = 0;
3033 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3034 I != E; ++I) {
3035 NamedDecl *D = (*I)->getUnderlyingDecl();
3036 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3037 return false;
3038
3039 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3040 }
3041
3042 if (isa<TagDecl>(Target)) {
3043 // No conflict between a tag and a non-tag.
3044 if (!Tag) return false;
3045
3046 Diag(Using->getLocation(), diag::err_using_decl_conflict)
3047 << 1 << 1; // both non-functions
3048 Diag(Target->getLocation(), diag::note_using_decl_target);
3049 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3050 return true;
3051 }
3052
3053 // No conflict between a tag and a non-tag.
3054 if (!NonTag) return false;
3055
3056 Diag(Using->getLocation(), diag::err_using_decl_conflict)
3057 << 1 // target not a function
3058 << int(NonTag->isFunctionOrFunctionTemplate());
3059 Diag(Target->getLocation(), diag::note_using_decl_target);
3060 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3061 return true;
3062}
3063
John McCall3f746822009-11-17 05:59:44 +00003064/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003065UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003066 UsingDecl *UD,
3067 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003068
3069 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003070 NamedDecl *Target = Orig;
3071 if (isa<UsingShadowDecl>(Target)) {
3072 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3073 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003074 }
3075
3076 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003077 = UsingShadowDecl::Create(Context, CurContext,
3078 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003079 UD->addShadowDecl(Shadow);
3080
3081 if (S)
John McCall3969e302009-12-08 07:46:18 +00003082 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003083 else
John McCall3969e302009-12-08 07:46:18 +00003084 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003085 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003086
John McCall3969e302009-12-08 07:46:18 +00003087 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3088 Shadow->setInvalidDecl();
3089
John McCall84d87672009-12-10 09:41:52 +00003090 return Shadow;
3091}
John McCall3969e302009-12-08 07:46:18 +00003092
John McCall84d87672009-12-10 09:41:52 +00003093/// Hides a using shadow declaration. This is required by the current
3094/// using-decl implementation when a resolvable using declaration in a
3095/// class is followed by a declaration which would hide or override
3096/// one or more of the using decl's targets; for example:
3097///
3098/// struct Base { void foo(int); };
3099/// struct Derived : Base {
3100/// using Base::foo;
3101/// void foo(int);
3102/// };
3103///
3104/// The governing language is C++03 [namespace.udecl]p12:
3105///
3106/// When a using-declaration brings names from a base class into a
3107/// derived class scope, member functions in the derived class
3108/// override and/or hide member functions with the same name and
3109/// parameter types in a base class (rather than conflicting).
3110///
3111/// There are two ways to implement this:
3112/// (1) optimistically create shadow decls when they're not hidden
3113/// by existing declarations, or
3114/// (2) don't create any shadow decls (or at least don't make them
3115/// visible) until we've fully parsed/instantiated the class.
3116/// The problem with (1) is that we might have to retroactively remove
3117/// a shadow decl, which requires several O(n) operations because the
3118/// decl structures are (very reasonably) not designed for removal.
3119/// (2) avoids this but is very fiddly and phase-dependent.
3120void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3121 // Remove it from the DeclContext...
3122 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003123
John McCall84d87672009-12-10 09:41:52 +00003124 // ...and the scope, if applicable...
3125 if (S) {
3126 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3127 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003128 }
3129
John McCall84d87672009-12-10 09:41:52 +00003130 // ...and the using decl.
3131 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3132
3133 // TODO: complain somehow if Shadow was used. It shouldn't
3134 // be possible for this to happen, because
John McCall3f746822009-11-17 05:59:44 +00003135}
3136
John McCalle61f2ba2009-11-18 02:36:19 +00003137/// Builds a using declaration.
3138///
3139/// \param IsInstantiation - Whether this call arises from an
3140/// instantiation of an unresolved using declaration. We treat
3141/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003142NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3143 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003144 const CXXScopeSpec &SS,
3145 SourceLocation IdentLoc,
3146 DeclarationName Name,
3147 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003148 bool IsInstantiation,
3149 bool IsTypeName,
3150 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003151 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3152 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003153
Anders Carlssonf038fc22009-08-28 05:49:21 +00003154 // FIXME: We ignore attributes for now.
3155 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003156
Anders Carlsson59140b32009-08-28 03:16:11 +00003157 if (SS.isEmpty()) {
3158 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003159 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
John McCall84d87672009-12-10 09:41:52 +00003162 // Do the redeclaration lookup in the current scope.
3163 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3164 ForRedeclaration);
3165 Previous.setHideTags(false);
3166 if (S) {
3167 LookupName(Previous, S);
3168
3169 // It is really dumb that we have to do this.
3170 LookupResult::Filter F = Previous.makeFilter();
3171 while (F.hasNext()) {
3172 NamedDecl *D = F.next();
3173 if (!isDeclInScope(D, CurContext, S))
3174 F.erase();
3175 }
3176 F.done();
3177 } else {
3178 assert(IsInstantiation && "no scope in non-instantiation");
3179 assert(CurContext->isRecord() && "scope not record in instantiation");
3180 LookupQualifiedName(Previous, CurContext);
3181 }
3182
Mike Stump11289f42009-09-09 15:08:12 +00003183 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003184 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3185
John McCall84d87672009-12-10 09:41:52 +00003186 // Check for invalid redeclarations.
3187 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3188 return 0;
3189
3190 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003191 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3192 return 0;
3193
John McCall84c16cf2009-11-12 03:15:40 +00003194 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003195 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003196 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003197 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003198 // FIXME: not all declaration name kinds are legal here
3199 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3200 UsingLoc, TypenameLoc,
3201 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003202 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003203 } else {
3204 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3205 UsingLoc, SS.getRange(), NNS,
3206 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003207 }
John McCallb96ec562009-12-04 22:46:56 +00003208 } else {
3209 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3210 SS.getRange(), UsingLoc, NNS, Name,
3211 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003212 }
John McCallb96ec562009-12-04 22:46:56 +00003213 D->setAccess(AS);
3214 CurContext->addDecl(D);
3215
3216 if (!LookupContext) return D;
3217 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003218
John McCall3969e302009-12-08 07:46:18 +00003219 if (RequireCompleteDeclContext(SS)) {
3220 UD->setInvalidDecl();
3221 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003222 }
3223
John McCall3969e302009-12-08 07:46:18 +00003224 // Look up the target name.
3225
John McCall27b18f82009-11-17 02:14:36 +00003226 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003227
John McCall3969e302009-12-08 07:46:18 +00003228 // Unlike most lookups, we don't always want to hide tag
3229 // declarations: tag names are visible through the using declaration
3230 // even if hidden by ordinary names, *except* in a dependent context
3231 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003232 if (!IsInstantiation)
3233 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003234
John McCall27b18f82009-11-17 02:14:36 +00003235 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003236
John McCall9f3059a2009-10-09 21:13:30 +00003237 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003238 Diag(IdentLoc, diag::err_no_member)
3239 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003240 UD->setInvalidDecl();
3241 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003242 }
3243
John McCallb96ec562009-12-04 22:46:56 +00003244 if (R.isAmbiguous()) {
3245 UD->setInvalidDecl();
3246 return UD;
3247 }
Mike Stump11289f42009-09-09 15:08:12 +00003248
John McCalle61f2ba2009-11-18 02:36:19 +00003249 if (IsTypeName) {
3250 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003251 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003252 Diag(IdentLoc, diag::err_using_typename_non_type);
3253 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3254 Diag((*I)->getUnderlyingDecl()->getLocation(),
3255 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003256 UD->setInvalidDecl();
3257 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003258 }
3259 } else {
3260 // If we asked for a non-typename and we got a type, error out,
3261 // but only if this is an instantiation of an unresolved using
3262 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003263 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003264 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3265 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003266 UD->setInvalidDecl();
3267 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003268 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003269 }
3270
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003271 // C++0x N2914 [namespace.udecl]p6:
3272 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003273 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003274 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3275 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003276 UD->setInvalidDecl();
3277 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003278 }
Mike Stump11289f42009-09-09 15:08:12 +00003279
John McCall84d87672009-12-10 09:41:52 +00003280 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3281 if (!CheckUsingShadowDecl(UD, *I, Previous))
3282 BuildUsingShadowDecl(S, UD, *I);
3283 }
John McCall3f746822009-11-17 05:59:44 +00003284
3285 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003286}
3287
John McCall84d87672009-12-10 09:41:52 +00003288/// Checks that the given using declaration is not an invalid
3289/// redeclaration. Note that this is checking only for the using decl
3290/// itself, not for any ill-formedness among the UsingShadowDecls.
3291bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3292 bool isTypeName,
3293 const CXXScopeSpec &SS,
3294 SourceLocation NameLoc,
3295 const LookupResult &Prev) {
3296 // C++03 [namespace.udecl]p8:
3297 // C++0x [namespace.udecl]p10:
3298 // A using-declaration is a declaration and can therefore be used
3299 // repeatedly where (and only where) multiple declarations are
3300 // allowed.
3301 // That's only in file contexts.
3302 if (CurContext->getLookupContext()->isFileContext())
3303 return false;
3304
3305 NestedNameSpecifier *Qual
3306 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3307
3308 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3309 NamedDecl *D = *I;
3310
3311 bool DTypename;
3312 NestedNameSpecifier *DQual;
3313 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3314 DTypename = UD->isTypeName();
3315 DQual = UD->getTargetNestedNameDecl();
3316 } else if (UnresolvedUsingValueDecl *UD
3317 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3318 DTypename = false;
3319 DQual = UD->getTargetNestedNameSpecifier();
3320 } else if (UnresolvedUsingTypenameDecl *UD
3321 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3322 DTypename = true;
3323 DQual = UD->getTargetNestedNameSpecifier();
3324 } else continue;
3325
3326 // using decls differ if one says 'typename' and the other doesn't.
3327 // FIXME: non-dependent using decls?
3328 if (isTypeName != DTypename) continue;
3329
3330 // using decls differ if they name different scopes (but note that
3331 // template instantiation can cause this check to trigger when it
3332 // didn't before instantiation).
3333 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3334 Context.getCanonicalNestedNameSpecifier(DQual))
3335 continue;
3336
3337 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3338 Diag(D->getLocation(), diag::note_previous_using_decl);
3339 return true;
3340 }
3341
3342 return false;
3343}
3344
John McCall3969e302009-12-08 07:46:18 +00003345
John McCallb96ec562009-12-04 22:46:56 +00003346/// Checks that the given nested-name qualifier used in a using decl
3347/// in the current context is appropriately related to the current
3348/// scope. If an error is found, diagnoses it and returns true.
3349bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3350 const CXXScopeSpec &SS,
3351 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003352 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003353
John McCall3969e302009-12-08 07:46:18 +00003354 if (!CurContext->isRecord()) {
3355 // C++03 [namespace.udecl]p3:
3356 // C++0x [namespace.udecl]p8:
3357 // A using-declaration for a class member shall be a member-declaration.
3358
3359 // If we weren't able to compute a valid scope, it must be a
3360 // dependent class scope.
3361 if (!NamedContext || NamedContext->isRecord()) {
3362 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3363 << SS.getRange();
3364 return true;
3365 }
3366
3367 // Otherwise, everything is known to be fine.
3368 return false;
3369 }
3370
3371 // The current scope is a record.
3372
3373 // If the named context is dependent, we can't decide much.
3374 if (!NamedContext) {
3375 // FIXME: in C++0x, we can diagnose if we can prove that the
3376 // nested-name-specifier does not refer to a base class, which is
3377 // still possible in some cases.
3378
3379 // Otherwise we have to conservatively report that things might be
3380 // okay.
3381 return false;
3382 }
3383
3384 if (!NamedContext->isRecord()) {
3385 // Ideally this would point at the last name in the specifier,
3386 // but we don't have that level of source info.
3387 Diag(SS.getRange().getBegin(),
3388 diag::err_using_decl_nested_name_specifier_is_not_class)
3389 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3390 return true;
3391 }
3392
3393 if (getLangOptions().CPlusPlus0x) {
3394 // C++0x [namespace.udecl]p3:
3395 // In a using-declaration used as a member-declaration, the
3396 // nested-name-specifier shall name a base class of the class
3397 // being defined.
3398
3399 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3400 cast<CXXRecordDecl>(NamedContext))) {
3401 if (CurContext == NamedContext) {
3402 Diag(NameLoc,
3403 diag::err_using_decl_nested_name_specifier_is_current_class)
3404 << SS.getRange();
3405 return true;
3406 }
3407
3408 Diag(SS.getRange().getBegin(),
3409 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3410 << (NestedNameSpecifier*) SS.getScopeRep()
3411 << cast<CXXRecordDecl>(CurContext)
3412 << SS.getRange();
3413 return true;
3414 }
3415
3416 return false;
3417 }
3418
3419 // C++03 [namespace.udecl]p4:
3420 // A using-declaration used as a member-declaration shall refer
3421 // to a member of a base class of the class being defined [etc.].
3422
3423 // Salient point: SS doesn't have to name a base class as long as
3424 // lookup only finds members from base classes. Therefore we can
3425 // diagnose here only if we can prove that that can't happen,
3426 // i.e. if the class hierarchies provably don't intersect.
3427
3428 // TODO: it would be nice if "definitely valid" results were cached
3429 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3430 // need to be repeated.
3431
3432 struct UserData {
3433 llvm::DenseSet<const CXXRecordDecl*> Bases;
3434
3435 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3436 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3437 Data->Bases.insert(Base);
3438 return true;
3439 }
3440
3441 bool hasDependentBases(const CXXRecordDecl *Class) {
3442 return !Class->forallBases(collect, this);
3443 }
3444
3445 /// Returns true if the base is dependent or is one of the
3446 /// accumulated base classes.
3447 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3448 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3449 return !Data->Bases.count(Base);
3450 }
3451
3452 bool mightShareBases(const CXXRecordDecl *Class) {
3453 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3454 }
3455 };
3456
3457 UserData Data;
3458
3459 // Returns false if we find a dependent base.
3460 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3461 return false;
3462
3463 // Returns false if the class has a dependent base or if it or one
3464 // of its bases is present in the base set of the current context.
3465 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3466 return false;
3467
3468 Diag(SS.getRange().getBegin(),
3469 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3470 << (NestedNameSpecifier*) SS.getScopeRep()
3471 << cast<CXXRecordDecl>(CurContext)
3472 << SS.getRange();
3473
3474 return true;
John McCallb96ec562009-12-04 22:46:56 +00003475}
3476
Mike Stump11289f42009-09-09 15:08:12 +00003477Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003478 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003479 SourceLocation AliasLoc,
3480 IdentifierInfo *Alias,
3481 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003482 SourceLocation IdentLoc,
3483 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003484
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003485 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003486 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3487 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003488
Anders Carlssondca83c42009-03-28 06:23:46 +00003489 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003490 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003491 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003492 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003493 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003494 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003495 if (!R.isAmbiguous() && !R.empty() &&
3496 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003497 return DeclPtrTy();
3498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
Anders Carlssondca83c42009-03-28 06:23:46 +00003500 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3501 diag::err_redefinition_different_kind;
3502 Diag(AliasLoc, DiagID) << Alias;
3503 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003504 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003505 }
3506
John McCall27b18f82009-11-17 02:14:36 +00003507 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003508 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003509
John McCall9f3059a2009-10-09 21:13:30 +00003510 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003511 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003512 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003513 }
Mike Stump11289f42009-09-09 15:08:12 +00003514
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003515 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003516 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3517 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003518 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003519 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003520
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003521 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003522 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003523}
3524
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003525void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3526 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003527 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3528 !Constructor->isUsed()) &&
3529 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003530
Eli Friedman9cf6b592009-11-09 19:20:36 +00003531 CXXRecordDecl *ClassDecl
3532 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3533 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003534
Eli Friedman9cf6b592009-11-09 19:20:36 +00003535 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003536 Diag(CurrentLocation, diag::note_member_synthesized_at)
3537 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003538 Constructor->setInvalidDecl();
3539 } else {
3540 Constructor->setUsed();
3541 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003542}
3543
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003544void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003545 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003546 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3547 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003548 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003549 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3550 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003551 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003552 // implicitly defined, all the implicitly-declared default destructors
3553 // for its base class and its non-static data members shall have been
3554 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003555 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3556 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003557 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003558 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003559 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003560 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003561 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3562 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3563 else
Mike Stump11289f42009-09-09 15:08:12 +00003564 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003565 "DefineImplicitDestructor - missing dtor in a base class");
3566 }
3567 }
Mike Stump11289f42009-09-09 15:08:12 +00003568
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003569 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3570 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003571 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3572 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3573 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003574 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003575 CXXRecordDecl *FieldClassDecl
3576 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3577 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003578 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003579 const_cast<CXXDestructorDecl*>(
3580 FieldClassDecl->getDestructor(Context)))
3581 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3582 else
Mike Stump11289f42009-09-09 15:08:12 +00003583 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003584 "DefineImplicitDestructor - missing dtor in class of a data member");
3585 }
3586 }
3587 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003588
3589 // FIXME: If CheckDestructor fails, we should emit a note about where the
3590 // implicit destructor was needed.
3591 if (CheckDestructor(Destructor)) {
3592 Diag(CurrentLocation, diag::note_member_synthesized_at)
3593 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3594
3595 Destructor->setInvalidDecl();
3596 return;
3597 }
3598
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003599 Destructor->setUsed();
3600}
3601
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003602void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3603 CXXMethodDecl *MethodDecl) {
3604 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3605 MethodDecl->getOverloadedOperator() == OO_Equal &&
3606 !MethodDecl->isUsed()) &&
3607 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003608
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003609 CXXRecordDecl *ClassDecl
3610 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003611
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003612 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003613 // Before the implicitly-declared copy assignment operator for a class is
3614 // implicitly defined, all implicitly-declared copy assignment operators
3615 // for its direct base classes and its nonstatic data members shall have
3616 // been implicitly defined.
3617 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003618 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3619 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003620 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003621 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003622 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003623 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3624 BaseClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003625 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3626 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003627 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3628 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003629 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3630 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3631 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003632 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003633 CXXRecordDecl *FieldClassDecl
3634 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003635 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003636 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3637 FieldClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003638 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003639 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003640 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003641 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3642 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003643 Diag(CurrentLocation, diag::note_first_required_here);
3644 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003645 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003646 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003647 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3648 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003649 Diag(CurrentLocation, diag::note_first_required_here);
3650 err = true;
3651 }
3652 }
3653 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003654 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003655}
3656
3657CXXMethodDecl *
Anders Carlssonefa47322009-12-09 03:01:51 +00003658Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3659 ParmVarDecl *ParmDecl,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003660 CXXRecordDecl *ClassDecl) {
3661 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3662 QualType RHSType(LHSType);
3663 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003664 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003665 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003666 RHSType = Context.getCVRQualifiedType(RHSType,
3667 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003668 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003669 LHSType,
3670 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003671 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003672 RHSType,
3673 CurrentLocation));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003674 Expr *Args[2] = { &*LHS, &*RHS };
3675 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003676 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003677 CandidateSet);
3678 OverloadCandidateSet::iterator Best;
Anders Carlssonefa47322009-12-09 03:01:51 +00003679 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003680 return cast<CXXMethodDecl>(Best->Function);
3681 assert(false &&
3682 "getAssignOperatorMethod - copy assignment operator method not found");
3683 return 0;
3684}
3685
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003686void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3687 CXXConstructorDecl *CopyConstructor,
3688 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003689 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003690 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3691 !CopyConstructor->isUsed()) &&
3692 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003693
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003694 CXXRecordDecl *ClassDecl
3695 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3696 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003697 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003698 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003699 // implicitly defined, all the implicitly-declared copy constructors
3700 // for its base class and its non-static data members shall have been
3701 // implicitly defined.
3702 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3703 Base != ClassDecl->bases_end(); ++Base) {
3704 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003705 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003706 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003707 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003708 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003709 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003710 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3711 FieldEnd = ClassDecl->field_end();
3712 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003713 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3714 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3715 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003716 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003717 CXXRecordDecl *FieldClassDecl
3718 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003719 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003720 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003721 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003722 }
3723 }
3724 CopyConstructor->setUsed();
3725}
3726
Anders Carlsson6eb55572009-08-25 05:12:04 +00003727Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003728Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003729 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003730 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003731 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003732
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003733 // C++ [class.copy]p15:
3734 // Whenever a temporary class object is copied using a copy constructor, and
3735 // this object and the copy have the same cv-unqualified type, an
3736 // implementation is permitted to treat the original and the copy as two
3737 // different ways of referring to the same object and not perform a copy at
3738 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003739
Anders Carlsson250aada2009-08-16 05:13:48 +00003740 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003741 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003742 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003743 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3744 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003745 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3746 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3747 E = ICE->getSubExpr();
Eli Friedmaneddf1212009-12-06 09:26:33 +00003748
3749 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3750 Elidable = !CE->getCallReturnType()->isReferenceType();
3751 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson250aada2009-08-16 05:13:48 +00003752 Elidable = true;
3753 }
Mike Stump11289f42009-09-09 15:08:12 +00003754
3755 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003756 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003757}
3758
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003759/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3760/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003761Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003762Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3763 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003764 MultiExprArg ExprArgs) {
3765 unsigned NumExprs = ExprArgs.size();
3766 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003767
Douglas Gregor27381f32009-11-23 12:27:39 +00003768 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003769 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3770 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003771}
3772
Anders Carlsson574315a2009-08-27 05:08:22 +00003773Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003774Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3775 QualType Ty,
3776 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003777 MultiExprArg Args,
3778 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003779 unsigned NumExprs = Args.size();
3780 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003781
Douglas Gregor27381f32009-11-23 12:27:39 +00003782 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003783 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3784 TyBeginLoc, Exprs,
3785 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003786}
3787
3788
Mike Stump11289f42009-09-09 15:08:12 +00003789bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003790 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003791 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003792 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003793 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003794 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003795 if (TempResult.isInvalid())
3796 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003797
Anders Carlsson6eb55572009-08-25 05:12:04 +00003798 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003799 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003800 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003801 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003802
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003803 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003804}
3805
Mike Stump11289f42009-09-09 15:08:12 +00003806void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003807 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003808 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003809 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003810 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003811 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003812 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003813}
3814
Mike Stump11289f42009-09-09 15:08:12 +00003815/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003816/// ActOnDeclarator, when a C++ direct initializer is present.
3817/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003818void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3819 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003820 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003821 SourceLocation *CommaLocs,
3822 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003823 unsigned NumExprs = Exprs.size();
3824 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003825 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003826
3827 // If there is no declaration, there was an error parsing it. Just ignore
3828 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003829 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003830 return;
Mike Stump11289f42009-09-09 15:08:12 +00003831
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003832 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3833 if (!VDecl) {
3834 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3835 RealDecl->setInvalidDecl();
3836 return;
3837 }
3838
Douglas Gregor402250f2009-08-26 21:14:46 +00003839 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003840 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003841 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3842 //
3843 // Clients that want to distinguish between the two forms, can check for
3844 // direct initializer using VarDecl::hasCXXDirectInitializer().
3845 // A major benefit is that clients that don't particularly care about which
3846 // exactly form was it (like the CodeGen) can handle both cases without
3847 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003848
Douglas Gregor402250f2009-08-26 21:14:46 +00003849 // If either the declaration has a dependent type or if any of the expressions
3850 // is type-dependent, we represent the initialization via a ParenListExpr for
3851 // later use during template instantiation.
3852 if (VDecl->getType()->isDependentType() ||
3853 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3854 // Let clients know that initialization was done with a direct initializer.
3855 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003856
Douglas Gregor402250f2009-08-26 21:14:46 +00003857 // Store the initialization expressions as a ParenListExpr.
3858 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003859 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003860 new (Context) ParenListExpr(Context, LParenLoc,
3861 (Expr **)Exprs.release(),
3862 NumExprs, RParenLoc));
3863 return;
3864 }
Mike Stump11289f42009-09-09 15:08:12 +00003865
Douglas Gregor402250f2009-08-26 21:14:46 +00003866
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003867 // C++ 8.5p11:
3868 // The form of initialization (using parentheses or '=') is generally
3869 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003870 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003871 QualType DeclInitType = VDecl->getType();
3872 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003873 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003874
Douglas Gregor4044d992009-03-24 16:43:20 +00003875 // FIXME: This isn't the right place to complete the type.
3876 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3877 diag::err_typecheck_decl_incomplete_type)) {
3878 VDecl->setInvalidDecl();
3879 return;
3880 }
3881
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003882 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003883 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3884
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003885 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003886 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003887 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003888 VDecl->getLocation(),
3889 SourceRange(VDecl->getLocation(),
3890 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003891 VDecl->getDeclName(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003892 InitializationKind::CreateDirect(VDecl->getLocation(),
3893 LParenLoc,
3894 RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003895 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003896 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003897 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003898 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003899 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003900 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003901 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003902 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003903 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003904 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003905 return;
3906 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003907
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003908 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003909 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3910 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003911 RealDecl->setInvalidDecl();
3912 return;
3913 }
3914
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003915 // Let clients know that initialization was done with a direct initializer.
3916 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003917
3918 assert(NumExprs == 1 && "Expected 1 expression");
3919 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003920 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3921 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003922}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003923
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003924/// \brief Add the applicable constructor candidates for an initialization
3925/// by constructor.
3926static void AddConstructorInitializationCandidates(Sema &SemaRef,
3927 QualType ClassType,
3928 Expr **Args,
3929 unsigned NumArgs,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003930 InitializationKind Kind,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003931 OverloadCandidateSet &CandidateSet) {
3932 // C++ [dcl.init]p14:
3933 // If the initialization is direct-initialization, or if it is
3934 // copy-initialization where the cv-unqualified version of the
3935 // source type is the same class as, or a derived class of, the
3936 // class of the destination, constructors are considered. The
3937 // applicable constructors are enumerated (13.3.1.3), and the
3938 // best one is chosen through overload resolution (13.3). The
3939 // constructor so selected is called to initialize the object,
3940 // with the initializer expression(s) as its argument(s). If no
3941 // constructor applies, or the overload resolution is ambiguous,
3942 // the initialization is ill-formed.
3943 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3944 assert(ClassRec && "Can only initialize a class type here");
3945
3946 // FIXME: When we decide not to synthesize the implicitly-declared
3947 // constructors, we'll need to make them appear here.
3948
3949 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3950 DeclarationName ConstructorName
3951 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3952 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3953 DeclContext::lookup_const_iterator Con, ConEnd;
3954 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3955 Con != ConEnd; ++Con) {
3956 // Find the constructor (which may be a template).
3957 CXXConstructorDecl *Constructor = 0;
3958 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3959 if (ConstructorTmpl)
3960 Constructor
3961 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3962 else
3963 Constructor = cast<CXXConstructorDecl>(*Con);
3964
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003965 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
3966 (Kind.getKind() == InitializationKind::IK_Value) ||
3967 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003968 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003969 ((Kind.getKind() == InitializationKind::IK_Default) &&
3970 Constructor->isDefaultConstructor())) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003971 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00003972 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3973 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003974 Args, NumArgs, CandidateSet);
3975 else
3976 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3977 }
3978 }
3979}
3980
3981/// \brief Attempt to perform initialization by constructor
3982/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3983/// copy-initialization.
3984///
3985/// This routine determines whether initialization by constructor is possible,
3986/// but it does not emit any diagnostics in the case where the initialization
3987/// is ill-formed.
3988///
3989/// \param ClassType the type of the object being initialized, which must have
3990/// class type.
3991///
3992/// \param Args the arguments provided to initialize the object
3993///
3994/// \param NumArgs the number of arguments provided to initialize the object
3995///
3996/// \param Kind the type of initialization being performed
3997///
3998/// \returns the constructor used to initialize the object, if successful.
3999/// Otherwise, emits a diagnostic and returns NULL.
4000CXXConstructorDecl *
4001Sema::TryInitializationByConstructor(QualType ClassType,
4002 Expr **Args, unsigned NumArgs,
4003 SourceLocation Loc,
4004 InitializationKind Kind) {
4005 // Build the overload candidate set
4006 OverloadCandidateSet CandidateSet;
4007 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4008 CandidateSet);
4009
4010 // Determine whether we found a constructor we can use.
4011 OverloadCandidateSet::iterator Best;
4012 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4013 case OR_Success:
4014 case OR_Deleted:
4015 // We found a constructor. Return it.
4016 return cast<CXXConstructorDecl>(Best->Function);
4017
4018 case OR_No_Viable_Function:
4019 case OR_Ambiguous:
4020 // Overload resolution failed. Return nothing.
4021 return 0;
4022 }
4023
4024 // Silence GCC warning
4025 return 0;
4026}
4027
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004028/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4029/// may occur as part of direct-initialization or copy-initialization.
4030///
4031/// \param ClassType the type of the object being initialized, which must have
4032/// class type.
4033///
4034/// \param ArgsPtr the arguments provided to initialize the object
4035///
4036/// \param Loc the source location where the initialization occurs
4037///
4038/// \param Range the source range that covers the entire initialization
4039///
4040/// \param InitEntity the name of the entity being initialized, if known
4041///
4042/// \param Kind the type of initialization being performed
4043///
4044/// \param ConvertedArgs a vector that will be filled in with the
4045/// appropriately-converted arguments to the constructor (if initialization
4046/// succeeded).
4047///
4048/// \returns the constructor used to initialize the object, if successful.
4049/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004050CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00004051Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004052 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00004053 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004054 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004055 InitializationKind Kind,
4056 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004057
4058 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004059 Expr **Args = (Expr **)ArgsPtr.get();
4060 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004061 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004062 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4063 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00004064
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004065 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004066 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004067 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004068 // We found a constructor. Break out so that we can convert the arguments
4069 // appropriately.
4070 break;
Mike Stump11289f42009-09-09 15:08:12 +00004071
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004072 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00004073 if (InitEntity)
4074 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00004075 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00004076 else
4077 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00004078 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00004079 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004080 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004081
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004082 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00004083 if (InitEntity)
4084 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4085 else
4086 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4088 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004089
4090 case OR_Deleted:
4091 if (InitEntity)
4092 Diag(Loc, diag::err_ovl_deleted_init)
4093 << Best->Function->isDeleted()
4094 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00004095 else {
4096 const CXXRecordDecl *RD =
4097 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004098 Diag(Loc, diag::err_ovl_deleted_init)
4099 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00004100 << RD->getDeclName() << Range;
4101 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00004102 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4103 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004106 // Convert the arguments, fill in default arguments, etc.
4107 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4108 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4109 return 0;
4110
4111 return Constructor;
4112}
4113
4114/// \brief Given a constructor and the set of arguments provided for the
4115/// constructor, convert the arguments and add any required default arguments
4116/// to form a proper call to this constructor.
4117///
4118/// \returns true if an error occurred, false otherwise.
4119bool
4120Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4121 MultiExprArg ArgsPtr,
4122 SourceLocation Loc,
4123 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4124 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4125 unsigned NumArgs = ArgsPtr.size();
4126 Expr **Args = (Expr **)ArgsPtr.get();
4127
4128 const FunctionProtoType *Proto
4129 = Constructor->getType()->getAs<FunctionProtoType>();
4130 assert(Proto && "Constructor without a prototype?");
4131 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004132
4133 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004134 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004135 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004136 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004137 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004138
4139 VariadicCallType CallType =
4140 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4141 llvm::SmallVector<Expr *, 8> AllArgs;
4142 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4143 Proto, 0, Args, NumArgs, AllArgs,
4144 CallType);
4145 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4146 ConvertedArgs.push_back(AllArgs[i]);
4147 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004148}
4149
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004150/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4151/// determine whether they are reference-related,
4152/// reference-compatible, reference-compatible with added
4153/// qualification, or incompatible, for use in C++ initialization by
4154/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4155/// type, and the first type (T1) is the pointee type of the reference
4156/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00004157Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004158Sema::CompareReferenceRelationship(SourceLocation Loc,
4159 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00004160 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004161 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004162 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004163 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004164
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004165 QualType T1 = Context.getCanonicalType(OrigT1);
4166 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004167 QualType UnqualT1 = T1.getLocalUnqualifiedType();
4168 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004169
4170 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004171 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00004172 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004173 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00004174 if (UnqualT1 == UnqualT2)
4175 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004176 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4177 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4178 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00004179 DerivedToBase = true;
4180 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004181 return Ref_Incompatible;
4182
4183 // At this point, we know that T1 and T2 are reference-related (at
4184 // least).
4185
4186 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004187 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004188 // reference-related to T2 and cv1 is the same cv-qualification
4189 // as, or greater cv-qualification than, cv2. For purposes of
4190 // overload resolution, cases for which cv1 is greater
4191 // cv-qualification than cv2 are identified as
4192 // reference-compatible with added qualification (see 13.3.3.2).
4193 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
4194 return Ref_Compatible;
4195 else if (T1.isMoreQualifiedThan(T2))
4196 return Ref_Compatible_With_Added_Qualification;
4197 else
4198 return Ref_Related;
4199}
4200
4201/// CheckReferenceInit - Check the initialization of a reference
4202/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4203/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00004204/// list), and DeclType is the type of the declaration. When ICS is
4205/// non-null, this routine will compute the implicit conversion
4206/// sequence according to C++ [over.ics.ref] and will not produce any
4207/// diagnostics; when ICS is null, it will emit diagnostics when any
4208/// errors are found. Either way, a return value of true indicates
4209/// that there was a failure, a return value of false indicates that
4210/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00004211///
4212/// When @p SuppressUserConversions, user-defined conversions are
4213/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004214/// When @p AllowExplicit, we also permit explicit user-defined
4215/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00004216/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00004217/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4218/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00004219bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00004220Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00004221 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004222 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00004223 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00004224 ImplicitConversionSequence *ICS,
4225 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004226 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4227
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004228 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004229 QualType T2 = Init->getType();
4230
Douglas Gregorcd695e52008-11-10 20:40:00 +00004231 // If the initializer is the address of an overloaded function, try
4232 // to resolve the overloaded function. If all goes well, T2 is the
4233 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004234 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00004235 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004236 ICS != 0);
4237 if (Fn) {
4238 // Since we're performing this reference-initialization for
4239 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004240 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00004241 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004242 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004243
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00004244 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004245 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004246
4247 T2 = Fn->getType();
4248 }
4249 }
4250
Douglas Gregor786ab212008-10-29 02:00:59 +00004251 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004252 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00004253 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00004254 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4255 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00004256 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004257 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00004258
4259 // Most paths end in a failed conversion.
4260 if (ICS)
4261 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004262
4263 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004264 // A reference to type "cv1 T1" is initialized by an expression
4265 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004266
4267 // -- If the initializer expression
4268
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004269 // Rvalue references cannot bind to lvalues (N2812).
4270 // There is absolutely no situation where they can. In particular, note that
4271 // this is ill-formed, even if B has a user-defined conversion to A&&:
4272 // B b;
4273 // A&& r = b;
4274 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4275 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004276 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004277 << Init->getSourceRange();
4278 return true;
4279 }
4280
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004281 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00004282 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4283 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00004284 //
4285 // Note that the bit-field check is skipped if we are just computing
4286 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00004287 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004288 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004289 BindsDirectly = true;
4290
Douglas Gregor786ab212008-10-29 02:00:59 +00004291 if (ICS) {
4292 // C++ [over.ics.ref]p1:
4293 // When a parameter of reference type binds directly (8.5.3)
4294 // to an argument expression, the implicit conversion sequence
4295 // is the identity conversion, unless the argument expression
4296 // has a type that is a derived class of the parameter type,
4297 // in which case the implicit conversion sequence is a
4298 // derived-to-base Conversion (13.3.3.1).
4299 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4300 ICS->Standard.First = ICK_Identity;
4301 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4302 ICS->Standard.Third = ICK_Identity;
4303 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4304 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004305 ICS->Standard.ReferenceBinding = true;
4306 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004307 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004308 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004309
4310 // Nothing more to do: the inaccessibility/ambiguity check for
4311 // derived-to-base conversions is suppressed when we're
4312 // computing the implicit conversion sequence (C++
4313 // [over.best.ics]p2).
4314 return false;
4315 } else {
4316 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004317 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4318 if (DerivedToBase)
4319 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004320 else if(CheckExceptionSpecCompatibility(Init, T1))
4321 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004322 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004323 }
4324 }
4325
4326 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00004327 // implicitly converted to an lvalue of type "cv3 T3,"
4328 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004329 // 92) (this conversion is selected by enumerating the
4330 // applicable conversion functions (13.3.1.6) and choosing
4331 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004332 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004333 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00004334 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004335 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004336
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004337 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00004338 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004339 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00004340 for (UnresolvedSet::iterator I = Conversions->begin(),
4341 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00004342 NamedDecl *D = *I;
4343 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4344 if (isa<UsingShadowDecl>(D))
4345 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4346
Mike Stump11289f42009-09-09 15:08:12 +00004347 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00004348 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00004349 CXXConversionDecl *Conv;
4350 if (ConvTemplate)
4351 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4352 else
John McCall6e9f8f62009-12-03 04:06:58 +00004353 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004354
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004355 // If the conversion function doesn't return a reference type,
4356 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004357 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00004358 (AllowExplicit || !Conv->isExplicit())) {
4359 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00004360 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4361 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004362 else
John McCall6e9f8f62009-12-03 04:06:58 +00004363 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004364 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004365 }
4366
4367 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00004368 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004369 case OR_Success:
4370 // This is a direct binding.
4371 BindsDirectly = true;
4372
4373 if (ICS) {
4374 // C++ [over.ics.ref]p1:
4375 //
4376 // [...] If the parameter binds directly to the result of
4377 // applying a conversion function to the argument
4378 // expression, the implicit conversion sequence is a
4379 // user-defined conversion sequence (13.3.3.1.2), with the
4380 // second standard conversion sequence either an identity
4381 // conversion or, if the conversion function returns an
4382 // entity of a type that is a derived class of the parameter
4383 // type, a derived-to-base Conversion.
4384 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4385 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4386 ICS->UserDefined.After = Best->FinalConversion;
4387 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004388 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004389 assert(ICS->UserDefined.After.ReferenceBinding &&
4390 ICS->UserDefined.After.DirectBinding &&
4391 "Expected a direct reference binding!");
4392 return false;
4393 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004394 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00004395 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004396 CastExpr::CK_UserDefinedConversion,
4397 cast<CXXMethodDecl>(Best->Function),
4398 Owned(Init));
4399 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00004400
4401 if (CheckExceptionSpecCompatibility(Init, T1))
4402 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004403 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4404 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004405 }
4406 break;
4407
4408 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004409 if (ICS) {
4410 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4411 Cand != CandidateSet.end(); ++Cand)
4412 if (Cand->Viable)
4413 ICS->ConversionFunctionSet.push_back(Cand->Function);
4414 break;
4415 }
4416 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4417 << Init->getSourceRange();
4418 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004419 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004420
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004421 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004422 case OR_Deleted:
4423 // There was no suitable conversion, or we found a deleted
4424 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004425 break;
4426 }
4427 }
Mike Stump11289f42009-09-09 15:08:12 +00004428
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004429 if (BindsDirectly) {
4430 // C++ [dcl.init.ref]p4:
4431 // [...] In all cases where the reference-related or
4432 // reference-compatible relationship of two types is used to
4433 // establish the validity of a reference binding, and T1 is a
4434 // base class of T2, a program that necessitates such a binding
4435 // is ill-formed if T1 is an inaccessible (clause 11) or
4436 // ambiguous (10.2) base class of T2.
4437 //
4438 // Note that we only check this condition when we're allowed to
4439 // complain about errors, because we should not be checking for
4440 // ambiguity (or inaccessibility) unless the reference binding
4441 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004442 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004443 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004444 Init->getSourceRange(),
4445 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004446 else
4447 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004448 }
4449
4450 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004451 // type (i.e., cv1 shall be const), or the reference shall be an
4452 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004453 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004454 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004455 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004456 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4457 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004458 return true;
4459 }
4460
4461 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004462 // class type, and "cv1 T1" is reference-compatible with
4463 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004464 // following ways (the choice is implementation-defined):
4465 //
4466 // -- The reference is bound to the object represented by
4467 // the rvalue (see 3.10) or to a sub-object within that
4468 // object.
4469 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004470 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004471 // a constructor is called to copy the entire rvalue
4472 // object into the temporary. The reference is bound to
4473 // the temporary or to a sub-object within the
4474 // temporary.
4475 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004476 // The constructor that would be used to make the copy
4477 // shall be callable whether or not the copy is actually
4478 // done.
4479 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004480 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004481 // freedom, so we will always take the first option and never build
4482 // a temporary in this case. FIXME: We will, however, have to check
4483 // for the presence of a copy constructor in C++98/03 mode.
4484 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004485 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4486 if (ICS) {
4487 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4488 ICS->Standard.First = ICK_Identity;
4489 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4490 ICS->Standard.Third = ICK_Identity;
4491 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4492 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004493 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004494 ICS->Standard.DirectBinding = false;
4495 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004496 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004497 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004498 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4499 if (DerivedToBase)
4500 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004501 else if(CheckExceptionSpecCompatibility(Init, T1))
4502 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004503 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004504 }
4505 return false;
4506 }
4507
Eli Friedman44b83ee2009-08-05 19:21:58 +00004508 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004509 // initialized from the initializer expression using the
4510 // rules for a non-reference copy initialization (8.5). The
4511 // reference is then bound to the temporary. If T1 is
4512 // reference-related to T2, cv1 must be the same
4513 // cv-qualification as, or greater cv-qualification than,
4514 // cv2; otherwise, the program is ill-formed.
4515 if (RefRelationship == Ref_Related) {
4516 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4517 // we would be reference-compatible or reference-compatible with
4518 // added qualification. But that wasn't the case, so the reference
4519 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004520 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004521 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004522 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4523 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004524 return true;
4525 }
4526
Douglas Gregor576e98c2009-01-30 23:27:23 +00004527 // If at least one of the types is a class type, the types are not
4528 // related, and we aren't allowed any user conversions, the
4529 // reference binding fails. This case is important for breaking
4530 // recursion, since TryImplicitConversion below will attempt to
4531 // create a temporary through the use of a copy constructor.
4532 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4533 (T1->isRecordType() || T2->isRecordType())) {
4534 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004535 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00004536 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4537 return true;
4538 }
4539
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004540 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004541 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004542 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004543 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004544 // When a parameter of reference type is not bound directly to
4545 // an argument expression, the conversion sequence is the one
4546 // required to convert the argument expression to the
4547 // underlying type of the reference according to
4548 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4549 // to copy-initializing a temporary of the underlying type with
4550 // the argument expression. Any difference in top-level
4551 // cv-qualification is subsumed by the initialization itself
4552 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004553 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4554 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004555 /*ForceRValue=*/false,
4556 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004557
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004558 // Of course, that's still a reference binding.
4559 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4560 ICS->Standard.ReferenceBinding = true;
4561 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004562 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004563 ImplicitConversionSequence::UserDefinedConversion) {
4564 ICS->UserDefined.After.ReferenceBinding = true;
4565 ICS->UserDefined.After.RRefBinding = isRValRef;
4566 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004567 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4568 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004569 ImplicitConversionSequence Conversions;
4570 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4571 false, false,
4572 Conversions);
4573 if (badConversion) {
4574 if ((Conversions.ConversionKind ==
4575 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004576 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004577 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004578 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4579 for (int j = Conversions.ConversionFunctionSet.size()-1;
4580 j >= 0; j--) {
4581 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4582 Diag(Func->getLocation(), diag::err_ovl_candidate);
4583 }
4584 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004585 else {
4586 if (isRValRef)
4587 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4588 << Init->getSourceRange();
4589 else
4590 Diag(DeclLoc, diag::err_invalid_initialization)
4591 << DeclType << Init->getType() << Init->getSourceRange();
4592 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004593 }
4594 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004595 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004596}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004597
4598/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4599/// of this overloaded operator is well-formed. If so, returns false;
4600/// otherwise, emits appropriate diagnostics and returns true.
4601bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004602 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004603 "Expected an overloaded operator declaration");
4604
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004605 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4606
Mike Stump11289f42009-09-09 15:08:12 +00004607 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004608 // The allocation and deallocation functions, operator new,
4609 // operator new[], operator delete and operator delete[], are
4610 // described completely in 3.7.3. The attributes and restrictions
4611 // found in the rest of this subclause do not apply to them unless
4612 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004613 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004614 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004615 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004616
4617 if (Op == OO_New || Op == OO_Array_New) {
4618 bool ret = false;
4619 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4620 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4621 QualType T = Context.getCanonicalType((*Param)->getType());
4622 if (!T->isDependentType() && SizeTy != T) {
4623 Diag(FnDecl->getLocation(),
4624 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4625 << SizeTy;
4626 ret = true;
4627 }
4628 }
4629 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4630 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4631 return Diag(FnDecl->getLocation(),
4632 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004633 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004634 return ret;
4635 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004636
4637 // C++ [over.oper]p6:
4638 // An operator function shall either be a non-static member
4639 // function or be a non-member function and have at least one
4640 // parameter whose type is a class, a reference to a class, an
4641 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004642 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4643 if (MethodDecl->isStatic())
4644 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004645 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004646 } else {
4647 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004648 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4649 ParamEnd = FnDecl->param_end();
4650 Param != ParamEnd; ++Param) {
4651 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004652 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4653 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004654 ClassOrEnumParam = true;
4655 break;
4656 }
4657 }
4658
Douglas Gregord69246b2008-11-17 16:14:12 +00004659 if (!ClassOrEnumParam)
4660 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004661 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004662 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004663 }
4664
4665 // C++ [over.oper]p8:
4666 // An operator function cannot have default arguments (8.3.6),
4667 // except where explicitly stated below.
4668 //
Mike Stump11289f42009-09-09 15:08:12 +00004669 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004670 // (C++ [over.call]p1).
4671 if (Op != OO_Call) {
4672 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4673 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004674 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004675 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004676 diag::err_operator_overload_default_arg)
4677 << FnDecl->getDeclName();
4678 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004679 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004680 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004681 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004682 }
4683 }
4684
Douglas Gregor6cf08062008-11-10 13:38:07 +00004685 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4686 { false, false, false }
4687#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4688 , { Unary, Binary, MemberOnly }
4689#include "clang/Basic/OperatorKinds.def"
4690 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004691
Douglas Gregor6cf08062008-11-10 13:38:07 +00004692 bool CanBeUnaryOperator = OperatorUses[Op][0];
4693 bool CanBeBinaryOperator = OperatorUses[Op][1];
4694 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004695
4696 // C++ [over.oper]p8:
4697 // [...] Operator functions cannot have more or fewer parameters
4698 // than the number required for the corresponding operator, as
4699 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004700 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004701 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004702 if (Op != OO_Call &&
4703 ((NumParams == 1 && !CanBeUnaryOperator) ||
4704 (NumParams == 2 && !CanBeBinaryOperator) ||
4705 (NumParams < 1) || (NumParams > 2))) {
4706 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004707 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004708 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004709 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004710 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004711 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004712 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004713 assert(CanBeBinaryOperator &&
4714 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004715 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004716 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004717
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004718 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004719 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004720 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004721
Douglas Gregord69246b2008-11-17 16:14:12 +00004722 // Overloaded operators other than operator() cannot be variadic.
4723 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004724 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004725 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004726 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004727 }
4728
4729 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004730 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4731 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004732 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004733 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004734 }
4735
4736 // C++ [over.inc]p1:
4737 // The user-defined function called operator++ implements the
4738 // prefix and postfix ++ operator. If this function is a member
4739 // function with no parameters, or a non-member function with one
4740 // parameter of class or enumeration type, it defines the prefix
4741 // increment operator ++ for objects of that type. If the function
4742 // is a member function with one parameter (which shall be of type
4743 // int) or a non-member function with two parameters (the second
4744 // of which shall be of type int), it defines the postfix
4745 // increment operator ++ for objects of that type.
4746 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4747 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4748 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004749 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004750 ParamIsInt = BT->getKind() == BuiltinType::Int;
4751
Chris Lattner2b786902008-11-21 07:50:02 +00004752 if (!ParamIsInt)
4753 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004754 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004755 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004756 }
4757
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004758 // Notify the class if it got an assignment operator.
4759 if (Op == OO_Equal) {
4760 // Would have returned earlier otherwise.
4761 assert(isa<CXXMethodDecl>(FnDecl) &&
4762 "Overloaded = not member, but not filtered.");
4763 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4764 Method->getParent()->addedAssignmentOperator(Context, Method);
4765 }
4766
Douglas Gregord69246b2008-11-17 16:14:12 +00004767 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004768}
Chris Lattner3b024a32008-12-17 07:09:26 +00004769
Douglas Gregor07665a62009-01-05 19:45:36 +00004770/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4771/// linkage specification, including the language and (if present)
4772/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4773/// the location of the language string literal, which is provided
4774/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4775/// the '{' brace. Otherwise, this linkage specification does not
4776/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004777Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4778 SourceLocation ExternLoc,
4779 SourceLocation LangLoc,
4780 const char *Lang,
4781 unsigned StrSize,
4782 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004783 LinkageSpecDecl::LanguageIDs Language;
4784 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4785 Language = LinkageSpecDecl::lang_c;
4786 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4787 Language = LinkageSpecDecl::lang_cxx;
4788 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004789 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004790 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004791 }
Mike Stump11289f42009-09-09 15:08:12 +00004792
Chris Lattner438e5012008-12-17 07:13:27 +00004793 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004794
Douglas Gregor07665a62009-01-05 19:45:36 +00004795 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004796 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004797 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004798 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004799 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004800 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004801}
4802
Douglas Gregor07665a62009-01-05 19:45:36 +00004803/// ActOnFinishLinkageSpecification - Completely the definition of
4804/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4805/// valid, it's the position of the closing '}' brace in a linkage
4806/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004807Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4808 DeclPtrTy LinkageSpec,
4809 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004810 if (LinkageSpec)
4811 PopDeclContext();
4812 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004813}
4814
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004815/// \brief Perform semantic analysis for the variable declaration that
4816/// occurs within a C++ catch clause, returning the newly-created
4817/// variable.
4818VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00004819 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004820 IdentifierInfo *Name,
4821 SourceLocation Loc,
4822 SourceRange Range) {
4823 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004824
4825 // Arrays and functions decay.
4826 if (ExDeclType->isArrayType())
4827 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4828 else if (ExDeclType->isFunctionType())
4829 ExDeclType = Context.getPointerType(ExDeclType);
4830
4831 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4832 // The exception-declaration shall not denote a pointer or reference to an
4833 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004834 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004835 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004836 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004837 Invalid = true;
4838 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004839
Sebastian Redl54c04d42008-12-22 19:15:10 +00004840 QualType BaseType = ExDeclType;
4841 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004842 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004843 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004844 BaseType = Ptr->getPointeeType();
4845 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004846 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004847 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004848 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004849 BaseType = Ref->getPointeeType();
4850 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004851 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004852 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004853 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004854 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004855 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004856
Mike Stump11289f42009-09-09 15:08:12 +00004857 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004858 RequireNonAbstractType(Loc, ExDeclType,
4859 diag::err_abstract_type_in_decl,
4860 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004861 Invalid = true;
4862
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004863 // FIXME: Need to test for ability to copy-construct and destroy the
4864 // exception variable.
4865
Sebastian Redl9b244a82008-12-22 21:35:02 +00004866 // FIXME: Need to check for abstract classes.
4867
Mike Stump11289f42009-09-09 15:08:12 +00004868 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCallbcd03502009-12-07 02:54:59 +00004869 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004870
4871 if (Invalid)
4872 ExDecl->setInvalidDecl();
4873
4874 return ExDecl;
4875}
4876
4877/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4878/// handler.
4879Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00004880 TypeSourceInfo *TInfo = 0;
4881 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004882
4883 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004884 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004885 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004886 // The scope should be freshly made just for us. There is just no way
4887 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004888 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004889 if (PrevDecl->isTemplateParameter()) {
4890 // Maybe we will complain about the shadowed template parameter.
4891 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004892 }
4893 }
4894
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004895 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004896 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4897 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004898 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004899 }
4900
John McCallbcd03502009-12-07 02:54:59 +00004901 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004902 D.getIdentifier(),
4903 D.getIdentifierLoc(),
4904 D.getDeclSpec().getSourceRange());
4905
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004906 if (Invalid)
4907 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004908
Sebastian Redl54c04d42008-12-22 19:15:10 +00004909 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004910 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004911 PushOnScopeChains(ExDecl, S);
4912 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004913 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004914
Douglas Gregor758a8692009-06-17 21:51:59 +00004915 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004916 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004917}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004918
Mike Stump11289f42009-09-09 15:08:12 +00004919Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004920 ExprArg assertexpr,
4921 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004922 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004923 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004924 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4925
Anders Carlsson54b26982009-03-14 00:33:21 +00004926 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4927 llvm::APSInt Value(32);
4928 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4929 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4930 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004931 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004932 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004933
Anders Carlsson54b26982009-03-14 00:33:21 +00004934 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004935 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004936 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004937 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004938 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004939 }
4940 }
Mike Stump11289f42009-09-09 15:08:12 +00004941
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004942 assertexpr.release();
4943 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004944 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004945 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004946
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004947 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004948 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004949}
Sebastian Redlf769df52009-03-24 22:27:57 +00004950
John McCall11083da2009-09-16 22:47:08 +00004951/// Handle a friend type declaration. This works in tandem with
4952/// ActOnTag.
4953///
4954/// Notes on friend class templates:
4955///
4956/// We generally treat friend class declarations as if they were
4957/// declaring a class. So, for example, the elaborated type specifier
4958/// in a friend declaration is required to obey the restrictions of a
4959/// class-head (i.e. no typedefs in the scope chain), template
4960/// parameters are required to match up with simple template-ids, &c.
4961/// However, unlike when declaring a template specialization, it's
4962/// okay to refer to a template specialization without an empty
4963/// template parameter declaration, e.g.
4964/// friend class A<T>::B<unsigned>;
4965/// We permit this as a special case; if there are any template
4966/// parameters present at all, require proper matching, i.e.
4967/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004968Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004969 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004970 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004971
4972 assert(DS.isFriendSpecified());
4973 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4974
John McCall11083da2009-09-16 22:47:08 +00004975 // Try to convert the decl specifier to a type. This works for
4976 // friend templates because ActOnTag never produces a ClassTemplateDecl
4977 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004978 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004979 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4980 if (TheDeclarator.isInvalidType())
4981 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004982
John McCall11083da2009-09-16 22:47:08 +00004983 // This is definitely an error in C++98. It's probably meant to
4984 // be forbidden in C++0x, too, but the specification is just
4985 // poorly written.
4986 //
4987 // The problem is with declarations like the following:
4988 // template <T> friend A<T>::foo;
4989 // where deciding whether a class C is a friend or not now hinges
4990 // on whether there exists an instantiation of A that causes
4991 // 'foo' to equal C. There are restrictions on class-heads
4992 // (which we declare (by fiat) elaborated friend declarations to
4993 // be) that makes this tractable.
4994 //
4995 // FIXME: handle "template <> friend class A<T>;", which
4996 // is possibly well-formed? Who even knows?
4997 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4998 Diag(Loc, diag::err_tagless_friend_type_template)
4999 << DS.getSourceRange();
5000 return DeclPtrTy();
5001 }
5002
John McCallaa74a0c2009-08-28 07:59:38 +00005003 // C++ [class.friend]p2:
5004 // An elaborated-type-specifier shall be used in a friend declaration
5005 // for a class.*
5006 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00005007 // This is one of the rare places in Clang where it's legitimate to
5008 // ask about the "spelling" of the type.
5009 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5010 // If we evaluated the type to a record type, suggest putting
5011 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00005012 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00005013 RecordDecl *RD = RT->getDecl();
5014
5015 std::string InsertionText = std::string(" ") + RD->getKindName();
5016
John McCallc3987482009-10-07 23:34:25 +00005017 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5018 << (unsigned) RD->getTagKind()
5019 << T
5020 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00005021 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5022 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00005023 return DeclPtrTy();
5024 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00005025 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5026 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005027 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00005028 }
5029 }
5030
John McCallc3987482009-10-07 23:34:25 +00005031 // Enum types cannot be friends.
5032 if (T->getAs<EnumType>()) {
5033 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5034 << SourceRange(DS.getFriendSpecLoc());
5035 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00005036 }
John McCallaa74a0c2009-08-28 07:59:38 +00005037
John McCallaa74a0c2009-08-28 07:59:38 +00005038 // C++98 [class.friend]p1: A friend of a class is a function
5039 // or class that is not a member of the class . . .
5040 // But that's a silly restriction which nobody implements for
5041 // inner classes, and C++0x removes it anyway, so we only report
5042 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00005043 if (!getLangOptions().CPlusPlus0x)
5044 if (const RecordType *RT = T->getAs<RecordType>())
5045 if (RT->getDecl()->getDeclContext() == CurContext)
5046 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00005047
John McCall11083da2009-09-16 22:47:08 +00005048 Decl *D;
5049 if (TempParams.size())
5050 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5051 TempParams.size(),
5052 (TemplateParameterList**) TempParams.release(),
5053 T.getTypePtr(),
5054 DS.getFriendSpecLoc());
5055 else
5056 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5057 DS.getFriendSpecLoc());
5058 D->setAccess(AS_public);
5059 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005060
John McCall11083da2009-09-16 22:47:08 +00005061 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005062}
5063
John McCall2f212b32009-09-11 21:02:39 +00005064Sema::DeclPtrTy
5065Sema::ActOnFriendFunctionDecl(Scope *S,
5066 Declarator &D,
5067 bool IsDefinition,
5068 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005069 const DeclSpec &DS = D.getDeclSpec();
5070
5071 assert(DS.isFriendSpecified());
5072 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5073
5074 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005075 TypeSourceInfo *TInfo = 0;
5076 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005077
5078 // C++ [class.friend]p1
5079 // A friend of a class is a function or class....
5080 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005081 // It *doesn't* see through dependent types, which is correct
5082 // according to [temp.arg.type]p3:
5083 // If a declaration acquires a function type through a
5084 // type dependent on a template-parameter and this causes
5085 // a declaration that does not use the syntactic form of a
5086 // function declarator to have a function type, the program
5087 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005088 if (!T->isFunctionType()) {
5089 Diag(Loc, diag::err_unexpected_friend);
5090
5091 // It might be worthwhile to try to recover by creating an
5092 // appropriate declaration.
5093 return DeclPtrTy();
5094 }
5095
5096 // C++ [namespace.memdef]p3
5097 // - If a friend declaration in a non-local class first declares a
5098 // class or function, the friend class or function is a member
5099 // of the innermost enclosing namespace.
5100 // - The name of the friend is not found by simple name lookup
5101 // until a matching declaration is provided in that namespace
5102 // scope (either before or after the class declaration granting
5103 // friendship).
5104 // - If a friend function is called, its name may be found by the
5105 // name lookup that considers functions from namespaces and
5106 // classes associated with the types of the function arguments.
5107 // - When looking for a prior declaration of a class or a function
5108 // declared as a friend, scopes outside the innermost enclosing
5109 // namespace scope are not considered.
5110
John McCallaa74a0c2009-08-28 07:59:38 +00005111 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5112 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005113 assert(Name);
5114
John McCall07e91c02009-08-06 02:15:43 +00005115 // The context we found the declaration in, or in which we should
5116 // create the declaration.
5117 DeclContext *DC;
5118
5119 // FIXME: handle local classes
5120
5121 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005122 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5123 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005124 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005125 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00005126 DC = computeDeclContext(ScopeQual);
5127
5128 // FIXME: handle dependent contexts
5129 if (!DC) return DeclPtrTy();
5130
John McCall1f82f242009-11-18 22:49:29 +00005131 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005132
5133 // If searching in that context implicitly found a declaration in
5134 // a different context, treat it like it wasn't found at all.
5135 // TODO: better diagnostics for this case. Suggesting the right
5136 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005137 // FIXME: getRepresentativeDecl() is not right here at all
5138 if (Previous.empty() ||
5139 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005140 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005141 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5142 return DeclPtrTy();
5143 }
5144
5145 // C++ [class.friend]p1: A friend of a class is a function or
5146 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005147 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005148 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5149
John McCall07e91c02009-08-06 02:15:43 +00005150 // Otherwise walk out to the nearest namespace scope looking for matches.
5151 } else {
5152 // TODO: handle local class contexts.
5153
5154 DC = CurContext;
5155 while (true) {
5156 // Skip class contexts. If someone can cite chapter and verse
5157 // for this behavior, that would be nice --- it's what GCC and
5158 // EDG do, and it seems like a reasonable intent, but the spec
5159 // really only says that checks for unqualified existing
5160 // declarations should stop at the nearest enclosing namespace,
5161 // not that they should only consider the nearest enclosing
5162 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005163 while (DC->isRecord())
5164 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005165
John McCall1f82f242009-11-18 22:49:29 +00005166 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005167
5168 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005169 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005170 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005171
John McCall07e91c02009-08-06 02:15:43 +00005172 if (DC->isFileContext()) break;
5173 DC = DC->getParent();
5174 }
5175
5176 // C++ [class.friend]p1: A friend of a class is a function or
5177 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005178 // C++0x changes this for both friend types and functions.
5179 // Most C++ 98 compilers do seem to give an error here, so
5180 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005181 if (!Previous.empty() && DC->Equals(CurContext)
5182 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005183 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5184 }
5185
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005186 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005187 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005188 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5189 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5190 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005191 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005192 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5193 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005194 return DeclPtrTy();
5195 }
John McCall07e91c02009-08-06 02:15:43 +00005196 }
5197
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005198 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005199 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005200 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005201 IsDefinition,
5202 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005203 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005204
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005205 assert(ND->getDeclContext() == DC);
5206 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005207
John McCall759e32b2009-08-31 22:39:49 +00005208 // Add the function declaration to the appropriate lookup tables,
5209 // adjusting the redeclarations list as necessary. We don't
5210 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005211 //
John McCall759e32b2009-08-31 22:39:49 +00005212 // Also update the scope-based lookup if the target context's
5213 // lookup context is in lexical scope.
5214 if (!CurContext->isDependentContext()) {
5215 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005216 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005217 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005218 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005219 }
John McCallaa74a0c2009-08-28 07:59:38 +00005220
5221 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005222 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005223 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005224 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005225 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005226
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005227 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005228}
5229
Chris Lattner83f095c2009-03-28 19:18:32 +00005230void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005231 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005232
Chris Lattner83f095c2009-03-28 19:18:32 +00005233 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005234 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5235 if (!Fn) {
5236 Diag(DelLoc, diag::err_deleted_non_function);
5237 return;
5238 }
5239 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5240 Diag(DelLoc, diag::err_deleted_decl_not_first);
5241 Diag(Prev->getLocation(), diag::note_previous_declaration);
5242 // If the declaration wasn't the first, we delete the function anyway for
5243 // recovery.
5244 }
5245 Fn->setDeleted();
5246}
Sebastian Redl4c018662009-04-27 21:33:24 +00005247
5248static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5249 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5250 ++CI) {
5251 Stmt *SubStmt = *CI;
5252 if (!SubStmt)
5253 continue;
5254 if (isa<ReturnStmt>(SubStmt))
5255 Self.Diag(SubStmt->getSourceRange().getBegin(),
5256 diag::err_return_in_constructor_handler);
5257 if (!isa<Expr>(SubStmt))
5258 SearchForReturnInStmt(Self, SubStmt);
5259 }
5260}
5261
5262void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5263 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5264 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5265 SearchForReturnInStmt(*this, Handler);
5266 }
5267}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005268
Mike Stump11289f42009-09-09 15:08:12 +00005269bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005270 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005271 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5272 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005273
5274 QualType CNewTy = Context.getCanonicalType(NewTy);
5275 QualType COldTy = Context.getCanonicalType(OldTy);
5276
Mike Stump11289f42009-09-09 15:08:12 +00005277 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005278 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005280
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005281 // Check if the return types are covariant
5282 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005283
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005284 /// Both types must be pointers or references to classes.
5285 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5286 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5287 NewClassTy = NewPT->getPointeeType();
5288 OldClassTy = OldPT->getPointeeType();
5289 }
5290 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5291 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5292 NewClassTy = NewRT->getPointeeType();
5293 OldClassTy = OldRT->getPointeeType();
5294 }
5295 }
Mike Stump11289f42009-09-09 15:08:12 +00005296
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005297 // The return types aren't either both pointers or references to a class type.
5298 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005299 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005300 diag::err_different_return_type_for_overriding_virtual_function)
5301 << New->getDeclName() << NewTy << OldTy;
5302 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005303
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005304 return true;
5305 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005306
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005307 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005308 // Check if the new class derives from the old class.
5309 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5310 Diag(New->getLocation(),
5311 diag::err_covariant_return_not_derived)
5312 << New->getDeclName() << NewTy << OldTy;
5313 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5314 return true;
5315 }
Mike Stump11289f42009-09-09 15:08:12 +00005316
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005317 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00005318 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005319 diag::err_covariant_return_inaccessible_base,
5320 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5321 // FIXME: Should this point to the return type?
5322 New->getLocation(), SourceRange(), New->getDeclName())) {
5323 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5324 return true;
5325 }
5326 }
Mike Stump11289f42009-09-09 15:08:12 +00005327
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005328 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005329 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005330 Diag(New->getLocation(),
5331 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005332 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005333 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5334 return true;
5335 };
Mike Stump11289f42009-09-09 15:08:12 +00005336
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005337
5338 // The new class type must have the same or less qualifiers as the old type.
5339 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5340 Diag(New->getLocation(),
5341 diag::err_covariant_return_type_class_type_more_qualified)
5342 << New->getDeclName() << NewTy << OldTy;
5343 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5344 return true;
5345 };
Mike Stump11289f42009-09-09 15:08:12 +00005346
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005347 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005348}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005349
Alexis Hunt96d5c762009-11-21 08:43:09 +00005350bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5351 const CXXMethodDecl *Old)
5352{
5353 if (Old->hasAttr<FinalAttr>()) {
5354 Diag(New->getLocation(), diag::err_final_function_overridden)
5355 << New->getDeclName();
5356 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5357 return true;
5358 }
5359
5360 return false;
5361}
5362
Douglas Gregor21920e372009-12-01 17:24:26 +00005363/// \brief Mark the given method pure.
5364///
5365/// \param Method the method to be marked pure.
5366///
5367/// \param InitRange the source range that covers the "0" initializer.
5368bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5369 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5370 Method->setPure();
5371
5372 // A class is abstract if at least one function is pure virtual.
5373 Method->getParent()->setAbstract(true);
5374 return false;
5375 }
5376
5377 if (!Method->isInvalidDecl())
5378 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5379 << Method->getDeclName() << InitRange;
5380 return true;
5381}
5382
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005383/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5384/// initializer for the declaration 'Dcl'.
5385/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5386/// static data member of class X, names should be looked up in the scope of
5387/// class X.
5388void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005389 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005390
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005391 Decl *D = Dcl.getAs<Decl>();
5392 // If there is no declaration, there was an error parsing it.
5393 if (D == 0)
5394 return;
5395
5396 // Check whether it is a declaration with a nested name specifier like
5397 // int foo::bar;
5398 if (!D->isOutOfLine())
5399 return;
Mike Stump11289f42009-09-09 15:08:12 +00005400
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005401 // C++ [basic.lookup.unqual]p13
5402 //
5403 // A name used in the definition of a static data member of class X
5404 // (after the qualified-id of the static member) is looked up as if the name
5405 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00005406
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005407 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00005408 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005409}
5410
5411/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5412/// initializer for the declaration 'Dcl'.
5413void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005414 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005415
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005416 Decl *D = Dcl.getAs<Decl>();
5417 // If there is no declaration, there was an error parsing it.
5418 if (D == 0)
5419 return;
5420
5421 // Check whether it is a declaration with a nested name specifier like
5422 // int foo::bar;
5423 if (!D->isOutOfLine())
5424 return;
5425
5426 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00005427 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005428}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005429
5430/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5431/// C++ if/switch/while/for statement.
5432/// e.g: "if (int x = f()) {...}"
5433Action::DeclResult
5434Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5435 // C++ 6.4p2:
5436 // The declarator shall not specify a function or an array.
5437 // The type-specifier-seq shall not contain typedef and shall not declare a
5438 // new class or enumeration.
5439 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5440 "Parser allowed 'typedef' as storage class of condition decl.");
5441
John McCallbcd03502009-12-07 02:54:59 +00005442 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005443 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005444 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005445
5446 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5447 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5448 // would be created and CXXConditionDeclExpr wants a VarDecl.
5449 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5450 << D.getSourceRange();
5451 return DeclResult();
5452 } else if (OwnedTag && OwnedTag->isDefinition()) {
5453 // The type-specifier-seq shall not declare a new class or enumeration.
5454 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5455 }
5456
5457 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5458 if (!Dcl)
5459 return DeclResult();
5460
5461 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5462 VD->setDeclaredInCondition(true);
5463 return Dcl;
5464}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005465
Anders Carlsson82fccd02009-12-07 08:24:59 +00005466void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5467 CXXMethodDecl *MD) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005468 // Ignore dependent types.
5469 if (MD->isDependentContext())
5470 return;
5471
5472 CXXRecordDecl *RD = MD->getParent();
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005473
5474 // Ignore classes without a vtable.
5475 if (!RD->isDynamicClass())
5476 return;
5477
Anders Carlsson82fccd02009-12-07 08:24:59 +00005478 if (!MD->isOutOfLine()) {
5479 // The only inline functions we care about are constructors. We also defer
5480 // marking the virtual members as referenced until we've reached the end
5481 // of the translation unit. We do this because we need to know the key
5482 // function of the class in order to determine the key function.
5483 if (isa<CXXConstructorDecl>(MD))
5484 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5485 return;
5486 }
5487
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005488 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005489
5490 if (!KeyFunction) {
5491 // This record does not have a key function, so we assume that the vtable
5492 // will be emitted when it's used by the constructor.
5493 if (!isa<CXXConstructorDecl>(MD))
5494 return;
5495 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5496 // We don't have the right key function.
5497 return;
5498 }
5499
Anders Carlsson82fccd02009-12-07 08:24:59 +00005500 // Mark the members as referenced.
5501 MarkVirtualMembersReferenced(Loc, RD);
5502 ClassesWithUnmarkedVirtualMembers.erase(RD);
5503}
5504
5505bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5506 if (ClassesWithUnmarkedVirtualMembers.empty())
5507 return false;
5508
5509 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5510 ClassesWithUnmarkedVirtualMembers.begin(),
5511 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5512 CXXRecordDecl *RD = i->first;
5513
5514 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5515 if (KeyFunction) {
5516 // We know that the class has a key function. If the key function was
5517 // declared in this translation unit, then it the class decl would not
5518 // have been in the ClassesWithUnmarkedVirtualMembers map.
5519 continue;
5520 }
5521
5522 SourceLocation Loc = i->second;
5523 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005524 }
5525
Anders Carlsson82fccd02009-12-07 08:24:59 +00005526 ClassesWithUnmarkedVirtualMembers.clear();
5527 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00005528}
Anders Carlsson82fccd02009-12-07 08:24:59 +00005529
5530void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5531 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5532 e = RD->method_end(); i != e; ++i) {
5533 CXXMethodDecl *MD = *i;
5534
5535 // C++ [basic.def.odr]p2:
5536 // [...] A virtual member function is used if it is not pure. [...]
5537 if (MD->isVirtual() && !MD->isPure())
5538 MarkDeclarationReferenced(Loc, MD);
5539 }
5540}
5541