blob: 0c0846071a88066a684982d2a24762a025444587 [file] [log] [blame]
Chris Lattner3d1cee32008-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 Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-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 Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000306 } else if (NewParam->hasDefaultArg()) {
307 if (New->getDescribedFunctionTemplate()) {
308 // Paragraph 4, quoted above, only applies to non-template functions.
309 Diag(NewParam->getLocation(),
310 diag::err_param_default_argument_template_redecl)
311 << NewParam->getDefaultArgRange();
312 Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000314 } else if (New->getTemplateSpecializationKind()
315 != TSK_ImplicitInstantiation &&
316 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 // C++ [temp.expr.spec]p21:
318 // Default function arguments shall not be specified in a declaration
319 // or a definition for one of the following explicit specializations:
320 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000321 // - the explicit specialization of a member function template;
322 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000323 // template where the class template specialization to which the
324 // member function specialization belongs is implicitly
325 // instantiated.
326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 << New->getDeclName()
329 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000330 } else if (New->getDeclContext()->isDependentContext()) {
331 // C++ [dcl.fct.default]p6 (DR217):
332 // Default arguments for a member function of a class template shall
333 // be specified on the initial declaration of the member function
334 // within the class template.
335 //
336 // Reading the tea leaves a bit in DR217 and its reference to DR205
337 // leads me to the conclusion that one cannot add default function
338 // arguments for an out-of-line definition of a member function of a
339 // dependent type.
340 int WhichKind = 2;
341 if (CXXRecordDecl *Record
342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343 if (Record->getDescribedClassTemplate())
344 WhichKind = 0;
345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 WhichKind = 1;
347 else
348 WhichKind = 2;
349 }
350
351 Diag(NewParam->getLocation(),
352 diag::err_param_default_argument_member_template_redecl)
353 << WhichKind
354 << NewParam->getDefaultArgRange();
355 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000356 }
357 }
358
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000359 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000361 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000363
Douglas Gregorcda9c672009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 else
Mike Stump1eb44332009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000420
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000429 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000430 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000431 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 } else
434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000436 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
Mike Stump1eb44332009-09-09 15:08:12 +0000442/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 SourceRange SpecifierRange,
449 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000450 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000451 SourceLocation BaseLoc) {
452 // C++ [class.union]p1:
453 // A union shall not have base classes.
454 if (Class->isUnion()) {
455 Diag(Class->getLocation(), diag::err_base_clause_on_union)
456 << SpecifierRange;
457 return 0;
458 }
459
460 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000462 Class->getTagKind() == RecordDecl::TK_class,
463 Access, BaseType);
464
465 // Base specifiers must be record types.
466 if (!BaseType->isRecordType()) {
467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.union]p1:
472 // A union shall not be used as a base class.
473 if (BaseType->isUnionType()) {
474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 return 0;
476 }
477
478 // C++ [class.derived]p2:
479 // The class-name in a base-specifier shall not be an incompletely
480 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000482 PDiag(diag::err_incomplete_base_class)
483 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000484 return 0;
485
Eli Friedman1d954f62009-08-15 21:55:26 +0000486 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000489 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000491 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
492 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000493
Sean Huntbbd37c62009-11-21 08:43:09 +0000494 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
495 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
496 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000497 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000499 return 0;
500 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000501
Eli Friedmand0137332009-12-05 23:03:49 +0000502 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000503
504 // Create the base specifier.
505 // FIXME: Allocate via ASTContext?
506 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
507 Class->getTagKind() == RecordDecl::TK_class,
508 Access, BaseType);
509}
510
511void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
512 const CXXRecordDecl *BaseClass,
513 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000514 // A class with a non-empty base class is not empty.
515 // FIXME: Standard ref?
516 if (!BaseClass->isEmpty())
517 Class->setEmpty(false);
518
519 // C++ [class.virtual]p1:
520 // A class that [...] inherits a virtual function is called a polymorphic
521 // class.
522 if (BaseClass->isPolymorphic())
523 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000524
Douglas Gregor2943aed2009-03-03 04:44:36 +0000525 // C++ [dcl.init.aggr]p1:
526 // An aggregate is [...] a class with [...] no base classes [...].
527 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000528
529 // C++ [class]p4:
530 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531 Class->setPOD(false);
532
Anders Carlsson51f94042009-12-03 17:49:57 +0000533 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000534 // C++ [class.ctor]p5:
535 // A constructor is trivial if its class has no virtual base classes.
536 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000537
538 // C++ [class.copy]p6:
539 // A copy constructor is trivial if its class has no virtual base classes.
540 Class->setHasTrivialCopyConstructor(false);
541
542 // C++ [class.copy]p11:
543 // A copy assignment operator is trivial if its class has no virtual
544 // base classes.
545 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000546
547 // C++0x [meta.unary.prop] is_empty:
548 // T is a class type, but not a union type, with ... no virtual base
549 // classes
550 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000551 } else {
552 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000554 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000555 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000556 Class->setHasTrivialConstructor(false);
557
558 // C++ [class.copy]p6:
559 // A copy constructor is trivial if all the direct base classes of its
560 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000561 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000562 Class->setHasTrivialCopyConstructor(false);
563
564 // C++ [class.copy]p11:
565 // A copy assignment operator is trivial if all the direct base classes
566 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000567 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000568 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000569 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000570
571 // C++ [class.ctor]p3:
572 // A destructor is trivial if all the direct base classes of its class
573 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000574 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000575 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576}
577
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000578/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
579/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000580/// example:
581/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000582/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000583Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000585 bool Virtual, AccessSpecifier Access,
586 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000587 if (!classdecl)
588 return true;
589
Douglas Gregor40808ce2009-03-09 23:48:35 +0000590 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000591 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000592 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
594 Virtual, Access,
595 BaseType, BaseLoc))
596 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000599}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601/// \brief Performs the actual work of attaching the given base class
602/// specifiers to a C++ class.
603bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
604 unsigned NumBases) {
605 if (NumBases == 0)
606 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000607
608 // Used to keep track of which base types we have already seen, so
609 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000610 // that the key is always the unqualified canonical type of the base
611 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000612 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
613
614 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000617 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000618 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000619 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000620 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000621
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000622 if (KnownBaseTypes[NewBaseType]) {
623 // C++ [class.mi]p3:
624 // A class shall not be specified as a direct base class of a
625 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000626 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000627 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000628 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000629 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000630
631 // Delete the duplicate base class specifier; we're going to
632 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000634
635 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000636 } else {
637 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 KnownBaseTypes[NewBaseType] = Bases[idx];
639 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000640 }
641 }
642
643 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000644 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000645
646 // Delete the remaining (good) base class specifiers, since their
647 // data has been copied into the CXXRecordDecl.
648 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000649 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000650
651 return Invalid;
652}
653
654/// ActOnBaseSpecifiers - Attach the given base specifiers to the
655/// class, after checking whether there are any duplicate base
656/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000657void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000658 unsigned NumBases) {
659 if (!ClassDecl || !Bases || !NumBases)
660 return;
661
662 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000664 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000665}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000666
Douglas Gregora8f32e02009-10-06 17:59:45 +0000667/// \brief Determine whether the type \p Derived is a C++ class that is
668/// derived from the type \p Base.
669bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
670 if (!getLangOptions().CPlusPlus)
671 return false;
672
673 const RecordType *DerivedRT = Derived->getAs<RecordType>();
674 if (!DerivedRT)
675 return false;
676
677 const RecordType *BaseRT = Base->getAs<RecordType>();
678 if (!BaseRT)
679 return false;
680
681 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
682 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall86ff3082010-02-04 22:26:26 +0000683 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
684 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000685}
686
687/// \brief Determine whether the type \p Derived is a C++ class that is
688/// derived from the type \p Base.
689bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
690 if (!getLangOptions().CPlusPlus)
691 return false;
692
693 const RecordType *DerivedRT = Derived->getAs<RecordType>();
694 if (!DerivedRT)
695 return false;
696
697 const RecordType *BaseRT = Base->getAs<RecordType>();
698 if (!BaseRT)
699 return false;
700
701 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
702 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
703 return DerivedRD->isDerivedFrom(BaseRD, Paths);
704}
705
706/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
707/// conversion (where Derived and Base are class types) is
708/// well-formed, meaning that the conversion is unambiguous (and
709/// that all of the base classes are accessible). Returns true
710/// and emits a diagnostic if the code is ill-formed, returns false
711/// otherwise. Loc is the location where this routine should point to
712/// if there is an error, and Range is the source range to highlight
713/// if there is an error.
714bool
715Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000716 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000717 unsigned AmbigiousBaseConvID,
718 SourceLocation Loc, SourceRange Range,
719 DeclarationName Name) {
720 // First, determine whether the path from Derived to Base is
721 // ambiguous. This is slightly more expensive than checking whether
722 // the Derived to Base conversion exists, because here we need to
723 // explore multiple paths to determine if there is an ambiguity.
724 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
725 /*DetectVirtual=*/false);
726 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
727 assert(DerivationOkay &&
728 "Can only be used with a derived-to-base conversion");
729 (void)DerivationOkay;
730
731 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000732 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000733 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000734
Douglas Gregora8f32e02009-10-06 17:59:45 +0000735 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000736 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
737 Base, Derived, Paths.front(),
738 /*force*/ false,
739 /*unprivileged*/ false,
740 ADK)) {
741 case AR_accessible: return false;
742 case AR_inaccessible: return true;
743 case AR_dependent: return false;
744 case AR_delayed: return false;
745 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000746 }
747
748 // We know that the derived-to-base conversion is ambiguous, and
749 // we're going to produce a diagnostic. Perform the derived-to-base
750 // search just one more time to compute all of the possible paths so
751 // that we can print them out. This is more expensive than any of
752 // the previous derived-to-base checks we've done, but at this point
753 // performance isn't as much of an issue.
754 Paths.clear();
755 Paths.setRecordingPaths(true);
756 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
757 assert(StillOkay && "Can only be used with a derived-to-base conversion");
758 (void)StillOkay;
759
760 // Build up a textual representation of the ambiguous paths, e.g.,
761 // D -> B -> A, that will be used to illustrate the ambiguous
762 // conversions in the diagnostic. We only print one of the paths
763 // to each base class subobject.
764 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
765
766 Diag(Loc, AmbigiousBaseConvID)
767 << Derived << Base << PathDisplayStr << Range << Name;
768 return true;
769}
770
771bool
772Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000773 SourceLocation Loc, SourceRange Range,
774 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000775 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000776 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000777 diag::err_ambiguous_derived_to_base_conv,
778 Loc, Range, DeclarationName());
779}
780
781
782/// @brief Builds a string representing ambiguous paths from a
783/// specific derived class to different subobjects of the same base
784/// class.
785///
786/// This function builds a string that can be used in error messages
787/// to show the different paths that one can take through the
788/// inheritance hierarchy to go from the derived class to different
789/// subobjects of a base class. The result looks something like this:
790/// @code
791/// struct D -> struct B -> struct A
792/// struct D -> struct C -> struct A
793/// @endcode
794std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
795 std::string PathDisplayStr;
796 std::set<unsigned> DisplayedPaths;
797 for (CXXBasePaths::paths_iterator Path = Paths.begin();
798 Path != Paths.end(); ++Path) {
799 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
800 // We haven't displayed a path to this particular base
801 // class subobject yet.
802 PathDisplayStr += "\n ";
803 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
804 for (CXXBasePath::const_iterator Element = Path->begin();
805 Element != Path->end(); ++Element)
806 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
807 }
808 }
809
810 return PathDisplayStr;
811}
812
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000813//===----------------------------------------------------------------------===//
814// C++ class member Handling
815//===----------------------------------------------------------------------===//
816
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000817/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
818/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
819/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000820/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000821Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000822Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000823 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000824 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
825 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000826 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000827 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000828 Expr *BitWidth = static_cast<Expr*>(BW);
829 Expr *Init = static_cast<Expr*>(InitExpr);
830 SourceLocation Loc = D.getIdentifierLoc();
831
Sebastian Redl669d5d72008-11-14 23:42:31 +0000832 bool isFunc = D.isFunctionDeclarator();
833
John McCall67d1a672009-08-06 02:15:43 +0000834 assert(!DS.isFriendSpecified());
835
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000836 // C++ 9.2p6: A member shall not be declared to have automatic storage
837 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000838 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
839 // data members and cannot be applied to names declared const or static,
840 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000841 switch (DS.getStorageClassSpec()) {
842 case DeclSpec::SCS_unspecified:
843 case DeclSpec::SCS_typedef:
844 case DeclSpec::SCS_static:
845 // FALL THROUGH.
846 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000847 case DeclSpec::SCS_mutable:
848 if (isFunc) {
849 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000850 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000851 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000852 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Sebastian Redla11f42f2008-11-17 23:24:37 +0000854 // FIXME: It would be nicer if the keyword was ignored only for this
855 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000856 D.getMutableDeclSpec().ClearStorageClassSpecs();
857 } else {
858 QualType T = GetTypeForDeclarator(D, S);
859 diag::kind err = static_cast<diag::kind>(0);
860 if (T->isReferenceType())
861 err = diag::err_mutable_reference;
862 else if (T.isConstQualified())
863 err = diag::err_mutable_const;
864 if (err != 0) {
865 if (DS.getStorageClassSpecLoc().isValid())
866 Diag(DS.getStorageClassSpecLoc(), err);
867 else
868 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000869 // FIXME: It would be nicer if the keyword was ignored only for this
870 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000871 D.getMutableDeclSpec().ClearStorageClassSpecs();
872 }
873 }
874 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000875 default:
876 if (DS.getStorageClassSpecLoc().isValid())
877 Diag(DS.getStorageClassSpecLoc(),
878 diag::err_storageclass_invalid_for_member);
879 else
880 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
881 D.getMutableDeclSpec().ClearStorageClassSpecs();
882 }
883
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000884 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000885 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000886 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000887 // Check also for this case:
888 //
889 // typedef int f();
890 // f a;
891 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000892 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000893 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000894 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000895
Sebastian Redl669d5d72008-11-14 23:42:31 +0000896 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
897 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000898 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000899
900 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000901 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000902 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000903 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
904 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000905 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000906 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000907 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000908 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000909 if (!Member) {
910 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000911 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000912 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000913
914 // Non-instance-fields can't have a bitfield.
915 if (BitWidth) {
916 if (Member->isInvalidDecl()) {
917 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000918 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000919 // C++ 9.6p3: A bit-field shall not be a static member.
920 // "static member 'A' cannot be a bit-field"
921 Diag(Loc, diag::err_static_not_bitfield)
922 << Name << BitWidth->getSourceRange();
923 } else if (isa<TypedefDecl>(Member)) {
924 // "typedef member 'x' cannot be a bit-field"
925 Diag(Loc, diag::err_typedef_not_bitfield)
926 << Name << BitWidth->getSourceRange();
927 } else {
928 // A function typedef ("typedef int f(); f a;").
929 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
930 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000931 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000932 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner8b963ef2009-03-05 23:01:03 +0000935 DeleteExpr(BitWidth);
936 BitWidth = 0;
937 Member->setInvalidDecl();
938 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000939
940 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Douglas Gregor37b372b2009-08-20 22:52:58 +0000942 // If we have declared a member function template, set the access of the
943 // templated declaration as well.
944 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
945 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000946 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947
Douglas Gregor10bd3682008-11-17 22:58:34 +0000948 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949
Douglas Gregor021c3b32009-03-11 23:00:04 +0000950 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000951 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000952 if (Deleted) // FIXME: Source location is not very good.
953 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000954
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000955 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000956 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000957 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000958 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000959 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000960}
961
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000962/// \brief Find the direct and/or virtual base specifiers that
963/// correspond to the given base type, for use in base initialization
964/// within a constructor.
965static bool FindBaseInitializer(Sema &SemaRef,
966 CXXRecordDecl *ClassDecl,
967 QualType BaseType,
968 const CXXBaseSpecifier *&DirectBaseSpec,
969 const CXXBaseSpecifier *&VirtualBaseSpec) {
970 // First, check for a direct base class.
971 DirectBaseSpec = 0;
972 for (CXXRecordDecl::base_class_const_iterator Base
973 = ClassDecl->bases_begin();
974 Base != ClassDecl->bases_end(); ++Base) {
975 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
976 // We found a direct base of this type. That's what we're
977 // initializing.
978 DirectBaseSpec = &*Base;
979 break;
980 }
981 }
982
983 // Check for a virtual base class.
984 // FIXME: We might be able to short-circuit this if we know in advance that
985 // there are no virtual bases.
986 VirtualBaseSpec = 0;
987 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
988 // We haven't found a base yet; search the class hierarchy for a
989 // virtual base class.
990 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
991 /*DetectVirtual=*/false);
992 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
993 BaseType, Paths)) {
994 for (CXXBasePaths::paths_iterator Path = Paths.begin();
995 Path != Paths.end(); ++Path) {
996 if (Path->back().Base->isVirtual()) {
997 VirtualBaseSpec = Path->back().Base;
998 break;
999 }
1000 }
1001 }
1002 }
1003
1004 return DirectBaseSpec || VirtualBaseSpec;
1005}
1006
Douglas Gregor7ad83902008-11-05 04:29:56 +00001007/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001008Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001009Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001010 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001011 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001012 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001013 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001014 SourceLocation IdLoc,
1015 SourceLocation LParenLoc,
1016 ExprTy **Args, unsigned NumArgs,
1017 SourceLocation *CommaLocs,
1018 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001019 if (!ConstructorD)
1020 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001022 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001023
1024 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001025 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001026 if (!Constructor) {
1027 // The user wrote a constructor initializer on a function that is
1028 // not a C++ constructor. Ignore the error for now, because we may
1029 // have more member initializers coming; we'll diagnose it just
1030 // once in ActOnMemInitializers.
1031 return true;
1032 }
1033
1034 CXXRecordDecl *ClassDecl = Constructor->getParent();
1035
1036 // C++ [class.base.init]p2:
1037 // Names in a mem-initializer-id are looked up in the scope of the
1038 // constructor’s class and, if not found in that scope, are looked
1039 // up in the scope containing the constructor’s
1040 // definition. [Note: if the constructor’s class contains a member
1041 // with the same name as a direct or virtual base class of the
1042 // class, a mem-initializer-id naming the member or base class and
1043 // composed of a single identifier refers to the class member. A
1044 // mem-initializer-id for the hidden base class may be specified
1045 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001046 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001047 // Look for a member, first.
1048 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001049 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001050 = ClassDecl->lookup(MemberOrBase);
1051 if (Result.first != Result.second)
1052 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001053
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001054 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001055
Eli Friedman59c04372009-07-29 19:44:27 +00001056 if (Member)
1057 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001058 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001059 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001060 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001061 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001062 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001063
1064 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001065 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001066 } else {
1067 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1068 LookupParsedName(R, S, &SS);
1069
1070 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1071 if (!TyD) {
1072 if (R.isAmbiguous()) return true;
1073
Douglas Gregor7a886e12010-01-19 06:46:48 +00001074 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1075 bool NotUnknownSpecialization = false;
1076 DeclContext *DC = computeDeclContext(SS, false);
1077 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1078 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1079
1080 if (!NotUnknownSpecialization) {
1081 // When the scope specifier can refer to a member of an unknown
1082 // specialization, we take it as a type name.
1083 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1084 *MemberOrBase, SS.getRange());
1085 R.clear();
1086 }
1087 }
1088
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001089 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001090 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001091 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1092 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1093 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1094 // We have found a non-static data member with a similar
1095 // name to what was typed; complain and initialize that
1096 // member.
1097 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1098 << MemberOrBase << true << R.getLookupName()
1099 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1100 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001101 Diag(Member->getLocation(), diag::note_previous_decl)
1102 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001103
1104 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1105 LParenLoc, RParenLoc);
1106 }
1107 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1108 const CXXBaseSpecifier *DirectBaseSpec;
1109 const CXXBaseSpecifier *VirtualBaseSpec;
1110 if (FindBaseInitializer(*this, ClassDecl,
1111 Context.getTypeDeclType(Type),
1112 DirectBaseSpec, VirtualBaseSpec)) {
1113 // We have found a direct or virtual base class with a
1114 // similar name to what was typed; complain and initialize
1115 // that base class.
1116 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1117 << MemberOrBase << false << R.getLookupName()
1118 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1119 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001120
1121 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1122 : VirtualBaseSpec;
1123 Diag(BaseSpec->getSourceRange().getBegin(),
1124 diag::note_base_class_specified_here)
1125 << BaseSpec->getType()
1126 << BaseSpec->getSourceRange();
1127
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001128 TyD = Type;
1129 }
1130 }
1131 }
1132
Douglas Gregor7a886e12010-01-19 06:46:48 +00001133 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001134 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1135 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1136 return true;
1137 }
John McCall2b194412009-12-21 10:41:20 +00001138 }
1139
Douglas Gregor7a886e12010-01-19 06:46:48 +00001140 if (BaseType.isNull()) {
1141 BaseType = Context.getTypeDeclType(TyD);
1142 if (SS.isSet()) {
1143 NestedNameSpecifier *Qualifier =
1144 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001145
Douglas Gregor7a886e12010-01-19 06:46:48 +00001146 // FIXME: preserve source range information
1147 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1148 }
John McCall2b194412009-12-21 10:41:20 +00001149 }
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
John McCalla93c9342009-12-07 02:54:59 +00001152 if (!TInfo)
1153 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001154
John McCalla93c9342009-12-07 02:54:59 +00001155 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001156 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001157}
1158
John McCallb4190042009-11-04 23:02:40 +00001159/// Checks an initializer expression for use of uninitialized fields, such as
1160/// containing the field that is being initialized. Returns true if there is an
1161/// uninitialized field was used an updates the SourceLocation parameter; false
1162/// otherwise.
1163static bool InitExprContainsUninitializedFields(const Stmt* S,
1164 const FieldDecl* LhsField,
1165 SourceLocation* L) {
1166 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1167 if (ME) {
1168 const NamedDecl* RhsField = ME->getMemberDecl();
1169 if (RhsField == LhsField) {
1170 // Initializing a field with itself. Throw a warning.
1171 // But wait; there are exceptions!
1172 // Exception #1: The field may not belong to this record.
1173 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1174 const Expr* base = ME->getBase();
1175 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1176 // Even though the field matches, it does not belong to this record.
1177 return false;
1178 }
1179 // None of the exceptions triggered; return true to indicate an
1180 // uninitialized field was used.
1181 *L = ME->getMemberLoc();
1182 return true;
1183 }
1184 }
1185 bool found = false;
1186 for (Stmt::const_child_iterator it = S->child_begin();
1187 it != S->child_end() && found == false;
1188 ++it) {
1189 if (isa<CallExpr>(S)) {
1190 // Do not descend into function calls or constructors, as the use
1191 // of an uninitialized field may be valid. One would have to inspect
1192 // the contents of the function/ctor to determine if it is safe or not.
1193 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1194 // may be safe, depending on what the function/ctor does.
1195 continue;
1196 }
1197 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1198 }
1199 return found;
1200}
1201
Eli Friedman59c04372009-07-29 19:44:27 +00001202Sema::MemInitResult
1203Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1204 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001205 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001206 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001207 // Diagnose value-uses of fields to initialize themselves, e.g.
1208 // foo(foo)
1209 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001210 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001211 for (unsigned i = 0; i < NumArgs; ++i) {
1212 SourceLocation L;
1213 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1214 // FIXME: Return true in the case when other fields are used before being
1215 // uninitialized. For example, let this field be the i'th field. When
1216 // initializing the i'th field, throw a warning if any of the >= i'th
1217 // fields are used, as they are not yet initialized.
1218 // Right now we are only handling the case where the i'th field uses
1219 // itself in its initializer.
1220 Diag(L, diag::warn_field_is_uninit);
1221 }
1222 }
1223
Eli Friedman59c04372009-07-29 19:44:27 +00001224 bool HasDependentArg = false;
1225 for (unsigned i = 0; i < NumArgs; i++)
1226 HasDependentArg |= Args[i]->isTypeDependent();
1227
Eli Friedman59c04372009-07-29 19:44:27 +00001228 QualType FieldType = Member->getType();
1229 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1230 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001231 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001232 if (FieldType->isDependentType() || HasDependentArg) {
1233 // Can't check initialization for a member of dependent type or when
1234 // any of the arguments are type-dependent expressions.
1235 OwningExprResult Init
1236 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1237 RParenLoc));
1238
1239 // Erase any temporaries within this evaluation context; we're not
1240 // going to track them in the AST, since we'll be rebuilding the
1241 // ASTs during template instantiation.
1242 ExprTemporaries.erase(
1243 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1244 ExprTemporaries.end());
1245
1246 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1247 LParenLoc,
1248 Init.takeAs<Expr>(),
1249 RParenLoc);
1250
Douglas Gregor7ad83902008-11-05 04:29:56 +00001251 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001252
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001253 if (Member->isInvalidDecl())
1254 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001255
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001256 // Initialize the member.
1257 InitializedEntity MemberEntity =
1258 InitializedEntity::InitializeMember(Member, 0);
1259 InitializationKind Kind =
1260 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1261
1262 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1263
1264 OwningExprResult MemberInit =
1265 InitSeq.Perform(*this, MemberEntity, Kind,
1266 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1267 if (MemberInit.isInvalid())
1268 return true;
1269
1270 // C++0x [class.base.init]p7:
1271 // The initialization of each base and member constitutes a
1272 // full-expression.
1273 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1274 if (MemberInit.isInvalid())
1275 return true;
1276
1277 // If we are in a dependent context, template instantiation will
1278 // perform this type-checking again. Just save the arguments that we
1279 // received in a ParenListExpr.
1280 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1281 // of the information that we have about the member
1282 // initializer. However, deconstructing the ASTs is a dicey process,
1283 // and this approach is far more likely to get the corner cases right.
1284 if (CurContext->isDependentContext()) {
1285 // Bump the reference count of all of the arguments.
1286 for (unsigned I = 0; I != NumArgs; ++I)
1287 Args[I]->Retain();
1288
1289 OwningExprResult Init
1290 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1291 RParenLoc));
1292 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1293 LParenLoc,
1294 Init.takeAs<Expr>(),
1295 RParenLoc);
1296 }
1297
Douglas Gregor802ab452009-12-02 22:36:29 +00001298 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001299 LParenLoc,
1300 MemberInit.takeAs<Expr>(),
1301 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001302}
1303
1304Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001305Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001306 Expr **Args, unsigned NumArgs,
1307 SourceLocation LParenLoc, SourceLocation RParenLoc,
1308 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001309 bool HasDependentArg = false;
1310 for (unsigned i = 0; i < NumArgs; i++)
1311 HasDependentArg |= Args[i]->isTypeDependent();
1312
John McCalla93c9342009-12-07 02:54:59 +00001313 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001314 if (BaseType->isDependentType() || HasDependentArg) {
1315 // Can't check initialization for a base of dependent type or when
1316 // any of the arguments are type-dependent expressions.
1317 OwningExprResult BaseInit
1318 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1319 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001320
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001321 // Erase any temporaries within this evaluation context; we're not
1322 // going to track them in the AST, since we'll be rebuilding the
1323 // ASTs during template instantiation.
1324 ExprTemporaries.erase(
1325 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1326 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001328 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1329 LParenLoc,
1330 BaseInit.takeAs<Expr>(),
1331 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001332 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001333
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001334 if (!BaseType->isRecordType())
1335 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1336 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1337
1338 // C++ [class.base.init]p2:
1339 // [...] Unless the mem-initializer-id names a nonstatic data
1340 // member of the constructor’s class or a direct or virtual base
1341 // of that class, the mem-initializer is ill-formed. A
1342 // mem-initializer-list can initialize a base class using any
1343 // name that denotes that base class type.
1344
1345 // Check for direct and virtual base classes.
1346 const CXXBaseSpecifier *DirectBaseSpec = 0;
1347 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1348 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1349 VirtualBaseSpec);
1350
1351 // C++ [base.class.init]p2:
1352 // If a mem-initializer-id is ambiguous because it designates both
1353 // a direct non-virtual base class and an inherited virtual base
1354 // class, the mem-initializer is ill-formed.
1355 if (DirectBaseSpec && VirtualBaseSpec)
1356 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1357 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1358 // C++ [base.class.init]p2:
1359 // Unless the mem-initializer-id names a nonstatic data membeer of the
1360 // constructor's class ot a direst or virtual base of that class, the
1361 // mem-initializer is ill-formed.
1362 if (!DirectBaseSpec && !VirtualBaseSpec)
1363 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1364 << BaseType << ClassDecl->getNameAsCString()
1365 << BaseTInfo->getTypeLoc().getSourceRange();
1366
1367 CXXBaseSpecifier *BaseSpec
1368 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1369 if (!BaseSpec)
1370 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1371
1372 // Initialize the base.
1373 InitializedEntity BaseEntity =
1374 InitializedEntity::InitializeBase(Context, BaseSpec);
1375 InitializationKind Kind =
1376 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1377
1378 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1379
1380 OwningExprResult BaseInit =
1381 InitSeq.Perform(*this, BaseEntity, Kind,
1382 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1383 if (BaseInit.isInvalid())
1384 return true;
1385
1386 // C++0x [class.base.init]p7:
1387 // The initialization of each base and member constitutes a
1388 // full-expression.
1389 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1390 if (BaseInit.isInvalid())
1391 return true;
1392
1393 // If we are in a dependent context, template instantiation will
1394 // perform this type-checking again. Just save the arguments that we
1395 // received in a ParenListExpr.
1396 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1397 // of the information that we have about the base
1398 // initializer. However, deconstructing the ASTs is a dicey process,
1399 // and this approach is far more likely to get the corner cases right.
1400 if (CurContext->isDependentContext()) {
1401 // Bump the reference count of all of the arguments.
1402 for (unsigned I = 0; I != NumArgs; ++I)
1403 Args[I]->Retain();
1404
1405 OwningExprResult Init
1406 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1407 RParenLoc));
1408 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1409 LParenLoc,
1410 Init.takeAs<Expr>(),
1411 RParenLoc);
1412 }
1413
1414 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1415 LParenLoc,
1416 BaseInit.takeAs<Expr>(),
1417 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001418}
1419
Eli Friedman80c30da2009-11-09 19:20:36 +00001420bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001421Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001422 CXXBaseOrMemberInitializer **Initializers,
1423 unsigned NumInitializers,
1424 bool IsImplicitConstructor,
1425 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001426 // We need to build the initializer AST according to order of construction
1427 // and not what user specified in the Initializers list.
1428 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1429 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1430 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1431 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001432 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001434 for (unsigned i = 0; i < NumInitializers; i++) {
1435 CXXBaseOrMemberInitializer *Member = Initializers[i];
1436 if (Member->isBaseInitializer()) {
1437 if (Member->getBaseClass()->isDependentType())
1438 HasDependentBaseInit = true;
1439 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1440 } else {
1441 AllBaseFields[Member->getMember()] = Member;
1442 }
1443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001445 if (HasDependentBaseInit) {
1446 // FIXME. This does not preserve the ordering of the initializers.
1447 // Try (with -Wreorder)
1448 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001449 // template<class X> struct B : A<X> {
1450 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001451 // int x1;
1452 // };
1453 // B<int> x;
1454 // On seeing one dependent type, we should essentially exit this routine
1455 // while preserving user-declared initializer list. When this routine is
1456 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001457 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001459 // If we have a dependent base initialization, we can't determine the
1460 // association between initializers and bases; just dump the known
1461 // initializers into the list, and don't try to deal with other bases.
1462 for (unsigned i = 0; i < NumInitializers; i++) {
1463 CXXBaseOrMemberInitializer *Member = Initializers[i];
1464 if (Member->isBaseInitializer())
1465 AllToInit.push_back(Member);
1466 }
1467 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001468 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1469
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001470 // Push virtual bases before others.
1471 for (CXXRecordDecl::base_class_iterator VBase =
1472 ClassDecl->vbases_begin(),
1473 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1474 if (VBase->getType()->isDependentType())
1475 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001476 if (CXXBaseOrMemberInitializer *Value
1477 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001478 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001479 } else if (!AnyErrors) {
1480 InitializedEntity InitEntity
1481 = InitializedEntity::InitializeBase(Context, VBase);
1482 InitializationKind InitKind
1483 = InitializationKind::CreateDefault(Constructor->getLocation());
1484 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1485 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1486 MultiExprArg(*this, 0, 0));
1487 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1488 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001489 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001490 continue;
1491 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001492
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001493 // Don't attach synthesized base initializers in a dependent
1494 // context; they'll be checked again at template instantiation
1495 // time.
1496 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001497 continue;
1498
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001499 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001500 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001501 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001502 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001503 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001504 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001505 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001506 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001507 }
1508 }
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001510 for (CXXRecordDecl::base_class_iterator Base =
1511 ClassDecl->bases_begin(),
1512 E = ClassDecl->bases_end(); Base != E; ++Base) {
1513 // Virtuals are in the virtual base list and already constructed.
1514 if (Base->isVirtual())
1515 continue;
1516 // Skip dependent types.
1517 if (Base->getType()->isDependentType())
1518 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001519 if (CXXBaseOrMemberInitializer *Value
1520 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001521 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001522 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001523 else if (!AnyErrors) {
1524 InitializedEntity InitEntity
1525 = InitializedEntity::InitializeBase(Context, Base);
1526 InitializationKind InitKind
1527 = InitializationKind::CreateDefault(Constructor->getLocation());
1528 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1529 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1530 MultiExprArg(*this, 0, 0));
1531 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1532 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001533 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001534 continue;
1535 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001536
1537 // Don't attach synthesized base initializers in a dependent
1538 // context; they'll be regenerated at template instantiation
1539 // time.
1540 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001541 continue;
1542
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001543 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001544 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001545 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001546 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001547 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001548 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001549 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001550 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001551 }
1552 }
1553 }
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001555 // non-static data members.
1556 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1557 E = ClassDecl->field_end(); Field != E; ++Field) {
1558 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001559 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001560 Field->getType()->getAs<RecordType>()) {
1561 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001562 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001563 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001564 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1565 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1566 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1567 // set to the anonymous union data member used in the initializer
1568 // list.
1569 Value->setMember(*Field);
1570 Value->setAnonUnionMember(*FA);
1571 AllToInit.push_back(Value);
1572 break;
1573 }
1574 }
1575 }
1576 continue;
1577 }
1578 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1579 AllToInit.push_back(Value);
1580 continue;
1581 }
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001583 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001584 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001585
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001586 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001587 if (FT->getAs<RecordType>()) {
1588 InitializedEntity InitEntity
1589 = InitializedEntity::InitializeMember(*Field);
1590 InitializationKind InitKind
1591 = InitializationKind::CreateDefault(Constructor->getLocation());
1592
1593 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1594 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1595 MultiExprArg(*this, 0, 0));
1596 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1597 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001598 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001599 continue;
1600 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001601
1602 // Don't attach synthesized member initializers in a dependent
1603 // context; they'll be regenerated a template instantiation
1604 // time.
1605 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001606 continue;
1607
Mike Stump1eb44332009-09-09 15:08:12 +00001608 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001609 new (Context) CXXBaseOrMemberInitializer(Context,
1610 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001611 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001612 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001613 SourceLocation());
1614
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001615 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001616 }
1617 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001618 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001619 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1620 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001621 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001622 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001623 }
1624 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001625 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001626 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1627 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001628 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001629 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001630 }
1631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001633 NumInitializers = AllToInit.size();
1634 if (NumInitializers > 0) {
1635 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1636 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1637 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001639 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1640 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1641 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1642 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001643
1644 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001645}
1646
Eli Friedman6347f422009-07-21 19:28:10 +00001647static void *GetKeyForTopLevelField(FieldDecl *Field) {
1648 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001649 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001650 if (RT->getDecl()->isAnonymousStructOrUnion())
1651 return static_cast<void *>(RT->getDecl());
1652 }
1653 return static_cast<void *>(Field);
1654}
1655
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001656static void *GetKeyForBase(QualType BaseType) {
1657 if (const RecordType *RT = BaseType->getAs<RecordType>())
1658 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001660 assert(0 && "Unexpected base type!");
1661 return 0;
1662}
1663
Mike Stump1eb44332009-09-09 15:08:12 +00001664static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001665 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001666 // For fields injected into the class via declaration of an anonymous union,
1667 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001668 if (Member->isMemberInitializer()) {
1669 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Eli Friedman49c16da2009-11-09 01:05:47 +00001671 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001672 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001673 // in AnonUnionMember field.
1674 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1675 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001676 if (Field->getDeclContext()->isRecord()) {
1677 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1678 if (RD->isAnonymousStructOrUnion())
1679 return static_cast<void *>(RD);
1680 }
1681 return static_cast<void *>(Field);
1682 }
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001684 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001685}
1686
John McCall6aee6212009-11-04 23:13:52 +00001687/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001688void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001689 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001690 MemInitTy **MemInits, unsigned NumMemInits,
1691 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001692 if (!ConstructorDecl)
1693 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001694
1695 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
1697 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001698 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Anders Carlssona7b35212009-03-25 02:58:17 +00001700 if (!Constructor) {
1701 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1702 return;
1703 }
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001705 if (!Constructor->isDependentContext()) {
1706 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1707 bool err = false;
1708 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001709 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001710 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1711 void *KeyToMember = GetKeyForMember(Member);
1712 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1713 if (!PrevMember) {
1714 PrevMember = Member;
1715 continue;
1716 }
1717 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001718 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001719 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001720 << Field->getNameAsString()
1721 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001722 else {
1723 Type *BaseClass = Member->getBaseClass();
1724 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001725 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001726 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001727 << QualType(BaseClass, 0)
1728 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001729 }
1730 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1731 << 0;
1732 err = true;
1733 }
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001735 if (err)
1736 return;
1737 }
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Eli Friedman49c16da2009-11-09 01:05:47 +00001739 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001740 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001741 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001743 if (Constructor->isDependentContext())
1744 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001745
1746 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001747 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001748 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001749 Diagnostic::Ignored)
1750 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001752 // Also issue warning if order of ctor-initializer list does not match order
1753 // of 1) base class declarations and 2) order of non-static data members.
1754 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001756 CXXRecordDecl *ClassDecl
1757 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1758 // Push virtual bases before others.
1759 for (CXXRecordDecl::base_class_iterator VBase =
1760 ClassDecl->vbases_begin(),
1761 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001762 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001764 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1765 E = ClassDecl->bases_end(); Base != E; ++Base) {
1766 // Virtuals are alread in the virtual base list and are constructed
1767 // first.
1768 if (Base->isVirtual())
1769 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001770 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001771 }
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1774 E = ClassDecl->field_end(); Field != E; ++Field)
1775 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001777 int Last = AllBaseOrMembers.size();
1778 int curIndex = 0;
1779 CXXBaseOrMemberInitializer *PrevMember = 0;
1780 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001781 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001782 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1783 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001784
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001785 for (; curIndex < Last; curIndex++)
1786 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1787 break;
1788 if (curIndex == Last) {
1789 assert(PrevMember && "Member not in member list?!");
1790 // Initializer as specified in ctor-initializer list is out of order.
1791 // Issue a warning diagnostic.
1792 if (PrevMember->isBaseInitializer()) {
1793 // Diagnostics is for an initialized base class.
1794 Type *BaseClass = PrevMember->getBaseClass();
1795 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001796 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001797 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001798 } else {
1799 FieldDecl *Field = PrevMember->getMember();
1800 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001801 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001802 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001803 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001804 // Also the note!
1805 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001806 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001807 diag::note_fieldorbase_initialized_here) << 0
1808 << Field->getNameAsString();
1809 else {
1810 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001811 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001812 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001813 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001814 }
1815 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001816 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001817 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001818 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001819 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001820 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001821}
1822
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001823void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001824Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1825 // Ignore dependent destructors.
1826 if (Destructor->isDependentContext())
1827 return;
1828
1829 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Anders Carlsson9f853df2009-11-17 04:44:12 +00001831 // Non-static data members.
1832 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1833 E = ClassDecl->field_end(); I != E; ++I) {
1834 FieldDecl *Field = *I;
1835
1836 QualType FieldType = Context.getBaseElementType(Field->getType());
1837
1838 const RecordType* RT = FieldType->getAs<RecordType>();
1839 if (!RT)
1840 continue;
1841
1842 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1843 if (FieldClassDecl->hasTrivialDestructor())
1844 continue;
1845
1846 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1847 MarkDeclarationReferenced(Destructor->getLocation(),
1848 const_cast<CXXDestructorDecl*>(Dtor));
1849 }
1850
1851 // Bases.
1852 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1853 E = ClassDecl->bases_end(); Base != E; ++Base) {
1854 // Ignore virtual bases.
1855 if (Base->isVirtual())
1856 continue;
1857
1858 // Ignore trivial destructors.
1859 CXXRecordDecl *BaseClassDecl
1860 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1861 if (BaseClassDecl->hasTrivialDestructor())
1862 continue;
1863
1864 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1865 MarkDeclarationReferenced(Destructor->getLocation(),
1866 const_cast<CXXDestructorDecl*>(Dtor));
1867 }
1868
1869 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001870 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1871 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001872 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001873 CXXRecordDecl *BaseClassDecl
1874 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1875 if (BaseClassDecl->hasTrivialDestructor())
1876 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001877
1878 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1879 MarkDeclarationReferenced(Destructor->getLocation(),
1880 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001881 }
1882}
1883
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001884void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001885 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001886 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001888 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001889
1890 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001891 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001892 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001893}
1894
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001895namespace {
1896 /// PureVirtualMethodCollector - traverses a class and its superclasses
1897 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001898 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001899 ASTContext &Context;
1900
Sebastian Redldfe292d2009-03-22 21:28:55 +00001901 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001902 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001903
1904 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001905 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001907 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001909 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001910 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001911 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001913 MethodList List;
1914 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001916 // Copy the temporary list to methods, and make sure to ignore any
1917 // null entries.
1918 for (size_t i = 0, e = List.size(); i != e; ++i) {
1919 if (List[i])
1920 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001921 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001922 }
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001924 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001926 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1927 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001928 };
Mike Stump1eb44332009-09-09 15:08:12 +00001929
1930 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001931 MethodList& Methods) {
1932 // First, collect the pure virtual methods for the base classes.
1933 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1934 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001935 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001936 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001937 if (BaseDecl && BaseDecl->isAbstract())
1938 Collect(BaseDecl, Methods);
1939 }
1940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001942 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001943 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001945 MethodSetTy OverriddenMethods;
1946 size_t MethodsSize = Methods.size();
1947
Mike Stump1eb44332009-09-09 15:08:12 +00001948 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001949 i != e; ++i) {
1950 // Traverse the record, looking for methods.
1951 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001952 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001953 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001954 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Anders Carlsson27823022009-10-18 19:34:08 +00001956 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001957 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1958 E = MD->end_overridden_methods(); I != E; ++I) {
1959 // Keep track of the overridden methods.
1960 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001961 }
1962 }
1963 }
Mike Stump1eb44332009-09-09 15:08:12 +00001964
1965 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001966 // overridden.
1967 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1968 if (OverriddenMethods.count(Methods[i]))
1969 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001970 }
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001972 }
1973}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001974
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001975
Mike Stump1eb44332009-09-09 15:08:12 +00001976bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001977 unsigned DiagID, AbstractDiagSelID SelID,
1978 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001979 if (SelID == -1)
1980 return RequireNonAbstractType(Loc, T,
1981 PDiag(DiagID), CurrentRD);
1982 else
1983 return RequireNonAbstractType(Loc, T,
1984 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001985}
1986
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001987bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1988 const PartialDiagnostic &PD,
1989 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001990 if (!getLangOptions().CPlusPlus)
1991 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Anders Carlsson11f21a02009-03-23 19:10:31 +00001993 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001994 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001995 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Ted Kremenek6217b802009-07-29 21:53:49 +00001997 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001998 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001999 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002000 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002002 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002003 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002004 }
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Ted Kremenek6217b802009-07-29 21:53:49 +00002006 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002007 if (!RT)
2008 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John McCall86ff3082010-02-04 22:26:26 +00002010 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002011
Anders Carlssone65a3c82009-03-24 17:23:42 +00002012 if (CurrentRD && CurrentRD != RD)
2013 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
John McCall86ff3082010-02-04 22:26:26 +00002015 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002016 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002017 return false;
2018
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002019 if (!RD->isAbstract())
2020 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002022 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002024 // Check if we've already emitted the list of pure virtual functions for this
2025 // class.
2026 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2027 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002029 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
2031 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002032 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2033 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002034
2035 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002036 MD->getDeclName();
2037 }
2038
2039 if (!PureVirtualClassDiagSet)
2040 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2041 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002043 return true;
2044}
2045
Anders Carlsson8211eff2009-03-24 01:19:16 +00002046namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002047 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002048 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2049 Sema &SemaRef;
2050 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Anders Carlssone65a3c82009-03-24 17:23:42 +00002052 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002053 bool Invalid = false;
2054
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002055 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2056 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002057 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002058
Anders Carlsson8211eff2009-03-24 01:19:16 +00002059 return Invalid;
2060 }
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Anders Carlssone65a3c82009-03-24 17:23:42 +00002062 public:
2063 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2064 : SemaRef(SemaRef), AbstractClass(ac) {
2065 Visit(SemaRef.Context.getTranslationUnitDecl());
2066 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002067
Anders Carlssone65a3c82009-03-24 17:23:42 +00002068 bool VisitFunctionDecl(const FunctionDecl *FD) {
2069 if (FD->isThisDeclarationADefinition()) {
2070 // No need to do the check if we're in a definition, because it requires
2071 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002072 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002073 return VisitDeclContext(FD);
2074 }
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Anders Carlssone65a3c82009-03-24 17:23:42 +00002076 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002077 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002078 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002079 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2080 diag::err_abstract_type_in_decl,
2081 Sema::AbstractReturnType,
2082 AbstractClass);
2083
Mike Stump1eb44332009-09-09 15:08:12 +00002084 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002085 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002086 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002087 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002088 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002089 VD->getOriginalType(),
2090 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002091 Sema::AbstractParamType,
2092 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002093 }
2094
2095 return Invalid;
2096 }
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Anders Carlssone65a3c82009-03-24 17:23:42 +00002098 bool VisitDecl(const Decl* D) {
2099 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2100 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Anders Carlssone65a3c82009-03-24 17:23:42 +00002102 return false;
2103 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002104 };
2105}
2106
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002107/// \brief Perform semantic checks on a class definition that has been
2108/// completing, introducing implicitly-declared members, checking for
2109/// abstract types, etc.
2110void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2111 if (!Record || Record->isInvalidDecl())
2112 return;
2113
Eli Friedmanff2d8782009-12-16 20:00:27 +00002114 if (!Record->isDependentType())
2115 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002116
Eli Friedmanff2d8782009-12-16 20:00:27 +00002117 if (Record->isInvalidDecl())
2118 return;
2119
John McCall233a6412010-01-28 07:38:46 +00002120 // Set access bits correctly on the directly-declared conversions.
2121 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2122 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2123 Convs->setAccess(I, (*I)->getAccess());
2124
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002125 if (!Record->isAbstract()) {
2126 // Collect all the pure virtual methods and see if this is an abstract
2127 // class after all.
2128 PureVirtualMethodCollector Collector(Context, Record);
2129 if (!Collector.empty())
2130 Record->setAbstract(true);
2131 }
2132
2133 if (Record->isAbstract())
2134 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002135}
2136
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002137void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002138 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002139 SourceLocation LBrac,
2140 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002141 if (!TagDecl)
2142 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Douglas Gregor42af25f2009-05-11 19:58:34 +00002144 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002145
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002146 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002147 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002148 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002149
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002150 CheckCompletedCXXClass(
2151 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002152}
2153
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002154/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2155/// special functions, such as the default constructor, copy
2156/// constructor, or destructor, to the given C++ class (C++
2157/// [special]p1). This routine can only be executed just before the
2158/// definition of the class is complete.
2159void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002160 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002161 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002162
Sebastian Redl465226e2009-05-27 22:11:52 +00002163 // FIXME: Implicit declarations have exception specifications, which are
2164 // the union of the specifications of the implicitly called functions.
2165
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002166 if (!ClassDecl->hasUserDeclaredConstructor()) {
2167 // C++ [class.ctor]p5:
2168 // A default constructor for a class X is a constructor of class X
2169 // that can be called without an argument. If there is no
2170 // user-declared constructor for class X, a default constructor is
2171 // implicitly declared. An implicitly-declared default constructor
2172 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002173 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002174 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002175 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002176 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002177 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002178 Context.getFunctionType(Context.VoidTy,
2179 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002180 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002181 /*isExplicit=*/false,
2182 /*isInline=*/true,
2183 /*isImplicitlyDeclared=*/true);
2184 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002185 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002186 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002187 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002188 }
2189
2190 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2191 // C++ [class.copy]p4:
2192 // If the class definition does not explicitly declare a copy
2193 // constructor, one is declared implicitly.
2194
2195 // C++ [class.copy]p5:
2196 // The implicitly-declared copy constructor for a class X will
2197 // have the form
2198 //
2199 // X::X(const X&)
2200 //
2201 // if
2202 bool HasConstCopyConstructor = true;
2203
2204 // -- each direct or virtual base class B of X has a copy
2205 // constructor whose first parameter is of type const B& or
2206 // const volatile B&, and
2207 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2208 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2209 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002210 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002211 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002212 = BaseClassDecl->hasConstCopyConstructor(Context);
2213 }
2214
2215 // -- for all the nonstatic data members of X that are of a
2216 // class type M (or array thereof), each such class type
2217 // has a copy constructor whose first parameter is of type
2218 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002219 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2220 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002221 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002222 QualType FieldType = (*Field)->getType();
2223 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2224 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002225 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002226 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002227 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002228 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002229 = FieldClassDecl->hasConstCopyConstructor(Context);
2230 }
2231 }
2232
Sebastian Redl64b45f72009-01-05 20:52:13 +00002233 // Otherwise, the implicitly declared copy constructor will have
2234 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002235 //
2236 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002237 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002238 if (HasConstCopyConstructor)
2239 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002240 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002241
Sebastian Redl64b45f72009-01-05 20:52:13 +00002242 // An implicitly-declared copy constructor is an inline public
2243 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002244 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002245 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002246 CXXConstructorDecl *CopyConstructor
2247 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002248 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002249 Context.getFunctionType(Context.VoidTy,
2250 &ArgType, 1,
2251 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002252 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002253 /*isExplicit=*/false,
2254 /*isInline=*/true,
2255 /*isImplicitlyDeclared=*/true);
2256 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002257 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002258 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002259
2260 // Add the parameter to the constructor.
2261 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2262 ClassDecl->getLocation(),
2263 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002264 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002265 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002266 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002267 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002268 }
2269
Sebastian Redl64b45f72009-01-05 20:52:13 +00002270 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2271 // Note: The following rules are largely analoguous to the copy
2272 // constructor rules. Note that virtual bases are not taken into account
2273 // for determining the argument type of the operator. Note also that
2274 // operators taking an object instead of a reference are allowed.
2275 //
2276 // C++ [class.copy]p10:
2277 // If the class definition does not explicitly declare a copy
2278 // assignment operator, one is declared implicitly.
2279 // The implicitly-defined copy assignment operator for a class X
2280 // will have the form
2281 //
2282 // X& X::operator=(const X&)
2283 //
2284 // if
2285 bool HasConstCopyAssignment = true;
2286
2287 // -- each direct base class B of X has a copy assignment operator
2288 // whose parameter is of type const B&, const volatile B& or B,
2289 // and
2290 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2291 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002292 assert(!Base->getType()->isDependentType() &&
2293 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002294 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002295 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002296 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002297 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002298 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002299 }
2300
2301 // -- for all the nonstatic data members of X that are of a class
2302 // type M (or array thereof), each such class type has a copy
2303 // assignment operator whose parameter is of type const M&,
2304 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002305 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2306 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002307 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002308 QualType FieldType = (*Field)->getType();
2309 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2310 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002311 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002312 const CXXRecordDecl *FieldClassDecl
2313 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002314 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002315 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002316 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002317 }
2318 }
2319
2320 // Otherwise, the implicitly declared copy assignment operator will
2321 // have the form
2322 //
2323 // X& X::operator=(X&)
2324 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002325 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002326 if (HasConstCopyAssignment)
2327 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002328 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002329
2330 // An implicitly-declared copy assignment operator is an inline public
2331 // member of its class.
2332 DeclarationName Name =
2333 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2334 CXXMethodDecl *CopyAssignment =
2335 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2336 Context.getFunctionType(RetType, &ArgType, 1,
2337 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002338 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002339 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002340 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002341 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002342 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002343
2344 // Add the parameter to the operator.
2345 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2346 ClassDecl->getLocation(),
2347 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002348 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002349 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002350 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002351
2352 // Don't call addedAssignmentOperator. There is no way to distinguish an
2353 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002354 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002355 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002356 }
2357
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002358 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002359 // C++ [class.dtor]p2:
2360 // If a class has no user-declared destructor, a destructor is
2361 // declared implicitly. An implicitly-declared destructor is an
2362 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002363 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002364 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002365 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002366 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002367 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002368 Context.getFunctionType(Context.VoidTy,
2369 0, 0, false, 0),
2370 /*isInline=*/true,
2371 /*isImplicitlyDeclared=*/true);
2372 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002373 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002374 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002375 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002376
2377 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002378 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002379}
2380
Douglas Gregor6569d682009-05-27 23:11:45 +00002381void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002382 Decl *D = TemplateD.getAs<Decl>();
2383 if (!D)
2384 return;
2385
2386 TemplateParameterList *Params = 0;
2387 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2388 Params = Template->getTemplateParameters();
2389 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2390 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2391 Params = PartialSpec->getTemplateParameters();
2392 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002393 return;
2394
Douglas Gregor6569d682009-05-27 23:11:45 +00002395 for (TemplateParameterList::iterator Param = Params->begin(),
2396 ParamEnd = Params->end();
2397 Param != ParamEnd; ++Param) {
2398 NamedDecl *Named = cast<NamedDecl>(*Param);
2399 if (Named->getDeclName()) {
2400 S->AddDecl(DeclPtrTy::make(Named));
2401 IdResolver.AddDecl(Named);
2402 }
2403 }
2404}
2405
John McCall7a1dc562009-12-19 10:49:29 +00002406void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2407 if (!RecordD) return;
2408 AdjustDeclIfTemplate(RecordD);
2409 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2410 PushDeclContext(S, Record);
2411}
2412
2413void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2414 if (!RecordD) return;
2415 PopDeclContext();
2416}
2417
Douglas Gregor72b505b2008-12-16 21:30:33 +00002418/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2419/// parsing a top-level (non-nested) C++ class, and we are now
2420/// parsing those parts of the given Method declaration that could
2421/// not be parsed earlier (C++ [class.mem]p2), such as default
2422/// arguments. This action should enter the scope of the given
2423/// Method declaration as if we had just parsed the qualified method
2424/// name. However, it should not bring the parameters into scope;
2425/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002426void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002427}
2428
2429/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2430/// C++ method declaration. We're (re-)introducing the given
2431/// function parameter into scope for use in parsing later parts of
2432/// the method declaration. For example, we could see an
2433/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002434void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002435 if (!ParamD)
2436 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Chris Lattnerb28317a2009-03-28 19:18:32 +00002438 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002439
2440 // If this parameter has an unparsed default argument, clear it out
2441 // to make way for the parsed default argument.
2442 if (Param->hasUnparsedDefaultArg())
2443 Param->setDefaultArg(0);
2444
Chris Lattnerb28317a2009-03-28 19:18:32 +00002445 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002446 if (Param->getDeclName())
2447 IdResolver.AddDecl(Param);
2448}
2449
2450/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2451/// processing the delayed method declaration for Method. The method
2452/// declaration is now considered finished. There may be a separate
2453/// ActOnStartOfFunctionDef action later (not necessarily
2454/// immediately!) for this method, if it was also defined inside the
2455/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002456void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002457 if (!MethodD)
2458 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002460 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Chris Lattnerb28317a2009-03-28 19:18:32 +00002462 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002463
2464 // Now that we have our default arguments, check the constructor
2465 // again. It could produce additional diagnostics or affect whether
2466 // the class has implicitly-declared destructors, among other
2467 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002468 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2469 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002470
2471 // Check the default arguments, which we may have added.
2472 if (!Method->isInvalidDecl())
2473 CheckCXXDefaultArguments(Method);
2474}
2475
Douglas Gregor42a552f2008-11-05 20:51:48 +00002476/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002477/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002478/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002479/// emit diagnostics and set the invalid bit to true. In any case, the type
2480/// will be updated to reflect a well-formed type for the constructor and
2481/// returned.
2482QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2483 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002484 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002485
2486 // C++ [class.ctor]p3:
2487 // A constructor shall not be virtual (10.3) or static (9.4). A
2488 // constructor can be invoked for a const, volatile or const
2489 // volatile object. A constructor shall not be declared const,
2490 // volatile, or const volatile (9.3.2).
2491 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002492 if (!D.isInvalidType())
2493 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2494 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2495 << SourceRange(D.getIdentifierLoc());
2496 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002497 }
2498 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002499 if (!D.isInvalidType())
2500 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2501 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2502 << SourceRange(D.getIdentifierLoc());
2503 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002504 SC = FunctionDecl::None;
2505 }
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Chris Lattner65401802009-04-25 08:28:21 +00002507 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2508 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002509 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002510 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2511 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002512 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002513 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2514 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002515 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002516 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2517 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002518 }
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Douglas Gregor42a552f2008-11-05 20:51:48 +00002520 // Rebuild the function type "R" without any type qualifiers (in
2521 // case any of the errors above fired) and with "void" as the
2522 // return type, since constructors don't have return types. We
2523 // *always* have to do this, because GetTypeForDeclarator will
2524 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002525 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002526 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2527 Proto->getNumArgs(),
2528 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002529}
2530
Douglas Gregor72b505b2008-12-16 21:30:33 +00002531/// CheckConstructor - Checks a fully-formed constructor for
2532/// well-formedness, issuing any diagnostics required. Returns true if
2533/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002534void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002535 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002536 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2537 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002538 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002539
2540 // C++ [class.copy]p3:
2541 // A declaration of a constructor for a class X is ill-formed if
2542 // its first parameter is of type (optionally cv-qualified) X and
2543 // either there are no other parameters or else all other
2544 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002545 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002546 ((Constructor->getNumParams() == 1) ||
2547 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002548 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2549 Constructor->getTemplateSpecializationKind()
2550 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002551 QualType ParamType = Constructor->getParamDecl(0)->getType();
2552 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2553 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002554 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2555 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002556 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002557
2558 // FIXME: Rather that making the constructor invalid, we should endeavor
2559 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002560 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002561 }
2562 }
Mike Stump1eb44332009-09-09 15:08:12 +00002563
Douglas Gregor72b505b2008-12-16 21:30:33 +00002564 // Notify the class that we've added a constructor.
2565 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002566}
2567
Anders Carlsson37909802009-11-30 21:24:50 +00002568/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2569/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002570bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002571 CXXRecordDecl *RD = Destructor->getParent();
2572
2573 if (Destructor->isVirtual()) {
2574 SourceLocation Loc;
2575
2576 if (!Destructor->isImplicit())
2577 Loc = Destructor->getLocation();
2578 else
2579 Loc = RD->getLocation();
2580
2581 // If we have a virtual destructor, look up the deallocation function
2582 FunctionDecl *OperatorDelete = 0;
2583 DeclarationName Name =
2584 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002585 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002586 return true;
2587
2588 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002589 }
Anders Carlsson37909802009-11-30 21:24:50 +00002590
2591 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002592}
2593
Mike Stump1eb44332009-09-09 15:08:12 +00002594static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002595FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2596 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2597 FTI.ArgInfo[0].Param &&
2598 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2599}
2600
Douglas Gregor42a552f2008-11-05 20:51:48 +00002601/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2602/// the well-formednes of the destructor declarator @p D with type @p
2603/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002604/// emit diagnostics and set the declarator to invalid. Even if this happens,
2605/// will be updated to reflect a well-formed type for the destructor and
2606/// returned.
2607QualType Sema::CheckDestructorDeclarator(Declarator &D,
2608 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002609 // C++ [class.dtor]p1:
2610 // [...] A typedef-name that names a class is a class-name
2611 // (7.1.3); however, a typedef-name that names a class shall not
2612 // be used as the identifier in the declarator for a destructor
2613 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002614 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002615 if (isa<TypedefType>(DeclaratorType)) {
2616 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002617 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002618 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002619 }
2620
2621 // C++ [class.dtor]p2:
2622 // A destructor is used to destroy objects of its class type. A
2623 // destructor takes no parameters, and no return type can be
2624 // specified for it (not even void). The address of a destructor
2625 // shall not be taken. A destructor shall not be static. A
2626 // destructor can be invoked for a const, volatile or const
2627 // volatile object. A destructor shall not be declared const,
2628 // volatile or const volatile (9.3.2).
2629 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002630 if (!D.isInvalidType())
2631 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2632 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2633 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002634 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002635 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002636 }
Chris Lattner65401802009-04-25 08:28:21 +00002637 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002638 // Destructors don't have return types, but the parser will
2639 // happily parse something like:
2640 //
2641 // class X {
2642 // float ~X();
2643 // };
2644 //
2645 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002646 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2647 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2648 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002649 }
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Chris Lattner65401802009-04-25 08:28:21 +00002651 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2652 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002653 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002654 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2655 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002656 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002657 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2658 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002659 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002660 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2661 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002662 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002663 }
2664
2665 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002666 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002667 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2668
2669 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002670 FTI.freeArgs();
2671 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002672 }
2673
Mike Stump1eb44332009-09-09 15:08:12 +00002674 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002675 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002676 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002677 D.setInvalidType();
2678 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002679
2680 // Rebuild the function type "R" without any type qualifiers or
2681 // parameters (in case any of the errors above fired) and with
2682 // "void" as the return type, since destructors don't have return
2683 // types. We *always* have to do this, because GetTypeForDeclarator
2684 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002685 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002686}
2687
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002688/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2689/// well-formednes of the conversion function declarator @p D with
2690/// type @p R. If there are any errors in the declarator, this routine
2691/// will emit diagnostics and return true. Otherwise, it will return
2692/// false. Either way, the type @p R will be updated to reflect a
2693/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002694void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002695 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002696 // C++ [class.conv.fct]p1:
2697 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002698 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002699 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002700 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002701 if (!D.isInvalidType())
2702 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2703 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2704 << SourceRange(D.getIdentifierLoc());
2705 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002706 SC = FunctionDecl::None;
2707 }
Chris Lattner6e475012009-04-25 08:35:12 +00002708 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002709 // Conversion functions don't have return types, but the parser will
2710 // happily parse something like:
2711 //
2712 // class X {
2713 // float operator bool();
2714 // };
2715 //
2716 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002717 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2718 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2719 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002720 }
2721
2722 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002723 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002724 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2725
2726 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002727 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002728 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002729 }
2730
Mike Stump1eb44332009-09-09 15:08:12 +00002731 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002732 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002733 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002734 D.setInvalidType();
2735 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002736
2737 // C++ [class.conv.fct]p4:
2738 // The conversion-type-id shall not represent a function type nor
2739 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002740 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002741 if (ConvType->isArrayType()) {
2742 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2743 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002744 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002745 } else if (ConvType->isFunctionType()) {
2746 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2747 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002748 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002749 }
2750
2751 // Rebuild the function type "R" without any parameters (in case any
2752 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002753 // return type.
2754 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002755 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002756
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002757 // C++0x explicit conversion operators.
2758 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002759 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002760 diag::warn_explicit_conversion_functions)
2761 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002762}
2763
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002764/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2765/// the declaration of the given C++ conversion function. This routine
2766/// is responsible for recording the conversion function in the C++
2767/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002768Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002769 assert(Conversion && "Expected to receive a conversion function declaration");
2770
Douglas Gregor9d350972008-12-12 08:25:50 +00002771 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002772
2773 // Make sure we aren't redeclaring the conversion function.
2774 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002775
2776 // C++ [class.conv.fct]p1:
2777 // [...] A conversion function is never used to convert a
2778 // (possibly cv-qualified) object to the (possibly cv-qualified)
2779 // same object type (or a reference to it), to a (possibly
2780 // cv-qualified) base class of that type (or a reference to it),
2781 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002782 // FIXME: Suppress this warning if the conversion function ends up being a
2783 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002784 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002785 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002786 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002787 ConvType = ConvTypeRef->getPointeeType();
2788 if (ConvType->isRecordType()) {
2789 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2790 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002791 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002792 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002793 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002794 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002795 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002796 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002797 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002798 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002799 }
2800
Douglas Gregor48026d22010-01-11 18:40:55 +00002801 if (Conversion->getPrimaryTemplate()) {
2802 // ignore specializations
2803 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002804 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002805 = Conversion->getDescribedFunctionTemplate()) {
2806 if (ClassDecl->replaceConversion(
2807 ConversionTemplate->getPreviousDeclaration(),
2808 ConversionTemplate))
2809 return DeclPtrTy::make(ConversionTemplate);
2810 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2811 Conversion))
John McCallba135432009-11-21 08:51:07 +00002812 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002813 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002814 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002815 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002816 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002817 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002818 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002819
Chris Lattnerb28317a2009-03-28 19:18:32 +00002820 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002821}
2822
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002823//===----------------------------------------------------------------------===//
2824// Namespace Handling
2825//===----------------------------------------------------------------------===//
2826
2827/// ActOnStartNamespaceDef - This is called at the start of a namespace
2828/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002829Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2830 SourceLocation IdentLoc,
2831 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002832 SourceLocation LBrace,
2833 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002834 NamespaceDecl *Namespc =
2835 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2836 Namespc->setLBracLoc(LBrace);
2837
2838 Scope *DeclRegionScope = NamespcScope->getParent();
2839
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002840 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2841
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002842 if (II) {
2843 // C++ [namespace.def]p2:
2844 // The identifier in an original-namespace-definition shall not have been
2845 // previously defined in the declarative region in which the
2846 // original-namespace-definition appears. The identifier in an
2847 // original-namespace-definition is the name of the namespace. Subsequently
2848 // in that declarative region, it is treated as an original-namespace-name.
2849
John McCallf36e02d2009-10-09 21:13:30 +00002850 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002851 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002852 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Douglas Gregor44b43212008-12-11 16:49:14 +00002854 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2855 // This is an extended namespace definition.
2856 // Attach this namespace decl to the chain of extended namespace
2857 // definitions.
2858 OrigNS->setNextNamespace(Namespc);
2859 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002860
Mike Stump1eb44332009-09-09 15:08:12 +00002861 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002862 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002863 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002864 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002865 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002866 } else if (PrevDecl) {
2867 // This is an invalid name redefinition.
2868 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2869 << Namespc->getDeclName();
2870 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2871 Namespc->setInvalidDecl();
2872 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002873 } else if (II->isStr("std") &&
2874 CurContext->getLookupContext()->isTranslationUnit()) {
2875 // This is the first "real" definition of the namespace "std", so update
2876 // our cache of the "std" namespace to point at this definition.
2877 if (StdNamespace) {
2878 // We had already defined a dummy namespace "std". Link this new
2879 // namespace definition to the dummy namespace "std".
2880 StdNamespace->setNextNamespace(Namespc);
2881 StdNamespace->setLocation(IdentLoc);
2882 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2883 }
2884
2885 // Make our StdNamespace cache point at the first real definition of the
2886 // "std" namespace.
2887 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002888 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002889
2890 PushOnScopeChains(Namespc, DeclRegionScope);
2891 } else {
John McCall9aeed322009-10-01 00:25:31 +00002892 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002893 assert(Namespc->isAnonymousNamespace());
2894 CurContext->addDecl(Namespc);
2895
2896 // Link the anonymous namespace into its parent.
2897 NamespaceDecl *PrevDecl;
2898 DeclContext *Parent = CurContext->getLookupContext();
2899 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2900 PrevDecl = TU->getAnonymousNamespace();
2901 TU->setAnonymousNamespace(Namespc);
2902 } else {
2903 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2904 PrevDecl = ND->getAnonymousNamespace();
2905 ND->setAnonymousNamespace(Namespc);
2906 }
2907
2908 // Link the anonymous namespace with its previous declaration.
2909 if (PrevDecl) {
2910 assert(PrevDecl->isAnonymousNamespace());
2911 assert(!PrevDecl->getNextNamespace());
2912 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2913 PrevDecl->setNextNamespace(Namespc);
2914 }
John McCall9aeed322009-10-01 00:25:31 +00002915
2916 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2917 // behaves as if it were replaced by
2918 // namespace unique { /* empty body */ }
2919 // using namespace unique;
2920 // namespace unique { namespace-body }
2921 // where all occurrences of 'unique' in a translation unit are
2922 // replaced by the same identifier and this identifier differs
2923 // from all other identifiers in the entire program.
2924
2925 // We just create the namespace with an empty name and then add an
2926 // implicit using declaration, just like the standard suggests.
2927 //
2928 // CodeGen enforces the "universally unique" aspect by giving all
2929 // declarations semantically contained within an anonymous
2930 // namespace internal linkage.
2931
John McCall5fdd7642009-12-16 02:06:49 +00002932 if (!PrevDecl) {
2933 UsingDirectiveDecl* UD
2934 = UsingDirectiveDecl::Create(Context, CurContext,
2935 /* 'using' */ LBrace,
2936 /* 'namespace' */ SourceLocation(),
2937 /* qualifier */ SourceRange(),
2938 /* NNS */ NULL,
2939 /* identifier */ SourceLocation(),
2940 Namespc,
2941 /* Ancestor */ CurContext);
2942 UD->setImplicit();
2943 CurContext->addDecl(UD);
2944 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002945 }
2946
2947 // Although we could have an invalid decl (i.e. the namespace name is a
2948 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002949 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2950 // for the namespace has the declarations that showed up in that particular
2951 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002952 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002953 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002954}
2955
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002956/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2957/// is a namespace alias, returns the namespace it points to.
2958static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2959 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2960 return AD->getNamespace();
2961 return dyn_cast_or_null<NamespaceDecl>(D);
2962}
2963
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002964/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2965/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002966void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2967 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002968 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2969 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2970 Namespc->setRBracLoc(RBrace);
2971 PopDeclContext();
2972}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002973
Chris Lattnerb28317a2009-03-28 19:18:32 +00002974Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2975 SourceLocation UsingLoc,
2976 SourceLocation NamespcLoc,
2977 const CXXScopeSpec &SS,
2978 SourceLocation IdentLoc,
2979 IdentifierInfo *NamespcName,
2980 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002981 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2982 assert(NamespcName && "Invalid NamespcName.");
2983 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002984 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002985
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002986 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002987
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002988 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002989 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2990 LookupParsedName(R, S, &SS);
2991 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002992 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002993
John McCallf36e02d2009-10-09 21:13:30 +00002994 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002995 NamedDecl *Named = R.getFoundDecl();
2996 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2997 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002998 // C++ [namespace.udir]p1:
2999 // A using-directive specifies that the names in the nominated
3000 // namespace can be used in the scope in which the
3001 // using-directive appears after the using-directive. During
3002 // unqualified name lookup (3.4.1), the names appear as if they
3003 // were declared in the nearest enclosing namespace which
3004 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003005 // namespace. [Note: in this context, "contains" means "contains
3006 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003007
3008 // Find enclosing context containing both using-directive and
3009 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003010 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003011 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3012 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3013 CommonAncestor = CommonAncestor->getParent();
3014
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003015 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003016 SS.getRange(),
3017 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003018 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003019 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003020 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003021 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003022 }
3023
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003024 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003025 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003026 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003027}
3028
3029void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3030 // If scope has associated entity, then using directive is at namespace
3031 // or translation unit scope. We add UsingDirectiveDecls, into
3032 // it's lookup structure.
3033 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003034 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003035 else
3036 // Otherwise it is block-sope. using-directives will affect lookup
3037 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003038 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003039}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003040
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003041
3042Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003043 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003044 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003045 SourceLocation UsingLoc,
3046 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003047 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003048 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003049 bool IsTypeName,
3050 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003051 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Douglas Gregor12c118a2009-11-04 16:30:06 +00003053 switch (Name.getKind()) {
3054 case UnqualifiedId::IK_Identifier:
3055 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003056 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003057 case UnqualifiedId::IK_ConversionFunctionId:
3058 break;
3059
3060 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003061 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003062 // C++0x inherited constructors.
3063 if (getLangOptions().CPlusPlus0x) break;
3064
Douglas Gregor12c118a2009-11-04 16:30:06 +00003065 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3066 << SS.getRange();
3067 return DeclPtrTy();
3068
3069 case UnqualifiedId::IK_DestructorName:
3070 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3071 << SS.getRange();
3072 return DeclPtrTy();
3073
3074 case UnqualifiedId::IK_TemplateId:
3075 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3076 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3077 return DeclPtrTy();
3078 }
3079
3080 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003081 if (!TargetName)
3082 return DeclPtrTy();
3083
John McCall60fa3cf2009-12-11 02:10:03 +00003084 // Warn about using declarations.
3085 // TODO: store that the declaration was written without 'using' and
3086 // talk about access decls instead of using decls in the
3087 // diagnostics.
3088 if (!HasUsingKeyword) {
3089 UsingLoc = Name.getSourceRange().getBegin();
3090
3091 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3092 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3093 "using ");
3094 }
3095
John McCall9488ea12009-11-17 05:59:44 +00003096 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003097 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003098 TargetName, AttrList,
3099 /* IsInstantiation */ false,
3100 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003101 if (UD)
3102 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003103
Anders Carlssonc72160b2009-08-28 05:40:36 +00003104 return DeclPtrTy::make(UD);
3105}
3106
John McCall9f54ad42009-12-10 09:41:52 +00003107/// Determines whether to create a using shadow decl for a particular
3108/// decl, given the set of decls existing prior to this using lookup.
3109bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3110 const LookupResult &Previous) {
3111 // Diagnose finding a decl which is not from a base class of the
3112 // current class. We do this now because there are cases where this
3113 // function will silently decide not to build a shadow decl, which
3114 // will pre-empt further diagnostics.
3115 //
3116 // We don't need to do this in C++0x because we do the check once on
3117 // the qualifier.
3118 //
3119 // FIXME: diagnose the following if we care enough:
3120 // struct A { int foo; };
3121 // struct B : A { using A::foo; };
3122 // template <class T> struct C : A {};
3123 // template <class T> struct D : C<T> { using B::foo; } // <---
3124 // This is invalid (during instantiation) in C++03 because B::foo
3125 // resolves to the using decl in B, which is not a base class of D<T>.
3126 // We can't diagnose it immediately because C<T> is an unknown
3127 // specialization. The UsingShadowDecl in D<T> then points directly
3128 // to A::foo, which will look well-formed when we instantiate.
3129 // The right solution is to not collapse the shadow-decl chain.
3130 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3131 DeclContext *OrigDC = Orig->getDeclContext();
3132
3133 // Handle enums and anonymous structs.
3134 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3135 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3136 while (OrigRec->isAnonymousStructOrUnion())
3137 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3138
3139 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3140 if (OrigDC == CurContext) {
3141 Diag(Using->getLocation(),
3142 diag::err_using_decl_nested_name_specifier_is_current_class)
3143 << Using->getNestedNameRange();
3144 Diag(Orig->getLocation(), diag::note_using_decl_target);
3145 return true;
3146 }
3147
3148 Diag(Using->getNestedNameRange().getBegin(),
3149 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3150 << Using->getTargetNestedNameDecl()
3151 << cast<CXXRecordDecl>(CurContext)
3152 << Using->getNestedNameRange();
3153 Diag(Orig->getLocation(), diag::note_using_decl_target);
3154 return true;
3155 }
3156 }
3157
3158 if (Previous.empty()) return false;
3159
3160 NamedDecl *Target = Orig;
3161 if (isa<UsingShadowDecl>(Target))
3162 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3163
John McCalld7533ec2009-12-11 02:33:26 +00003164 // If the target happens to be one of the previous declarations, we
3165 // don't have a conflict.
3166 //
3167 // FIXME: but we might be increasing its access, in which case we
3168 // should redeclare it.
3169 NamedDecl *NonTag = 0, *Tag = 0;
3170 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3171 I != E; ++I) {
3172 NamedDecl *D = (*I)->getUnderlyingDecl();
3173 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3174 return false;
3175
3176 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3177 }
3178
John McCall9f54ad42009-12-10 09:41:52 +00003179 if (Target->isFunctionOrFunctionTemplate()) {
3180 FunctionDecl *FD;
3181 if (isa<FunctionTemplateDecl>(Target))
3182 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3183 else
3184 FD = cast<FunctionDecl>(Target);
3185
3186 NamedDecl *OldDecl = 0;
3187 switch (CheckOverload(FD, Previous, OldDecl)) {
3188 case Ovl_Overload:
3189 return false;
3190
3191 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003192 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003193 break;
3194
3195 // We found a decl with the exact signature.
3196 case Ovl_Match:
3197 if (isa<UsingShadowDecl>(OldDecl)) {
3198 // Silently ignore the possible conflict.
3199 return false;
3200 }
3201
3202 // If we're in a record, we want to hide the target, so we
3203 // return true (without a diagnostic) to tell the caller not to
3204 // build a shadow decl.
3205 if (CurContext->isRecord())
3206 return true;
3207
3208 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003209 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003210 break;
3211 }
3212
3213 Diag(Target->getLocation(), diag::note_using_decl_target);
3214 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3215 return true;
3216 }
3217
3218 // Target is not a function.
3219
John McCall9f54ad42009-12-10 09:41:52 +00003220 if (isa<TagDecl>(Target)) {
3221 // No conflict between a tag and a non-tag.
3222 if (!Tag) return false;
3223
John McCall41ce66f2009-12-10 19:51:03 +00003224 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003225 Diag(Target->getLocation(), diag::note_using_decl_target);
3226 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3227 return true;
3228 }
3229
3230 // No conflict between a tag and a non-tag.
3231 if (!NonTag) return false;
3232
John McCall41ce66f2009-12-10 19:51:03 +00003233 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003234 Diag(Target->getLocation(), diag::note_using_decl_target);
3235 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3236 return true;
3237}
3238
John McCall9488ea12009-11-17 05:59:44 +00003239/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003240UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003241 UsingDecl *UD,
3242 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003243
3244 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003245 NamedDecl *Target = Orig;
3246 if (isa<UsingShadowDecl>(Target)) {
3247 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3248 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003249 }
3250
3251 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003252 = UsingShadowDecl::Create(Context, CurContext,
3253 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003254 UD->addShadowDecl(Shadow);
3255
3256 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003257 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003258 else
John McCall604e7f12009-12-08 07:46:18 +00003259 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003260 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003261
John McCall604e7f12009-12-08 07:46:18 +00003262 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3263 Shadow->setInvalidDecl();
3264
John McCall9f54ad42009-12-10 09:41:52 +00003265 return Shadow;
3266}
John McCall604e7f12009-12-08 07:46:18 +00003267
John McCall9f54ad42009-12-10 09:41:52 +00003268/// Hides a using shadow declaration. This is required by the current
3269/// using-decl implementation when a resolvable using declaration in a
3270/// class is followed by a declaration which would hide or override
3271/// one or more of the using decl's targets; for example:
3272///
3273/// struct Base { void foo(int); };
3274/// struct Derived : Base {
3275/// using Base::foo;
3276/// void foo(int);
3277/// };
3278///
3279/// The governing language is C++03 [namespace.udecl]p12:
3280///
3281/// When a using-declaration brings names from a base class into a
3282/// derived class scope, member functions in the derived class
3283/// override and/or hide member functions with the same name and
3284/// parameter types in a base class (rather than conflicting).
3285///
3286/// There are two ways to implement this:
3287/// (1) optimistically create shadow decls when they're not hidden
3288/// by existing declarations, or
3289/// (2) don't create any shadow decls (or at least don't make them
3290/// visible) until we've fully parsed/instantiated the class.
3291/// The problem with (1) is that we might have to retroactively remove
3292/// a shadow decl, which requires several O(n) operations because the
3293/// decl structures are (very reasonably) not designed for removal.
3294/// (2) avoids this but is very fiddly and phase-dependent.
3295void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3296 // Remove it from the DeclContext...
3297 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003298
John McCall9f54ad42009-12-10 09:41:52 +00003299 // ...and the scope, if applicable...
3300 if (S) {
3301 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3302 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003303 }
3304
John McCall9f54ad42009-12-10 09:41:52 +00003305 // ...and the using decl.
3306 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3307
3308 // TODO: complain somehow if Shadow was used. It shouldn't
3309 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003310}
3311
John McCall7ba107a2009-11-18 02:36:19 +00003312/// Builds a using declaration.
3313///
3314/// \param IsInstantiation - Whether this call arises from an
3315/// instantiation of an unresolved using declaration. We treat
3316/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003317NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3318 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003319 const CXXScopeSpec &SS,
3320 SourceLocation IdentLoc,
3321 DeclarationName Name,
3322 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003323 bool IsInstantiation,
3324 bool IsTypeName,
3325 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003326 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3327 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003328
Anders Carlsson550b14b2009-08-28 05:49:21 +00003329 // FIXME: We ignore attributes for now.
3330 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003332 if (SS.isEmpty()) {
3333 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003334 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003335 }
Mike Stump1eb44332009-09-09 15:08:12 +00003336
John McCall9f54ad42009-12-10 09:41:52 +00003337 // Do the redeclaration lookup in the current scope.
3338 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3339 ForRedeclaration);
3340 Previous.setHideTags(false);
3341 if (S) {
3342 LookupName(Previous, S);
3343
3344 // It is really dumb that we have to do this.
3345 LookupResult::Filter F = Previous.makeFilter();
3346 while (F.hasNext()) {
3347 NamedDecl *D = F.next();
3348 if (!isDeclInScope(D, CurContext, S))
3349 F.erase();
3350 }
3351 F.done();
3352 } else {
3353 assert(IsInstantiation && "no scope in non-instantiation");
3354 assert(CurContext->isRecord() && "scope not record in instantiation");
3355 LookupQualifiedName(Previous, CurContext);
3356 }
3357
Mike Stump1eb44332009-09-09 15:08:12 +00003358 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003359 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3360
John McCall9f54ad42009-12-10 09:41:52 +00003361 // Check for invalid redeclarations.
3362 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3363 return 0;
3364
3365 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003366 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3367 return 0;
3368
John McCallaf8e6ed2009-11-12 03:15:40 +00003369 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003370 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003371 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003372 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003373 // FIXME: not all declaration name kinds are legal here
3374 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3375 UsingLoc, TypenameLoc,
3376 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003377 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003378 } else {
3379 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3380 UsingLoc, SS.getRange(), NNS,
3381 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003382 }
John McCalled976492009-12-04 22:46:56 +00003383 } else {
3384 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3385 SS.getRange(), UsingLoc, NNS, Name,
3386 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003387 }
John McCalled976492009-12-04 22:46:56 +00003388 D->setAccess(AS);
3389 CurContext->addDecl(D);
3390
3391 if (!LookupContext) return D;
3392 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003393
John McCall604e7f12009-12-08 07:46:18 +00003394 if (RequireCompleteDeclContext(SS)) {
3395 UD->setInvalidDecl();
3396 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003397 }
3398
John McCall604e7f12009-12-08 07:46:18 +00003399 // Look up the target name.
3400
John McCalla24dc2e2009-11-17 02:14:36 +00003401 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003402
John McCall604e7f12009-12-08 07:46:18 +00003403 // Unlike most lookups, we don't always want to hide tag
3404 // declarations: tag names are visible through the using declaration
3405 // even if hidden by ordinary names, *except* in a dependent context
3406 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003407 if (!IsInstantiation)
3408 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003409
John McCalla24dc2e2009-11-17 02:14:36 +00003410 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003411
John McCallf36e02d2009-10-09 21:13:30 +00003412 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003413 Diag(IdentLoc, diag::err_no_member)
3414 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003415 UD->setInvalidDecl();
3416 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003417 }
3418
John McCalled976492009-12-04 22:46:56 +00003419 if (R.isAmbiguous()) {
3420 UD->setInvalidDecl();
3421 return UD;
3422 }
Mike Stump1eb44332009-09-09 15:08:12 +00003423
John McCall7ba107a2009-11-18 02:36:19 +00003424 if (IsTypeName) {
3425 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003426 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003427 Diag(IdentLoc, diag::err_using_typename_non_type);
3428 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3429 Diag((*I)->getUnderlyingDecl()->getLocation(),
3430 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003431 UD->setInvalidDecl();
3432 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003433 }
3434 } else {
3435 // If we asked for a non-typename and we got a type, error out,
3436 // but only if this is an instantiation of an unresolved using
3437 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003438 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003439 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3440 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003441 UD->setInvalidDecl();
3442 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003443 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003444 }
3445
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003446 // C++0x N2914 [namespace.udecl]p6:
3447 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003448 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003449 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3450 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003451 UD->setInvalidDecl();
3452 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003453 }
Mike Stump1eb44332009-09-09 15:08:12 +00003454
John McCall9f54ad42009-12-10 09:41:52 +00003455 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3456 if (!CheckUsingShadowDecl(UD, *I, Previous))
3457 BuildUsingShadowDecl(S, UD, *I);
3458 }
John McCall9488ea12009-11-17 05:59:44 +00003459
3460 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003461}
3462
John McCall9f54ad42009-12-10 09:41:52 +00003463/// Checks that the given using declaration is not an invalid
3464/// redeclaration. Note that this is checking only for the using decl
3465/// itself, not for any ill-formedness among the UsingShadowDecls.
3466bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3467 bool isTypeName,
3468 const CXXScopeSpec &SS,
3469 SourceLocation NameLoc,
3470 const LookupResult &Prev) {
3471 // C++03 [namespace.udecl]p8:
3472 // C++0x [namespace.udecl]p10:
3473 // A using-declaration is a declaration and can therefore be used
3474 // repeatedly where (and only where) multiple declarations are
3475 // allowed.
3476 // That's only in file contexts.
3477 if (CurContext->getLookupContext()->isFileContext())
3478 return false;
3479
3480 NestedNameSpecifier *Qual
3481 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3482
3483 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3484 NamedDecl *D = *I;
3485
3486 bool DTypename;
3487 NestedNameSpecifier *DQual;
3488 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3489 DTypename = UD->isTypeName();
3490 DQual = UD->getTargetNestedNameDecl();
3491 } else if (UnresolvedUsingValueDecl *UD
3492 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3493 DTypename = false;
3494 DQual = UD->getTargetNestedNameSpecifier();
3495 } else if (UnresolvedUsingTypenameDecl *UD
3496 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3497 DTypename = true;
3498 DQual = UD->getTargetNestedNameSpecifier();
3499 } else continue;
3500
3501 // using decls differ if one says 'typename' and the other doesn't.
3502 // FIXME: non-dependent using decls?
3503 if (isTypeName != DTypename) continue;
3504
3505 // using decls differ if they name different scopes (but note that
3506 // template instantiation can cause this check to trigger when it
3507 // didn't before instantiation).
3508 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3509 Context.getCanonicalNestedNameSpecifier(DQual))
3510 continue;
3511
3512 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003513 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003514 return true;
3515 }
3516
3517 return false;
3518}
3519
John McCall604e7f12009-12-08 07:46:18 +00003520
John McCalled976492009-12-04 22:46:56 +00003521/// Checks that the given nested-name qualifier used in a using decl
3522/// in the current context is appropriately related to the current
3523/// scope. If an error is found, diagnoses it and returns true.
3524bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3525 const CXXScopeSpec &SS,
3526 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003527 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003528
John McCall604e7f12009-12-08 07:46:18 +00003529 if (!CurContext->isRecord()) {
3530 // C++03 [namespace.udecl]p3:
3531 // C++0x [namespace.udecl]p8:
3532 // A using-declaration for a class member shall be a member-declaration.
3533
3534 // If we weren't able to compute a valid scope, it must be a
3535 // dependent class scope.
3536 if (!NamedContext || NamedContext->isRecord()) {
3537 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3538 << SS.getRange();
3539 return true;
3540 }
3541
3542 // Otherwise, everything is known to be fine.
3543 return false;
3544 }
3545
3546 // The current scope is a record.
3547
3548 // If the named context is dependent, we can't decide much.
3549 if (!NamedContext) {
3550 // FIXME: in C++0x, we can diagnose if we can prove that the
3551 // nested-name-specifier does not refer to a base class, which is
3552 // still possible in some cases.
3553
3554 // Otherwise we have to conservatively report that things might be
3555 // okay.
3556 return false;
3557 }
3558
3559 if (!NamedContext->isRecord()) {
3560 // Ideally this would point at the last name in the specifier,
3561 // but we don't have that level of source info.
3562 Diag(SS.getRange().getBegin(),
3563 diag::err_using_decl_nested_name_specifier_is_not_class)
3564 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3565 return true;
3566 }
3567
3568 if (getLangOptions().CPlusPlus0x) {
3569 // C++0x [namespace.udecl]p3:
3570 // In a using-declaration used as a member-declaration, the
3571 // nested-name-specifier shall name a base class of the class
3572 // being defined.
3573
3574 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3575 cast<CXXRecordDecl>(NamedContext))) {
3576 if (CurContext == NamedContext) {
3577 Diag(NameLoc,
3578 diag::err_using_decl_nested_name_specifier_is_current_class)
3579 << SS.getRange();
3580 return true;
3581 }
3582
3583 Diag(SS.getRange().getBegin(),
3584 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3585 << (NestedNameSpecifier*) SS.getScopeRep()
3586 << cast<CXXRecordDecl>(CurContext)
3587 << SS.getRange();
3588 return true;
3589 }
3590
3591 return false;
3592 }
3593
3594 // C++03 [namespace.udecl]p4:
3595 // A using-declaration used as a member-declaration shall refer
3596 // to a member of a base class of the class being defined [etc.].
3597
3598 // Salient point: SS doesn't have to name a base class as long as
3599 // lookup only finds members from base classes. Therefore we can
3600 // diagnose here only if we can prove that that can't happen,
3601 // i.e. if the class hierarchies provably don't intersect.
3602
3603 // TODO: it would be nice if "definitely valid" results were cached
3604 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3605 // need to be repeated.
3606
3607 struct UserData {
3608 llvm::DenseSet<const CXXRecordDecl*> Bases;
3609
3610 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3611 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3612 Data->Bases.insert(Base);
3613 return true;
3614 }
3615
3616 bool hasDependentBases(const CXXRecordDecl *Class) {
3617 return !Class->forallBases(collect, this);
3618 }
3619
3620 /// Returns true if the base is dependent or is one of the
3621 /// accumulated base classes.
3622 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3623 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3624 return !Data->Bases.count(Base);
3625 }
3626
3627 bool mightShareBases(const CXXRecordDecl *Class) {
3628 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3629 }
3630 };
3631
3632 UserData Data;
3633
3634 // Returns false if we find a dependent base.
3635 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3636 return false;
3637
3638 // Returns false if the class has a dependent base or if it or one
3639 // of its bases is present in the base set of the current context.
3640 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3641 return false;
3642
3643 Diag(SS.getRange().getBegin(),
3644 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3645 << (NestedNameSpecifier*) SS.getScopeRep()
3646 << cast<CXXRecordDecl>(CurContext)
3647 << SS.getRange();
3648
3649 return true;
John McCalled976492009-12-04 22:46:56 +00003650}
3651
Mike Stump1eb44332009-09-09 15:08:12 +00003652Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003653 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003654 SourceLocation AliasLoc,
3655 IdentifierInfo *Alias,
3656 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003657 SourceLocation IdentLoc,
3658 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Anders Carlsson81c85c42009-03-28 23:53:49 +00003660 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003661 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3662 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003663
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003664 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003665 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003666 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003667 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003668 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003669 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003670 if (!R.isAmbiguous() && !R.empty() &&
3671 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003672 return DeclPtrTy();
3673 }
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003675 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3676 diag::err_redefinition_different_kind;
3677 Diag(AliasLoc, DiagID) << Alias;
3678 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003679 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003680 }
3681
John McCalla24dc2e2009-11-17 02:14:36 +00003682 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003683 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003684
John McCallf36e02d2009-10-09 21:13:30 +00003685 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003686 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003687 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003688 }
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003690 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003691 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3692 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003693 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003694 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003696 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003697 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003698}
3699
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003700void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3701 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003702 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3703 !Constructor->isUsed()) &&
3704 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Eli Friedman80c30da2009-11-09 19:20:36 +00003706 CXXRecordDecl *ClassDecl
3707 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3708 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003709
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003710 DeclContext *PreviousContext = CurContext;
3711 CurContext = Constructor;
3712 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003713 Diag(CurrentLocation, diag::note_member_synthesized_at)
3714 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003715 Constructor->setInvalidDecl();
3716 } else {
3717 Constructor->setUsed();
3718 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003719 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003720}
3721
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003722void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003723 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003724 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3725 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003726 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003727 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003728
3729 DeclContext *PreviousContext = CurContext;
3730 CurContext = Destructor;
3731
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003732 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003733 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003734 // implicitly defined, all the implicitly-declared default destructors
3735 // for its base class and its non-static data members shall have been
3736 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003737 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3738 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003739 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003740 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003741 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003742 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003743 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3744 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3745 else
Mike Stump1eb44332009-09-09 15:08:12 +00003746 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003747 "DefineImplicitDestructor - missing dtor in a base class");
3748 }
3749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003751 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3752 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003753 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3754 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3755 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003756 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003757 CXXRecordDecl *FieldClassDecl
3758 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3759 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003760 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003761 const_cast<CXXDestructorDecl*>(
3762 FieldClassDecl->getDestructor(Context)))
3763 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3764 else
Mike Stump1eb44332009-09-09 15:08:12 +00003765 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003766 "DefineImplicitDestructor - missing dtor in class of a data member");
3767 }
3768 }
3769 }
Anders Carlsson37909802009-11-30 21:24:50 +00003770
3771 // FIXME: If CheckDestructor fails, we should emit a note about where the
3772 // implicit destructor was needed.
3773 if (CheckDestructor(Destructor)) {
3774 Diag(CurrentLocation, diag::note_member_synthesized_at)
3775 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3776
3777 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003778 CurContext = PreviousContext;
3779
Anders Carlsson37909802009-11-30 21:24:50 +00003780 return;
3781 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003782 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003783
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003784 Destructor->setUsed();
3785}
3786
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003787void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3788 CXXMethodDecl *MethodDecl) {
3789 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3790 MethodDecl->getOverloadedOperator() == OO_Equal &&
3791 !MethodDecl->isUsed()) &&
3792 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003793
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003794 CXXRecordDecl *ClassDecl
3795 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003796
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003797 DeclContext *PreviousContext = CurContext;
3798 CurContext = MethodDecl;
3799
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003800 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003801 // Before the implicitly-declared copy assignment operator for a class is
3802 // implicitly defined, all implicitly-declared copy assignment operators
3803 // for its direct base classes and its nonstatic data members shall have
3804 // been implicitly defined.
3805 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003806 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3807 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003808 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003809 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003810 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003811 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3812 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003813 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3814 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003815 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3816 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003817 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3818 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3819 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003820 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003821 CXXRecordDecl *FieldClassDecl
3822 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003823 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003824 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3825 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003826 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003827 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003828 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003829 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3830 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003831 Diag(CurrentLocation, diag::note_first_required_here);
3832 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003833 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003834 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003835 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3836 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003837 Diag(CurrentLocation, diag::note_first_required_here);
3838 err = true;
3839 }
3840 }
3841 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003842 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003843
3844 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003845}
3846
3847CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003848Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3849 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003850 CXXRecordDecl *ClassDecl) {
3851 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3852 QualType RHSType(LHSType);
3853 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003854 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003855 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003856 RHSType = Context.getCVRQualifiedType(RHSType,
3857 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003858 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003859 LHSType,
3860 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003861 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003862 RHSType,
3863 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003864 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003865 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003866 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003867 CandidateSet);
3868 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003869 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003870 return cast<CXXMethodDecl>(Best->Function);
3871 assert(false &&
3872 "getAssignOperatorMethod - copy assignment operator method not found");
3873 return 0;
3874}
3875
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003876void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3877 CXXConstructorDecl *CopyConstructor,
3878 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003879 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003880 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003881 !CopyConstructor->isUsed()) &&
3882 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003884 CXXRecordDecl *ClassDecl
3885 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3886 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003887
3888 DeclContext *PreviousContext = CurContext;
3889 CurContext = CopyConstructor;
3890
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003891 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003892 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003893 // implicitly defined, all the implicitly-declared copy constructors
3894 // for its base class and its non-static data members shall have been
3895 // implicitly defined.
3896 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3897 Base != ClassDecl->bases_end(); ++Base) {
3898 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003899 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003900 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003901 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003902 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003903 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003904 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3905 FieldEnd = ClassDecl->field_end();
3906 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003907 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3908 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3909 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003910 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003911 CXXRecordDecl *FieldClassDecl
3912 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003913 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003914 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003915 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003916 }
3917 }
3918 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003919
3920 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003921}
3922
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003923Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003924Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003925 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003926 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003927 bool RequiresZeroInit,
3928 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003929 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Douglas Gregor39da0b82009-09-09 23:08:42 +00003931 // C++ [class.copy]p15:
3932 // Whenever a temporary class object is copied using a copy constructor, and
3933 // this object and the copy have the same cv-unqualified type, an
3934 // implementation is permitted to treat the original and the copy as two
3935 // different ways of referring to the same object and not perform a copy at
3936 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003938 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003939 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003940 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003941 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3942 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3943 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003944 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3945 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003946 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3947 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003948 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3949 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3950 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003951
3952 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3953 Elidable = !CE->getCallReturnType()->isReferenceType();
3954 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003955 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003956 else if (isa<CXXConstructExpr>(E))
3957 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003958 }
Mike Stump1eb44332009-09-09 15:08:12 +00003959
3960 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003961 Elidable, move(ExprArgs), RequiresZeroInit,
3962 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003963}
3964
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003965/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3966/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003967Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003968Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3969 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003970 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003971 bool RequiresZeroInit,
3972 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003973 unsigned NumExprs = ExprArgs.size();
3974 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003975
Douglas Gregor7edfb692009-11-23 12:27:39 +00003976 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003977 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003978 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003979 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003980}
3981
Mike Stump1eb44332009-09-09 15:08:12 +00003982bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003983 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003984 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003985 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003986 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003987 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003988 if (TempResult.isInvalid())
3989 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003991 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003992 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003993 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00003994 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Anders Carlssonfe2de492009-08-25 05:18:00 +00003996 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003997}
3998
John McCall68c6c9a2010-02-02 09:10:11 +00003999void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4000 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
John McCall4f9506a2010-02-02 08:45:54 +00004001 if (!ClassDecl->hasTrivialDestructor()) {
4002 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4003 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004004 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004005 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004006}
4007
Mike Stump1eb44332009-09-09 15:08:12 +00004008/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004009/// ActOnDeclarator, when a C++ direct initializer is present.
4010/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004011void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4012 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004013 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004014 SourceLocation *CommaLocs,
4015 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004016 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004017 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004018
4019 // If there is no declaration, there was an error parsing it. Just ignore
4020 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004021 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004022 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004024 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4025 if (!VDecl) {
4026 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4027 RealDecl->setInvalidDecl();
4028 return;
4029 }
4030
Douglas Gregor83ddad32009-08-26 21:14:46 +00004031 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004032 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004033 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4034 //
4035 // Clients that want to distinguish between the two forms, can check for
4036 // direct initializer using VarDecl::hasCXXDirectInitializer().
4037 // A major benefit is that clients that don't particularly care about which
4038 // exactly form was it (like the CodeGen) can handle both cases without
4039 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004040
Douglas Gregor83ddad32009-08-26 21:14:46 +00004041 // If either the declaration has a dependent type or if any of the expressions
4042 // is type-dependent, we represent the initialization via a ParenListExpr for
4043 // later use during template instantiation.
4044 if (VDecl->getType()->isDependentType() ||
4045 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4046 // Let clients know that initialization was done with a direct initializer.
4047 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Douglas Gregor83ddad32009-08-26 21:14:46 +00004049 // Store the initialization expressions as a ParenListExpr.
4050 unsigned NumExprs = Exprs.size();
Douglas Gregor838db382010-02-11 01:19:42 +00004051 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
Douglas Gregor83ddad32009-08-26 21:14:46 +00004052 (Expr **)Exprs.release(),
4053 NumExprs, RParenLoc));
4054 return;
4055 }
Mike Stump1eb44332009-09-09 15:08:12 +00004056
Douglas Gregor83ddad32009-08-26 21:14:46 +00004057
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004058 // C++ 8.5p11:
4059 // The form of initialization (using parentheses or '=') is generally
4060 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004061 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004062 QualType DeclInitType = VDecl->getType();
4063 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004064 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004065
Douglas Gregor615c5d42009-03-24 16:43:20 +00004066 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4067 diag::err_typecheck_decl_incomplete_type)) {
4068 VDecl->setInvalidDecl();
4069 return;
4070 }
4071
Douglas Gregor90f93822009-12-22 22:17:25 +00004072 // The variable can not have an abstract class type.
4073 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4074 diag::err_abstract_type_in_decl,
4075 AbstractVariableType))
4076 VDecl->setInvalidDecl();
4077
Sebastian Redl31310a22010-02-01 20:16:42 +00004078 const VarDecl *Def;
4079 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004080 Diag(VDecl->getLocation(), diag::err_redefinition)
4081 << VDecl->getDeclName();
4082 Diag(Def->getLocation(), diag::note_previous_definition);
4083 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004084 return;
4085 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004086
4087 // Capture the variable that is being initialized and the style of
4088 // initialization.
4089 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4090
4091 // FIXME: Poor source location information.
4092 InitializationKind Kind
4093 = InitializationKind::CreateDirect(VDecl->getLocation(),
4094 LParenLoc, RParenLoc);
4095
4096 InitializationSequence InitSeq(*this, Entity, Kind,
4097 (Expr**)Exprs.get(), Exprs.size());
4098 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4099 if (Result.isInvalid()) {
4100 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004101 return;
4102 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004103
4104 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004105 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004106 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004107
John McCall68c6c9a2010-02-02 09:10:11 +00004108 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4109 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004110}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004111
Douglas Gregor19aeac62009-11-14 03:27:21 +00004112/// \brief Add the applicable constructor candidates for an initialization
4113/// by constructor.
4114static void AddConstructorInitializationCandidates(Sema &SemaRef,
4115 QualType ClassType,
4116 Expr **Args,
4117 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004118 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004119 OverloadCandidateSet &CandidateSet) {
4120 // C++ [dcl.init]p14:
4121 // If the initialization is direct-initialization, or if it is
4122 // copy-initialization where the cv-unqualified version of the
4123 // source type is the same class as, or a derived class of, the
4124 // class of the destination, constructors are considered. The
4125 // applicable constructors are enumerated (13.3.1.3), and the
4126 // best one is chosen through overload resolution (13.3). The
4127 // constructor so selected is called to initialize the object,
4128 // with the initializer expression(s) as its argument(s). If no
4129 // constructor applies, or the overload resolution is ambiguous,
4130 // the initialization is ill-formed.
4131 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4132 assert(ClassRec && "Can only initialize a class type here");
4133
4134 // FIXME: When we decide not to synthesize the implicitly-declared
4135 // constructors, we'll need to make them appear here.
4136
4137 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4138 DeclarationName ConstructorName
4139 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4140 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4141 DeclContext::lookup_const_iterator Con, ConEnd;
4142 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4143 Con != ConEnd; ++Con) {
4144 // Find the constructor (which may be a template).
4145 CXXConstructorDecl *Constructor = 0;
4146 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4147 if (ConstructorTmpl)
4148 Constructor
4149 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4150 else
4151 Constructor = cast<CXXConstructorDecl>(*Con);
4152
Douglas Gregor20093b42009-12-09 23:02:17 +00004153 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4154 (Kind.getKind() == InitializationKind::IK_Value) ||
4155 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004156 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004157 ((Kind.getKind() == InitializationKind::IK_Default) &&
4158 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004159 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004160 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004161 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004162 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004163 Args, NumArgs, CandidateSet);
4164 else
John McCall86820f52010-01-26 01:37:31 +00004165 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4166 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004167 }
4168 }
4169}
4170
4171/// \brief Attempt to perform initialization by constructor
4172/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4173/// copy-initialization.
4174///
4175/// This routine determines whether initialization by constructor is possible,
4176/// but it does not emit any diagnostics in the case where the initialization
4177/// is ill-formed.
4178///
4179/// \param ClassType the type of the object being initialized, which must have
4180/// class type.
4181///
4182/// \param Args the arguments provided to initialize the object
4183///
4184/// \param NumArgs the number of arguments provided to initialize the object
4185///
4186/// \param Kind the type of initialization being performed
4187///
4188/// \returns the constructor used to initialize the object, if successful.
4189/// Otherwise, emits a diagnostic and returns NULL.
4190CXXConstructorDecl *
4191Sema::TryInitializationByConstructor(QualType ClassType,
4192 Expr **Args, unsigned NumArgs,
4193 SourceLocation Loc,
4194 InitializationKind Kind) {
4195 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004196 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004197 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4198 CandidateSet);
4199
4200 // Determine whether we found a constructor we can use.
4201 OverloadCandidateSet::iterator Best;
4202 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4203 case OR_Success:
4204 case OR_Deleted:
4205 // We found a constructor. Return it.
4206 return cast<CXXConstructorDecl>(Best->Function);
4207
4208 case OR_No_Viable_Function:
4209 case OR_Ambiguous:
4210 // Overload resolution failed. Return nothing.
4211 return 0;
4212 }
4213
4214 // Silence GCC warning
4215 return 0;
4216}
4217
Douglas Gregor39da0b82009-09-09 23:08:42 +00004218/// \brief Given a constructor and the set of arguments provided for the
4219/// constructor, convert the arguments and add any required default arguments
4220/// to form a proper call to this constructor.
4221///
4222/// \returns true if an error occurred, false otherwise.
4223bool
4224Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4225 MultiExprArg ArgsPtr,
4226 SourceLocation Loc,
4227 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4228 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4229 unsigned NumArgs = ArgsPtr.size();
4230 Expr **Args = (Expr **)ArgsPtr.get();
4231
4232 const FunctionProtoType *Proto
4233 = Constructor->getType()->getAs<FunctionProtoType>();
4234 assert(Proto && "Constructor without a prototype?");
4235 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004236
4237 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004238 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004239 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004240 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004241 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004242
4243 VariadicCallType CallType =
4244 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4245 llvm::SmallVector<Expr *, 8> AllArgs;
4246 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4247 Proto, 0, Args, NumArgs, AllArgs,
4248 CallType);
4249 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4250 ConvertedArgs.push_back(AllArgs[i]);
4251 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004252}
4253
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004254/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4255/// determine whether they are reference-related,
4256/// reference-compatible, reference-compatible with added
4257/// qualification, or incompatible, for use in C++ initialization by
4258/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4259/// type, and the first type (T1) is the pointee type of the reference
4260/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004261Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004262Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004263 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004264 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004265 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004266 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004267 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004268
Douglas Gregor393896f2009-11-05 13:06:35 +00004269 QualType T1 = Context.getCanonicalType(OrigT1);
4270 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004271 Qualifiers T1Quals, T2Quals;
4272 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4273 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004274
4275 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004276 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004277 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004278 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004279 if (UnqualT1 == UnqualT2)
4280 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004281 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4282 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4283 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004284 DerivedToBase = true;
4285 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004286 return Ref_Incompatible;
4287
4288 // At this point, we know that T1 and T2 are reference-related (at
4289 // least).
4290
Chandler Carruth28e318c2009-12-29 07:16:59 +00004291 // If the type is an array type, promote the element qualifiers to the type
4292 // for comparison.
4293 if (isa<ArrayType>(T1) && T1Quals)
4294 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4295 if (isa<ArrayType>(T2) && T2Quals)
4296 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4297
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004298 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004299 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004300 // reference-related to T2 and cv1 is the same cv-qualification
4301 // as, or greater cv-qualification than, cv2. For purposes of
4302 // overload resolution, cases for which cv1 is greater
4303 // cv-qualification than cv2 are identified as
4304 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004305 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004306 return Ref_Compatible;
4307 else if (T1.isMoreQualifiedThan(T2))
4308 return Ref_Compatible_With_Added_Qualification;
4309 else
4310 return Ref_Related;
4311}
4312
4313/// CheckReferenceInit - Check the initialization of a reference
4314/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4315/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004316/// list), and DeclType is the type of the declaration. When ICS is
4317/// non-null, this routine will compute the implicit conversion
4318/// sequence according to C++ [over.ics.ref] and will not produce any
4319/// diagnostics; when ICS is null, it will emit diagnostics when any
4320/// errors are found. Either way, a return value of true indicates
4321/// that there was a failure, a return value of false indicates that
4322/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004323///
4324/// When @p SuppressUserConversions, user-defined conversions are
4325/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004326/// When @p AllowExplicit, we also permit explicit user-defined
4327/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004328/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004329/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4330/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004331bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004332Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004333 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004334 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004335 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004336 ImplicitConversionSequence *ICS,
4337 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004338 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4339
Ted Kremenek6217b802009-07-29 21:53:49 +00004340 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004341 QualType T2 = Init->getType();
4342
Douglas Gregor904eed32008-11-10 20:40:00 +00004343 // If the initializer is the address of an overloaded function, try
4344 // to resolve the overloaded function. If all goes well, T2 is the
4345 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004346 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004347 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004348 ICS != 0);
4349 if (Fn) {
4350 // Since we're performing this reference-initialization for
4351 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004352 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004353 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004354 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004355
Anders Carlsson96ad5332009-10-21 17:16:23 +00004356 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004357 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004358
4359 T2 = Fn->getType();
4360 }
4361 }
4362
Douglas Gregor15da57e2008-10-29 02:00:59 +00004363 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004364 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004365 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004366 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4367 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004368 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004369 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004370
4371 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004372 if (ICS) {
4373 ICS->setBad();
4374 ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4375 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004376
4377 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004378 // A reference to type "cv1 T1" is initialized by an expression
4379 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004380
4381 // -- If the initializer expression
4382
Sebastian Redla9845802009-03-29 15:27:50 +00004383 // Rvalue references cannot bind to lvalues (N2812).
4384 // There is absolutely no situation where they can. In particular, note that
4385 // this is ill-formed, even if B has a user-defined conversion to A&&:
4386 // B b;
4387 // A&& r = b;
4388 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4389 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004390 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004391 << Init->getSourceRange();
4392 return true;
4393 }
4394
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004395 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004396 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4397 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004398 //
4399 // Note that the bit-field check is skipped if we are just computing
4400 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004401 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004402 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004403 BindsDirectly = true;
4404
Douglas Gregor15da57e2008-10-29 02:00:59 +00004405 if (ICS) {
4406 // C++ [over.ics.ref]p1:
4407 // When a parameter of reference type binds directly (8.5.3)
4408 // to an argument expression, the implicit conversion sequence
4409 // is the identity conversion, unless the argument expression
4410 // has a type that is a derived class of the parameter type,
4411 // in which case the implicit conversion sequence is a
4412 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004413 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004414 ICS->Standard.First = ICK_Identity;
4415 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4416 ICS->Standard.Third = ICK_Identity;
4417 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004418 ICS->Standard.setToType(0, T2);
4419 ICS->Standard.setToType(1, T1);
4420 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004421 ICS->Standard.ReferenceBinding = true;
4422 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004423 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004424 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004425
4426 // Nothing more to do: the inaccessibility/ambiguity check for
4427 // derived-to-base conversions is suppressed when we're
4428 // computing the implicit conversion sequence (C++
4429 // [over.best.ics]p2).
4430 return false;
4431 } else {
4432 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004433 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4434 if (DerivedToBase)
4435 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004436 else if(CheckExceptionSpecCompatibility(Init, T1))
4437 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004438 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004439 }
4440 }
4441
4442 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004443 // implicitly converted to an lvalue of type "cv3 T3,"
4444 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004445 // 92) (this conversion is selected by enumerating the
4446 // applicable conversion functions (13.3.1.6) and choosing
4447 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004448 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004449 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004450 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004451 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004452
John McCall5769d612010-02-08 23:07:23 +00004453 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004454 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004455 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004456 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004457 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004458 NamedDecl *D = *I;
4459 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4460 if (isa<UsingShadowDecl>(D))
4461 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4462
Mike Stump1eb44332009-09-09 15:08:12 +00004463 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004464 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004465 CXXConversionDecl *Conv;
4466 if (ConvTemplate)
4467 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4468 else
John McCall701c89e2009-12-03 04:06:58 +00004469 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004470
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004471 // If the conversion function doesn't return a reference type,
4472 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004473 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004474 (AllowExplicit || !Conv->isExplicit())) {
4475 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004476 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004477 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004478 else
John McCall86820f52010-01-26 01:37:31 +00004479 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4480 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004481 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004482 }
4483
4484 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004485 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004486 case OR_Success:
4487 // This is a direct binding.
4488 BindsDirectly = true;
4489
4490 if (ICS) {
4491 // C++ [over.ics.ref]p1:
4492 //
4493 // [...] If the parameter binds directly to the result of
4494 // applying a conversion function to the argument
4495 // expression, the implicit conversion sequence is a
4496 // user-defined conversion sequence (13.3.3.1.2), with the
4497 // second standard conversion sequence either an identity
4498 // conversion or, if the conversion function returns an
4499 // entity of a type that is a derived class of the parameter
4500 // type, a derived-to-base Conversion.
John McCall1d318332010-01-12 00:44:57 +00004501 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004502 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4503 ICS->UserDefined.After = Best->FinalConversion;
4504 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004505 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004506 assert(ICS->UserDefined.After.ReferenceBinding &&
4507 ICS->UserDefined.After.DirectBinding &&
4508 "Expected a direct reference binding!");
4509 return false;
4510 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004511 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004512 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004513 CastExpr::CK_UserDefinedConversion,
4514 cast<CXXMethodDecl>(Best->Function),
4515 Owned(Init));
4516 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004517
4518 if (CheckExceptionSpecCompatibility(Init, T1))
4519 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004520 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4521 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004522 }
4523 break;
4524
4525 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004526 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004527 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004528 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4529 Cand != CandidateSet.end(); ++Cand)
4530 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004531 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004532 break;
4533 }
4534 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4535 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004536 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004537 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004538
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004539 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004540 case OR_Deleted:
4541 // There was no suitable conversion, or we found a deleted
4542 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004543 break;
4544 }
4545 }
Mike Stump1eb44332009-09-09 15:08:12 +00004546
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004547 if (BindsDirectly) {
4548 // C++ [dcl.init.ref]p4:
4549 // [...] In all cases where the reference-related or
4550 // reference-compatible relationship of two types is used to
4551 // establish the validity of a reference binding, and T1 is a
4552 // base class of T2, a program that necessitates such a binding
4553 // is ill-formed if T1 is an inaccessible (clause 11) or
4554 // ambiguous (10.2) base class of T2.
4555 //
4556 // Note that we only check this condition when we're allowed to
4557 // complain about errors, because we should not be checking for
4558 // ambiguity (or inaccessibility) unless the reference binding
4559 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004560 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004561 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004562 Init->getSourceRange(),
4563 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004564 else
4565 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004566 }
4567
4568 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004569 // type (i.e., cv1 shall be const), or the reference shall be an
4570 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004571 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004572 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004573 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004574 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004575 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004576 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004577 return true;
4578 }
4579
4580 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004581 // class type, and "cv1 T1" is reference-compatible with
4582 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004583 // following ways (the choice is implementation-defined):
4584 //
4585 // -- The reference is bound to the object represented by
4586 // the rvalue (see 3.10) or to a sub-object within that
4587 // object.
4588 //
Eli Friedman33a31382009-08-05 19:21:58 +00004589 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004590 // a constructor is called to copy the entire rvalue
4591 // object into the temporary. The reference is bound to
4592 // the temporary or to a sub-object within the
4593 // temporary.
4594 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004595 // The constructor that would be used to make the copy
4596 // shall be callable whether or not the copy is actually
4597 // done.
4598 //
Sebastian Redla9845802009-03-29 15:27:50 +00004599 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004600 // freedom, so we will always take the first option and never build
4601 // a temporary in this case. FIXME: We will, however, have to check
4602 // for the presence of a copy constructor in C++98/03 mode.
4603 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004604 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4605 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004606 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004607 ICS->Standard.First = ICK_Identity;
4608 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4609 ICS->Standard.Third = ICK_Identity;
4610 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004611 ICS->Standard.setToType(0, T2);
4612 ICS->Standard.setToType(1, T1);
4613 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004614 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004615 ICS->Standard.DirectBinding = false;
4616 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004617 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004618 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004619 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4620 if (DerivedToBase)
4621 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004622 else if(CheckExceptionSpecCompatibility(Init, T1))
4623 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004624 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004625 }
4626 return false;
4627 }
4628
Eli Friedman33a31382009-08-05 19:21:58 +00004629 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004630 // initialized from the initializer expression using the
4631 // rules for a non-reference copy initialization (8.5). The
4632 // reference is then bound to the temporary. If T1 is
4633 // reference-related to T2, cv1 must be the same
4634 // cv-qualification as, or greater cv-qualification than,
4635 // cv2; otherwise, the program is ill-formed.
4636 if (RefRelationship == Ref_Related) {
4637 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4638 // we would be reference-compatible or reference-compatible with
4639 // added qualification. But that wasn't the case, so the reference
4640 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004641 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004642 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004643 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004644 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004645 return true;
4646 }
4647
Douglas Gregor734d9862009-01-30 23:27:23 +00004648 // If at least one of the types is a class type, the types are not
4649 // related, and we aren't allowed any user conversions, the
4650 // reference binding fails. This case is important for breaking
4651 // recursion, since TryImplicitConversion below will attempt to
4652 // create a temporary through the use of a copy constructor.
4653 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4654 (T1->isRecordType() || T2->isRecordType())) {
4655 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004656 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004657 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004658 return true;
4659 }
4660
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004661 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004662 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004663 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004664 //
Sebastian Redla9845802009-03-29 15:27:50 +00004665 // When a parameter of reference type is not bound directly to
4666 // an argument expression, the conversion sequence is the one
4667 // required to convert the argument expression to the
4668 // underlying type of the reference according to
4669 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4670 // to copy-initializing a temporary of the underlying type with
4671 // the argument expression. Any difference in top-level
4672 // cv-qualification is subsumed by the initialization itself
4673 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004674 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4675 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004676 /*ForceRValue=*/false,
4677 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Sebastian Redla9845802009-03-29 15:27:50 +00004679 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004680 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004681 ICS->Standard.ReferenceBinding = true;
4682 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004683 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004684 ICS->UserDefined.After.ReferenceBinding = true;
4685 ICS->UserDefined.After.RRefBinding = isRValRef;
4686 }
John McCall1d318332010-01-12 00:44:57 +00004687 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004688 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004689 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004690 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004691 false, false,
4692 Conversions);
4693 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004694 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004695 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004696 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004697 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004698 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004699 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004700 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004701 }
4702 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004703 else {
4704 if (isRValRef)
4705 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4706 << Init->getSourceRange();
4707 else
4708 Diag(DeclLoc, diag::err_invalid_initialization)
4709 << DeclType << Init->getType() << Init->getSourceRange();
4710 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004711 }
4712 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004713 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004714}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004715
Anders Carlsson20d45d22009-12-12 00:32:00 +00004716static inline bool
4717CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4718 const FunctionDecl *FnDecl) {
4719 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4720 if (isa<NamespaceDecl>(DC)) {
4721 return SemaRef.Diag(FnDecl->getLocation(),
4722 diag::err_operator_new_delete_declared_in_namespace)
4723 << FnDecl->getDeclName();
4724 }
4725
4726 if (isa<TranslationUnitDecl>(DC) &&
4727 FnDecl->getStorageClass() == FunctionDecl::Static) {
4728 return SemaRef.Diag(FnDecl->getLocation(),
4729 diag::err_operator_new_delete_declared_static)
4730 << FnDecl->getDeclName();
4731 }
4732
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004733 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004734}
4735
Anders Carlsson156c78e2009-12-13 17:53:43 +00004736static inline bool
4737CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4738 CanQualType ExpectedResultType,
4739 CanQualType ExpectedFirstParamType,
4740 unsigned DependentParamTypeDiag,
4741 unsigned InvalidParamTypeDiag) {
4742 QualType ResultType =
4743 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4744
4745 // Check that the result type is not dependent.
4746 if (ResultType->isDependentType())
4747 return SemaRef.Diag(FnDecl->getLocation(),
4748 diag::err_operator_new_delete_dependent_result_type)
4749 << FnDecl->getDeclName() << ExpectedResultType;
4750
4751 // Check that the result type is what we expect.
4752 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4753 return SemaRef.Diag(FnDecl->getLocation(),
4754 diag::err_operator_new_delete_invalid_result_type)
4755 << FnDecl->getDeclName() << ExpectedResultType;
4756
4757 // A function template must have at least 2 parameters.
4758 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4759 return SemaRef.Diag(FnDecl->getLocation(),
4760 diag::err_operator_new_delete_template_too_few_parameters)
4761 << FnDecl->getDeclName();
4762
4763 // The function decl must have at least 1 parameter.
4764 if (FnDecl->getNumParams() == 0)
4765 return SemaRef.Diag(FnDecl->getLocation(),
4766 diag::err_operator_new_delete_too_few_parameters)
4767 << FnDecl->getDeclName();
4768
4769 // Check the the first parameter type is not dependent.
4770 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4771 if (FirstParamType->isDependentType())
4772 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4773 << FnDecl->getDeclName() << ExpectedFirstParamType;
4774
4775 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004776 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004777 ExpectedFirstParamType)
4778 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4779 << FnDecl->getDeclName() << ExpectedFirstParamType;
4780
4781 return false;
4782}
4783
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004784static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004785CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004786 // C++ [basic.stc.dynamic.allocation]p1:
4787 // A program is ill-formed if an allocation function is declared in a
4788 // namespace scope other than global scope or declared static in global
4789 // scope.
4790 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4791 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004792
4793 CanQualType SizeTy =
4794 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4795
4796 // C++ [basic.stc.dynamic.allocation]p1:
4797 // The return type shall be void*. The first parameter shall have type
4798 // std::size_t.
4799 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4800 SizeTy,
4801 diag::err_operator_new_dependent_param_type,
4802 diag::err_operator_new_param_type))
4803 return true;
4804
4805 // C++ [basic.stc.dynamic.allocation]p1:
4806 // The first parameter shall not have an associated default argument.
4807 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004808 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004809 diag::err_operator_new_default_arg)
4810 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4811
4812 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004813}
4814
4815static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004816CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4817 // C++ [basic.stc.dynamic.deallocation]p1:
4818 // A program is ill-formed if deallocation functions are declared in a
4819 // namespace scope other than global scope or declared static in global
4820 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004821 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4822 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004823
4824 // C++ [basic.stc.dynamic.deallocation]p2:
4825 // Each deallocation function shall return void and its first parameter
4826 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004827 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4828 SemaRef.Context.VoidPtrTy,
4829 diag::err_operator_delete_dependent_param_type,
4830 diag::err_operator_delete_param_type))
4831 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004832
Anders Carlsson46991d62009-12-12 00:16:02 +00004833 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4834 if (FirstParamType->isDependentType())
4835 return SemaRef.Diag(FnDecl->getLocation(),
4836 diag::err_operator_delete_dependent_param_type)
4837 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4838
4839 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4840 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004841 return SemaRef.Diag(FnDecl->getLocation(),
4842 diag::err_operator_delete_param_type)
4843 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004844
4845 return false;
4846}
4847
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004848/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4849/// of this overloaded operator is well-formed. If so, returns false;
4850/// otherwise, emits appropriate diagnostics and returns true.
4851bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004852 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004853 "Expected an overloaded operator declaration");
4854
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004855 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4856
Mike Stump1eb44332009-09-09 15:08:12 +00004857 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004858 // The allocation and deallocation functions, operator new,
4859 // operator new[], operator delete and operator delete[], are
4860 // described completely in 3.7.3. The attributes and restrictions
4861 // found in the rest of this subclause do not apply to them unless
4862 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004863 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004864 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004865
Anders Carlssona3ccda52009-12-12 00:26:23 +00004866 if (Op == OO_New || Op == OO_Array_New)
4867 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004868
4869 // C++ [over.oper]p6:
4870 // An operator function shall either be a non-static member
4871 // function or be a non-member function and have at least one
4872 // parameter whose type is a class, a reference to a class, an
4873 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004874 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4875 if (MethodDecl->isStatic())
4876 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004877 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004878 } else {
4879 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004880 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4881 ParamEnd = FnDecl->param_end();
4882 Param != ParamEnd; ++Param) {
4883 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004884 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4885 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004886 ClassOrEnumParam = true;
4887 break;
4888 }
4889 }
4890
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004891 if (!ClassOrEnumParam)
4892 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004893 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004894 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004895 }
4896
4897 // C++ [over.oper]p8:
4898 // An operator function cannot have default arguments (8.3.6),
4899 // except where explicitly stated below.
4900 //
Mike Stump1eb44332009-09-09 15:08:12 +00004901 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004902 // (C++ [over.call]p1).
4903 if (Op != OO_Call) {
4904 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4905 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004906 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004907 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004908 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004909 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004910 }
4911 }
4912
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004913 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4914 { false, false, false }
4915#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4916 , { Unary, Binary, MemberOnly }
4917#include "clang/Basic/OperatorKinds.def"
4918 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004919
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004920 bool CanBeUnaryOperator = OperatorUses[Op][0];
4921 bool CanBeBinaryOperator = OperatorUses[Op][1];
4922 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004923
4924 // C++ [over.oper]p8:
4925 // [...] Operator functions cannot have more or fewer parameters
4926 // than the number required for the corresponding operator, as
4927 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004928 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004929 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004930 if (Op != OO_Call &&
4931 ((NumParams == 1 && !CanBeUnaryOperator) ||
4932 (NumParams == 2 && !CanBeBinaryOperator) ||
4933 (NumParams < 1) || (NumParams > 2))) {
4934 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004935 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004936 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004937 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004938 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004939 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004940 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004941 assert(CanBeBinaryOperator &&
4942 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004943 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004944 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004945
Chris Lattner416e46f2008-11-21 07:57:12 +00004946 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004947 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004948 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004949
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004950 // Overloaded operators other than operator() cannot be variadic.
4951 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004952 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004953 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004954 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004955 }
4956
4957 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004958 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4959 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004960 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004961 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004962 }
4963
4964 // C++ [over.inc]p1:
4965 // The user-defined function called operator++ implements the
4966 // prefix and postfix ++ operator. If this function is a member
4967 // function with no parameters, or a non-member function with one
4968 // parameter of class or enumeration type, it defines the prefix
4969 // increment operator ++ for objects of that type. If the function
4970 // is a member function with one parameter (which shall be of type
4971 // int) or a non-member function with two parameters (the second
4972 // of which shall be of type int), it defines the postfix
4973 // increment operator ++ for objects of that type.
4974 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4975 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4976 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004977 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004978 ParamIsInt = BT->getKind() == BuiltinType::Int;
4979
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004980 if (!ParamIsInt)
4981 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004982 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004983 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004984 }
4985
Sebastian Redl64b45f72009-01-05 20:52:13 +00004986 // Notify the class if it got an assignment operator.
4987 if (Op == OO_Equal) {
4988 // Would have returned earlier otherwise.
4989 assert(isa<CXXMethodDecl>(FnDecl) &&
4990 "Overloaded = not member, but not filtered.");
4991 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4992 Method->getParent()->addedAssignmentOperator(Context, Method);
4993 }
4994
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004995 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004996}
Chris Lattner5a003a42008-12-17 07:09:26 +00004997
Sean Hunta6c058d2010-01-13 09:01:02 +00004998/// CheckLiteralOperatorDeclaration - Check whether the declaration
4999/// of this literal operator function is well-formed. If so, returns
5000/// false; otherwise, emits appropriate diagnostics and returns true.
5001bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5002 DeclContext *DC = FnDecl->getDeclContext();
5003 Decl::Kind Kind = DC->getDeclKind();
5004 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5005 Kind != Decl::LinkageSpec) {
5006 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5007 << FnDecl->getDeclName();
5008 return true;
5009 }
5010
5011 bool Valid = false;
5012
5013 // FIXME: Check for the one valid template signature
5014 // template <char...> type operator "" name();
5015
5016 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5017 // Check the first parameter
5018 QualType T = (*Param)->getType();
5019
5020 // unsigned long long int and long double are allowed, but only
5021 // alone.
5022 // We also allow any character type; their omission seems to be a bug
5023 // in n3000
5024 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5025 Context.hasSameType(T, Context.LongDoubleTy) ||
5026 Context.hasSameType(T, Context.CharTy) ||
5027 Context.hasSameType(T, Context.WCharTy) ||
5028 Context.hasSameType(T, Context.Char16Ty) ||
5029 Context.hasSameType(T, Context.Char32Ty)) {
5030 if (++Param == FnDecl->param_end())
5031 Valid = true;
5032 goto FinishedParams;
5033 }
5034
5035 // Otherwise it must be a pointer to const; let's strip those.
5036 const PointerType *PT = T->getAs<PointerType>();
5037 if (!PT)
5038 goto FinishedParams;
5039 T = PT->getPointeeType();
5040 if (!T.isConstQualified())
5041 goto FinishedParams;
5042 T = T.getUnqualifiedType();
5043
5044 // Move on to the second parameter;
5045 ++Param;
5046
5047 // If there is no second parameter, the first must be a const char *
5048 if (Param == FnDecl->param_end()) {
5049 if (Context.hasSameType(T, Context.CharTy))
5050 Valid = true;
5051 goto FinishedParams;
5052 }
5053
5054 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5055 // are allowed as the first parameter to a two-parameter function
5056 if (!(Context.hasSameType(T, Context.CharTy) ||
5057 Context.hasSameType(T, Context.WCharTy) ||
5058 Context.hasSameType(T, Context.Char16Ty) ||
5059 Context.hasSameType(T, Context.Char32Ty)))
5060 goto FinishedParams;
5061
5062 // The second and final parameter must be an std::size_t
5063 T = (*Param)->getType().getUnqualifiedType();
5064 if (Context.hasSameType(T, Context.getSizeType()) &&
5065 ++Param == FnDecl->param_end())
5066 Valid = true;
5067 }
5068
5069 // FIXME: This diagnostic is absolutely terrible.
5070FinishedParams:
5071 if (!Valid) {
5072 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5073 << FnDecl->getDeclName();
5074 return true;
5075 }
5076
5077 return false;
5078}
5079
Douglas Gregor074149e2009-01-05 19:45:36 +00005080/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5081/// linkage specification, including the language and (if present)
5082/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5083/// the location of the language string literal, which is provided
5084/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5085/// the '{' brace. Otherwise, this linkage specification does not
5086/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005087Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5088 SourceLocation ExternLoc,
5089 SourceLocation LangLoc,
5090 const char *Lang,
5091 unsigned StrSize,
5092 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005093 LinkageSpecDecl::LanguageIDs Language;
5094 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5095 Language = LinkageSpecDecl::lang_c;
5096 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5097 Language = LinkageSpecDecl::lang_cxx;
5098 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005099 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005100 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005101 }
Mike Stump1eb44332009-09-09 15:08:12 +00005102
Chris Lattnercc98eac2008-12-17 07:13:27 +00005103 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005104
Douglas Gregor074149e2009-01-05 19:45:36 +00005105 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005106 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005107 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005108 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005109 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005110 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005111}
5112
Douglas Gregor074149e2009-01-05 19:45:36 +00005113/// ActOnFinishLinkageSpecification - Completely the definition of
5114/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5115/// valid, it's the position of the closing '}' brace in a linkage
5116/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005117Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5118 DeclPtrTy LinkageSpec,
5119 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005120 if (LinkageSpec)
5121 PopDeclContext();
5122 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005123}
5124
Douglas Gregord308e622009-05-18 20:51:54 +00005125/// \brief Perform semantic analysis for the variable declaration that
5126/// occurs within a C++ catch clause, returning the newly-created
5127/// variable.
5128VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005129 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005130 IdentifierInfo *Name,
5131 SourceLocation Loc,
5132 SourceRange Range) {
5133 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005134
5135 // Arrays and functions decay.
5136 if (ExDeclType->isArrayType())
5137 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5138 else if (ExDeclType->isFunctionType())
5139 ExDeclType = Context.getPointerType(ExDeclType);
5140
5141 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5142 // The exception-declaration shall not denote a pointer or reference to an
5143 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005144 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005145 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005146 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005147 Invalid = true;
5148 }
Douglas Gregord308e622009-05-18 20:51:54 +00005149
Sebastian Redl4b07b292008-12-22 19:15:10 +00005150 QualType BaseType = ExDeclType;
5151 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005152 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005153 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005154 BaseType = Ptr->getPointeeType();
5155 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005156 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005157 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005158 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005159 BaseType = Ref->getPointeeType();
5160 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005161 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005162 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005163 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005164 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005165 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005166
Mike Stump1eb44332009-09-09 15:08:12 +00005167 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005168 RequireNonAbstractType(Loc, ExDeclType,
5169 diag::err_abstract_type_in_decl,
5170 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005171 Invalid = true;
5172
Douglas Gregord308e622009-05-18 20:51:54 +00005173 // FIXME: Need to test for ability to copy-construct and destroy the
5174 // exception variable.
5175
Sebastian Redl8351da02008-12-22 21:35:02 +00005176 // FIXME: Need to check for abstract classes.
5177
Mike Stump1eb44332009-09-09 15:08:12 +00005178 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005179 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005180
5181 if (Invalid)
5182 ExDecl->setInvalidDecl();
5183
5184 return ExDecl;
5185}
5186
5187/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5188/// handler.
5189Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005190 TypeSourceInfo *TInfo = 0;
5191 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005192
5193 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005194 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005195 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005196 // The scope should be freshly made just for us. There is just no way
5197 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005198 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005199 if (PrevDecl->isTemplateParameter()) {
5200 // Maybe we will complain about the shadowed template parameter.
5201 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005202 }
5203 }
5204
Chris Lattnereaaebc72009-04-25 08:06:05 +00005205 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005206 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5207 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005208 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005209 }
5210
John McCalla93c9342009-12-07 02:54:59 +00005211 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005212 D.getIdentifier(),
5213 D.getIdentifierLoc(),
5214 D.getDeclSpec().getSourceRange());
5215
Chris Lattnereaaebc72009-04-25 08:06:05 +00005216 if (Invalid)
5217 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005218
Sebastian Redl4b07b292008-12-22 19:15:10 +00005219 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005220 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005221 PushOnScopeChains(ExDecl, S);
5222 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005223 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005224
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005225 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005226 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005227}
Anders Carlssonfb311762009-03-14 00:25:26 +00005228
Mike Stump1eb44332009-09-09 15:08:12 +00005229Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005230 ExprArg assertexpr,
5231 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005232 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005233 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005234 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5235
Anders Carlssonc3082412009-03-14 00:33:21 +00005236 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5237 llvm::APSInt Value(32);
5238 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5239 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5240 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005241 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005242 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005243
Anders Carlssonc3082412009-03-14 00:33:21 +00005244 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005245 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005246 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005247 }
5248 }
Mike Stump1eb44332009-09-09 15:08:12 +00005249
Anders Carlsson77d81422009-03-15 17:35:16 +00005250 assertexpr.release();
5251 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005252 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005253 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005254
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005255 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005256 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005257}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005258
John McCalldd4a3b02009-09-16 22:47:08 +00005259/// Handle a friend type declaration. This works in tandem with
5260/// ActOnTag.
5261///
5262/// Notes on friend class templates:
5263///
5264/// We generally treat friend class declarations as if they were
5265/// declaring a class. So, for example, the elaborated type specifier
5266/// in a friend declaration is required to obey the restrictions of a
5267/// class-head (i.e. no typedefs in the scope chain), template
5268/// parameters are required to match up with simple template-ids, &c.
5269/// However, unlike when declaring a template specialization, it's
5270/// okay to refer to a template specialization without an empty
5271/// template parameter declaration, e.g.
5272/// friend class A<T>::B<unsigned>;
5273/// We permit this as a special case; if there are any template
5274/// parameters present at all, require proper matching, i.e.
5275/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005276Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005277 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005278 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005279
5280 assert(DS.isFriendSpecified());
5281 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5282
John McCalldd4a3b02009-09-16 22:47:08 +00005283 // Try to convert the decl specifier to a type. This works for
5284 // friend templates because ActOnTag never produces a ClassTemplateDecl
5285 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005286 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005287 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5288 if (TheDeclarator.isInvalidType())
5289 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005290
John McCalldd4a3b02009-09-16 22:47:08 +00005291 // This is definitely an error in C++98. It's probably meant to
5292 // be forbidden in C++0x, too, but the specification is just
5293 // poorly written.
5294 //
5295 // The problem is with declarations like the following:
5296 // template <T> friend A<T>::foo;
5297 // where deciding whether a class C is a friend or not now hinges
5298 // on whether there exists an instantiation of A that causes
5299 // 'foo' to equal C. There are restrictions on class-heads
5300 // (which we declare (by fiat) elaborated friend declarations to
5301 // be) that makes this tractable.
5302 //
5303 // FIXME: handle "template <> friend class A<T>;", which
5304 // is possibly well-formed? Who even knows?
5305 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5306 Diag(Loc, diag::err_tagless_friend_type_template)
5307 << DS.getSourceRange();
5308 return DeclPtrTy();
5309 }
5310
John McCall02cace72009-08-28 07:59:38 +00005311 // C++ [class.friend]p2:
5312 // An elaborated-type-specifier shall be used in a friend declaration
5313 // for a class.*
5314 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005315 // This is one of the rare places in Clang where it's legitimate to
5316 // ask about the "spelling" of the type.
5317 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5318 // If we evaluated the type to a record type, suggest putting
5319 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005320 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005321 RecordDecl *RD = RT->getDecl();
5322
5323 std::string InsertionText = std::string(" ") + RD->getKindName();
5324
John McCalle3af0232009-10-07 23:34:25 +00005325 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5326 << (unsigned) RD->getTagKind()
5327 << T
5328 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005329 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5330 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005331 return DeclPtrTy();
5332 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005333 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5334 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005335 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005336 }
5337 }
5338
John McCalle3af0232009-10-07 23:34:25 +00005339 // Enum types cannot be friends.
5340 if (T->getAs<EnumType>()) {
5341 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5342 << SourceRange(DS.getFriendSpecLoc());
5343 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005344 }
John McCall02cace72009-08-28 07:59:38 +00005345
John McCall02cace72009-08-28 07:59:38 +00005346 // C++98 [class.friend]p1: A friend of a class is a function
5347 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005348 // This is fixed in DR77, which just barely didn't make the C++03
5349 // deadline. It's also a very silly restriction that seriously
5350 // affects inner classes and which nobody else seems to implement;
5351 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005352
John McCalldd4a3b02009-09-16 22:47:08 +00005353 Decl *D;
5354 if (TempParams.size())
5355 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5356 TempParams.size(),
5357 (TemplateParameterList**) TempParams.release(),
5358 T.getTypePtr(),
5359 DS.getFriendSpecLoc());
5360 else
5361 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5362 DS.getFriendSpecLoc());
5363 D->setAccess(AS_public);
5364 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005365
John McCalldd4a3b02009-09-16 22:47:08 +00005366 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005367}
5368
John McCallbbbcdd92009-09-11 21:02:39 +00005369Sema::DeclPtrTy
5370Sema::ActOnFriendFunctionDecl(Scope *S,
5371 Declarator &D,
5372 bool IsDefinition,
5373 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005374 const DeclSpec &DS = D.getDeclSpec();
5375
5376 assert(DS.isFriendSpecified());
5377 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5378
5379 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005380 TypeSourceInfo *TInfo = 0;
5381 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005382
5383 // C++ [class.friend]p1
5384 // A friend of a class is a function or class....
5385 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005386 // It *doesn't* see through dependent types, which is correct
5387 // according to [temp.arg.type]p3:
5388 // If a declaration acquires a function type through a
5389 // type dependent on a template-parameter and this causes
5390 // a declaration that does not use the syntactic form of a
5391 // function declarator to have a function type, the program
5392 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005393 if (!T->isFunctionType()) {
5394 Diag(Loc, diag::err_unexpected_friend);
5395
5396 // It might be worthwhile to try to recover by creating an
5397 // appropriate declaration.
5398 return DeclPtrTy();
5399 }
5400
5401 // C++ [namespace.memdef]p3
5402 // - If a friend declaration in a non-local class first declares a
5403 // class or function, the friend class or function is a member
5404 // of the innermost enclosing namespace.
5405 // - The name of the friend is not found by simple name lookup
5406 // until a matching declaration is provided in that namespace
5407 // scope (either before or after the class declaration granting
5408 // friendship).
5409 // - If a friend function is called, its name may be found by the
5410 // name lookup that considers functions from namespaces and
5411 // classes associated with the types of the function arguments.
5412 // - When looking for a prior declaration of a class or a function
5413 // declared as a friend, scopes outside the innermost enclosing
5414 // namespace scope are not considered.
5415
John McCall02cace72009-08-28 07:59:38 +00005416 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5417 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005418 assert(Name);
5419
John McCall67d1a672009-08-06 02:15:43 +00005420 // The context we found the declaration in, or in which we should
5421 // create the declaration.
5422 DeclContext *DC;
5423
5424 // FIXME: handle local classes
5425
5426 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005427 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5428 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005429 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005430 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005431 DC = computeDeclContext(ScopeQual);
5432
5433 // FIXME: handle dependent contexts
5434 if (!DC) return DeclPtrTy();
5435
John McCall68263142009-11-18 22:49:29 +00005436 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005437
5438 // If searching in that context implicitly found a declaration in
5439 // a different context, treat it like it wasn't found at all.
5440 // TODO: better diagnostics for this case. Suggesting the right
5441 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005442 // FIXME: getRepresentativeDecl() is not right here at all
5443 if (Previous.empty() ||
5444 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005445 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005446 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5447 return DeclPtrTy();
5448 }
5449
5450 // C++ [class.friend]p1: A friend of a class is a function or
5451 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005452 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005453 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5454
John McCall67d1a672009-08-06 02:15:43 +00005455 // Otherwise walk out to the nearest namespace scope looking for matches.
5456 } else {
5457 // TODO: handle local class contexts.
5458
5459 DC = CurContext;
5460 while (true) {
5461 // Skip class contexts. If someone can cite chapter and verse
5462 // for this behavior, that would be nice --- it's what GCC and
5463 // EDG do, and it seems like a reasonable intent, but the spec
5464 // really only says that checks for unqualified existing
5465 // declarations should stop at the nearest enclosing namespace,
5466 // not that they should only consider the nearest enclosing
5467 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005468 while (DC->isRecord())
5469 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005470
John McCall68263142009-11-18 22:49:29 +00005471 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005472
5473 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005474 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005475 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005476
John McCall67d1a672009-08-06 02:15:43 +00005477 if (DC->isFileContext()) break;
5478 DC = DC->getParent();
5479 }
5480
5481 // C++ [class.friend]p1: A friend of a class is a function or
5482 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005483 // C++0x changes this for both friend types and functions.
5484 // Most C++ 98 compilers do seem to give an error here, so
5485 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005486 if (!Previous.empty() && DC->Equals(CurContext)
5487 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005488 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5489 }
5490
Douglas Gregor182ddf02009-09-28 00:08:27 +00005491 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005492 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005493 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5494 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5495 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005496 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005497 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5498 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005499 return DeclPtrTy();
5500 }
John McCall67d1a672009-08-06 02:15:43 +00005501 }
5502
Douglas Gregor182ddf02009-09-28 00:08:27 +00005503 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005504 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005505 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005506 IsDefinition,
5507 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005508 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005509
Douglas Gregor182ddf02009-09-28 00:08:27 +00005510 assert(ND->getDeclContext() == DC);
5511 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005512
John McCallab88d972009-08-31 22:39:49 +00005513 // Add the function declaration to the appropriate lookup tables,
5514 // adjusting the redeclarations list as necessary. We don't
5515 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005516 //
John McCallab88d972009-08-31 22:39:49 +00005517 // Also update the scope-based lookup if the target context's
5518 // lookup context is in lexical scope.
5519 if (!CurContext->isDependentContext()) {
5520 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005521 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005522 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005523 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005524 }
John McCall02cace72009-08-28 07:59:38 +00005525
5526 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005527 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005528 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005529 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005530 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005531
Douglas Gregor7557a132009-12-24 20:56:24 +00005532 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5533 FrD->setSpecialization(true);
5534
Douglas Gregor182ddf02009-09-28 00:08:27 +00005535 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005536}
5537
Chris Lattnerb28317a2009-03-28 19:18:32 +00005538void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005539 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005540
Chris Lattnerb28317a2009-03-28 19:18:32 +00005541 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005542 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5543 if (!Fn) {
5544 Diag(DelLoc, diag::err_deleted_non_function);
5545 return;
5546 }
5547 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5548 Diag(DelLoc, diag::err_deleted_decl_not_first);
5549 Diag(Prev->getLocation(), diag::note_previous_declaration);
5550 // If the declaration wasn't the first, we delete the function anyway for
5551 // recovery.
5552 }
5553 Fn->setDeleted();
5554}
Sebastian Redl13e88542009-04-27 21:33:24 +00005555
5556static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5557 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5558 ++CI) {
5559 Stmt *SubStmt = *CI;
5560 if (!SubStmt)
5561 continue;
5562 if (isa<ReturnStmt>(SubStmt))
5563 Self.Diag(SubStmt->getSourceRange().getBegin(),
5564 diag::err_return_in_constructor_handler);
5565 if (!isa<Expr>(SubStmt))
5566 SearchForReturnInStmt(Self, SubStmt);
5567 }
5568}
5569
5570void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5571 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5572 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5573 SearchForReturnInStmt(*this, Handler);
5574 }
5575}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005576
Mike Stump1eb44332009-09-09 15:08:12 +00005577bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005578 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005579 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5580 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005581
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005582 if (Context.hasSameType(NewTy, OldTy))
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005583 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005584
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005585 // Check if the return types are covariant
5586 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005587
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005588 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005589 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5590 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005591 NewClassTy = NewPT->getPointeeType();
5592 OldClassTy = OldPT->getPointeeType();
5593 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005594 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5595 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5596 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5597 NewClassTy = NewRT->getPointeeType();
5598 OldClassTy = OldRT->getPointeeType();
5599 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005600 }
5601 }
Mike Stump1eb44332009-09-09 15:08:12 +00005602
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005603 // The return types aren't either both pointers or references to a class type.
5604 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005605 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005606 diag::err_different_return_type_for_overriding_virtual_function)
5607 << New->getDeclName() << NewTy << OldTy;
5608 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005609
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005610 return true;
5611 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005612
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005613 // C++ [class.virtual]p6:
5614 // If the return type of D::f differs from the return type of B::f, the
5615 // class type in the return type of D::f shall be complete at the point of
5616 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005617 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5618 if (!RT->isBeingDefined() &&
5619 RequireCompleteType(New->getLocation(), NewClassTy,
5620 PDiag(diag::err_covariant_return_incomplete)
5621 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005622 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005623 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005624
Douglas Gregora4923eb2009-11-16 21:35:15 +00005625 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005626 // Check if the new class derives from the old class.
5627 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5628 Diag(New->getLocation(),
5629 diag::err_covariant_return_not_derived)
5630 << New->getDeclName() << NewTy << OldTy;
5631 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5632 return true;
5633 }
Mike Stump1eb44332009-09-09 15:08:12 +00005634
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005635 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005636 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005637 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5638 // FIXME: Should this point to the return type?
5639 New->getLocation(), SourceRange(), New->getDeclName())) {
5640 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5641 return true;
5642 }
5643 }
Mike Stump1eb44332009-09-09 15:08:12 +00005644
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005645 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005646 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005647 Diag(New->getLocation(),
5648 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005649 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005650 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5651 return true;
5652 };
Mike Stump1eb44332009-09-09 15:08:12 +00005653
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005654
5655 // The new class type must have the same or less qualifiers as the old type.
5656 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5657 Diag(New->getLocation(),
5658 diag::err_covariant_return_type_class_type_more_qualified)
5659 << New->getDeclName() << NewTy << OldTy;
5660 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5661 return true;
5662 };
Mike Stump1eb44332009-09-09 15:08:12 +00005663
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005664 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005665}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005666
Sean Huntbbd37c62009-11-21 08:43:09 +00005667bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5668 const CXXMethodDecl *Old)
5669{
5670 if (Old->hasAttr<FinalAttr>()) {
5671 Diag(New->getLocation(), diag::err_final_function_overridden)
5672 << New->getDeclName();
5673 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5674 return true;
5675 }
5676
5677 return false;
5678}
5679
Douglas Gregor4ba31362009-12-01 17:24:26 +00005680/// \brief Mark the given method pure.
5681///
5682/// \param Method the method to be marked pure.
5683///
5684/// \param InitRange the source range that covers the "0" initializer.
5685bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5686 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5687 Method->setPure();
5688
5689 // A class is abstract if at least one function is pure virtual.
5690 Method->getParent()->setAbstract(true);
5691 return false;
5692 }
5693
5694 if (!Method->isInvalidDecl())
5695 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5696 << Method->getDeclName() << InitRange;
5697 return true;
5698}
5699
John McCall731ad842009-12-19 09:28:58 +00005700/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5701/// an initializer for the out-of-line declaration 'Dcl'. The scope
5702/// is a fresh scope pushed for just this purpose.
5703///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005704/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5705/// static data member of class X, names should be looked up in the scope of
5706/// class X.
5707void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005708 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005709 Decl *D = Dcl.getAs<Decl>();
5710 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005711
John McCall731ad842009-12-19 09:28:58 +00005712 // We should only get called for declarations with scope specifiers, like:
5713 // int foo::bar;
5714 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005715 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005716}
5717
5718/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005719/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005720void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005721 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005722 Decl *D = Dcl.getAs<Decl>();
5723 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005724
John McCall731ad842009-12-19 09:28:58 +00005725 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005726 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005727}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005728
5729/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5730/// C++ if/switch/while/for statement.
5731/// e.g: "if (int x = f()) {...}"
5732Action::DeclResult
5733Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5734 // C++ 6.4p2:
5735 // The declarator shall not specify a function or an array.
5736 // The type-specifier-seq shall not contain typedef and shall not declare a
5737 // new class or enumeration.
5738 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5739 "Parser allowed 'typedef' as storage class of condition decl.");
5740
John McCalla93c9342009-12-07 02:54:59 +00005741 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005742 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005743 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005744
5745 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5746 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5747 // would be created and CXXConditionDeclExpr wants a VarDecl.
5748 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5749 << D.getSourceRange();
5750 return DeclResult();
5751 } else if (OwnedTag && OwnedTag->isDefinition()) {
5752 // The type-specifier-seq shall not declare a new class or enumeration.
5753 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5754 }
5755
5756 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5757 if (!Dcl)
5758 return DeclResult();
5759
5760 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5761 VD->setDeclaredInCondition(true);
5762 return Dcl;
5763}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005764
Anders Carlssond6a637f2009-12-07 08:24:59 +00005765void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5766 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005767 // Ignore dependent types.
5768 if (MD->isDependentContext())
5769 return;
5770
5771 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005772
5773 // Ignore classes without a vtable.
5774 if (!RD->isDynamicClass())
5775 return;
5776
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005777 // Ignore declarations that are not definitions.
5778 if (!MD->isThisDeclarationADefinition())
Anders Carlssond6a637f2009-12-07 08:24:59 +00005779 return;
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005780
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005781 if (isa<CXXConstructorDecl>(MD)) {
5782 switch (MD->getParent()->getTemplateSpecializationKind()) {
5783 case TSK_Undeclared:
5784 case TSK_ExplicitSpecialization:
5785 // Classes that aren't instantiations of templates don't need their
5786 // virtual methods marked until we see the definition of the key
5787 // function.
5788 return;
5789
5790 case TSK_ImplicitInstantiation:
5791 case TSK_ExplicitInstantiationDeclaration:
5792 case TSK_ExplicitInstantiationDefinition:
5793 // This is a constructor of a class template; mark all of the virtual
5794 // members as referenced to ensure that they get instantiatied.
5795 break;
5796 }
5797 } else if (!MD->isOutOfLine()) {
5798 // Consider only out-of-line definitions of member functions. When we see
5799 // an inline definition, it's too early to compute the key function.
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005800 return;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005801 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5802 // If this is not the key function, we don't need to mark virtual members.
5803 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5804 return;
5805 } else {
5806 // The class has no key function, so we've already noted that we need to
5807 // mark the virtual members of this class.
5808 return;
5809 }
5810
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005811 // We will need to mark all of the virtual members as referenced to build the
5812 // vtable.
5813 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Anders Carlssond6a637f2009-12-07 08:24:59 +00005814}
5815
5816bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5817 if (ClassesWithUnmarkedVirtualMembers.empty())
5818 return false;
5819
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005820 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5821 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5822 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5823 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005824 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005825 }
5826
Anders Carlssond6a637f2009-12-07 08:24:59 +00005827 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005828}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005829
5830void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5831 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5832 e = RD->method_end(); i != e; ++i) {
5833 CXXMethodDecl *MD = *i;
5834
5835 // C++ [basic.def.odr]p2:
5836 // [...] A virtual member function is used if it is not pure. [...]
5837 if (MD->isVirtual() && !MD->isPure())
5838 MarkDeclarationReferenced(Loc, MD);
5839 }
5840}
5841