blob: a062724ee4125f461b9ff14955cb0ca07b7f697b [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
Douglas Gregore13ad832010-02-12 07:32:17 +0000359 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000360 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361
Douglas Gregorcda9c672009-02-16 17:45:42 +0000362 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000363}
364
365/// CheckCXXDefaultArguments - Verify that the default arguments for a
366/// function declaration are well-formed according to C++
367/// [dcl.fct.default].
368void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
369 unsigned NumParams = FD->getNumParams();
370 unsigned p;
371
372 // Find first parameter with a default argument
373 for (p = 0; p < NumParams; ++p) {
374 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000375 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376 break;
377 }
378
379 // C++ [dcl.fct.default]p4:
380 // In a given function declaration, all parameters
381 // subsequent to a parameter with a default argument shall
382 // have default arguments supplied in this or previous
383 // declarations. A default argument shall not be redefined
384 // by a later declaration (not even to the same value).
385 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000386 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000387 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000388 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000389 if (Param->isInvalidDecl())
390 /* We already complained about this parameter. */;
391 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000392 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000393 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000394 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000395 else
Mike Stump1eb44332009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 LastMissingDefaultArg = p;
400 }
401 }
402
403 if (LastMissingDefaultArg > 0) {
404 // Some default arguments were missing. Clear out all of the
405 // default arguments up to (and including) the last missing
406 // default argument, so that we leave the function parameters
407 // in a semantically valid state.
408 for (p = 0; p <= LastMissingDefaultArg; ++p) {
409 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000410 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000411 if (!Param->hasUnparsedDefaultArg())
412 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000413 Param->setDefaultArg(0);
414 }
415 }
416 }
417}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000418
Douglas Gregorb48fe382008-10-31 09:07:45 +0000419/// isCurrentClassName - Determine whether the identifier II is the
420/// name of the class type currently being defined. In the case of
421/// nested classes, this will only return true if II is the name of
422/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000423bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
424 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000425 assert(getLangOptions().CPlusPlus && "No class names in C!");
426
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000427 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000428 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000429 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431 } else
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000434 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000435 return &II == CurDecl->getIdentifier();
436 else
437 return false;
438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446 SourceRange SpecifierRange,
447 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000448 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000449 SourceLocation BaseLoc) {
450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460 Class->getTagKind() == RecordDecl::TK_class,
461 Access, BaseType);
462
463 // Base specifiers must be record types.
464 if (!BaseType->isRecordType()) {
465 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
466 return 0;
467 }
468
469 // C++ [class.union]p1:
470 // A union shall not be used as a base class.
471 if (BaseType->isUnionType()) {
472 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
473 return 0;
474 }
475
476 // C++ [class.derived]p2:
477 // The class-name in a base-specifier shall not be an incompletely
478 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000479 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000480 PDiag(diag::err_incomplete_base_class)
481 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 return 0;
483
Eli Friedman1d954f62009-08-15 21:55:26 +0000484 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000485 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000487 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000489 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
490 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000491
Sean Huntbbd37c62009-11-21 08:43:09 +0000492 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000495 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
496 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000497 return 0;
498 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499
Eli Friedmand0137332009-12-05 23:03:49 +0000500 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000501
502 // Create the base specifier.
503 // FIXME: Allocate via ASTContext?
504 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
505 Class->getTagKind() == RecordDecl::TK_class,
506 Access, BaseType);
507}
508
509void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
510 const CXXRecordDecl *BaseClass,
511 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000512 // A class with a non-empty base class is not empty.
513 // FIXME: Standard ref?
514 if (!BaseClass->isEmpty())
515 Class->setEmpty(false);
516
517 // C++ [class.virtual]p1:
518 // A class that [...] inherits a virtual function is called a polymorphic
519 // class.
520 if (BaseClass->isPolymorphic())
521 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000522
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523 // C++ [dcl.init.aggr]p1:
524 // An aggregate is [...] a class with [...] no base classes [...].
525 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000526
527 // C++ [class]p4:
528 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529 Class->setPOD(false);
530
Anders Carlsson51f94042009-12-03 17:49:57 +0000531 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000532 // C++ [class.ctor]p5:
533 // A constructor is trivial if its class has no virtual base classes.
534 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000535
536 // C++ [class.copy]p6:
537 // A copy constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialCopyConstructor(false);
539
540 // C++ [class.copy]p11:
541 // A copy assignment operator is trivial if its class has no virtual
542 // base classes.
543 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000544
545 // C++0x [meta.unary.prop] is_empty:
546 // T is a class type, but not a union type, with ... no virtual base
547 // classes
548 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000549 } else {
550 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000551 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000552 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000553 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000554 Class->setHasTrivialConstructor(false);
555
556 // C++ [class.copy]p6:
557 // A copy constructor is trivial if all the direct base classes of its
558 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000560 Class->setHasTrivialCopyConstructor(false);
561
562 // C++ [class.copy]p11:
563 // A copy assignment operator is trivial if all the direct base classes
564 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000567 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000568
569 // C++ [class.ctor]p3:
570 // A destructor is trivial if all the direct base classes of its class
571 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000572 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000573 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574}
575
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000576/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
577/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000578/// example:
579/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000580/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000581Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000582Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000583 bool Virtual, AccessSpecifier Access,
584 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000585 if (!classdecl)
586 return true;
587
Douglas Gregor40808ce2009-03-09 23:48:35 +0000588 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000590 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
592 Virtual, Access,
593 BaseType, BaseLoc))
594 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000597}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599/// \brief Performs the actual work of attaching the given base class
600/// specifiers to a C++ class.
601bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
602 unsigned NumBases) {
603 if (NumBases == 0)
604 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605
606 // Used to keep track of which base types we have already seen, so
607 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000608 // that the key is always the unqualified canonical type of the base
609 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
611
612 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000616 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000618 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 if (KnownBaseTypes[NewBaseType]) {
621 // C++ [class.mi]p3:
622 // A class shall not be specified as a direct base class of a
623 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000625 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000626 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000628
629 // Delete the duplicate base class specifier; we're going to
630 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000631 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632
633 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000634 } else {
635 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636 KnownBaseTypes[NewBaseType] = Bases[idx];
637 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 }
639 }
640
641 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000642 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000643
644 // Delete the remaining (good) base class specifiers, since their
645 // data has been copied into the CXXRecordDecl.
646 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000647 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648
649 return Invalid;
650}
651
652/// ActOnBaseSpecifiers - Attach the given base specifiers to the
653/// class, after checking whether there are any duplicate base
654/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000655void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000656 unsigned NumBases) {
657 if (!ClassDecl || !Bases || !NumBases)
658 return;
659
660 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000661 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000663}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000664
Douglas Gregora8f32e02009-10-06 17:59:45 +0000665/// \brief Determine whether the type \p Derived is a C++ class that is
666/// derived from the type \p Base.
667bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
668 if (!getLangOptions().CPlusPlus)
669 return false;
670
671 const RecordType *DerivedRT = Derived->getAs<RecordType>();
672 if (!DerivedRT)
673 return false;
674
675 const RecordType *BaseRT = Base->getAs<RecordType>();
676 if (!BaseRT)
677 return false;
678
679 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
680 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall86ff3082010-02-04 22:26:26 +0000681 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
682 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000683}
684
685/// \brief Determine whether the type \p Derived is a C++ class that is
686/// derived from the type \p Base.
687bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
688 if (!getLangOptions().CPlusPlus)
689 return false;
690
691 const RecordType *DerivedRT = Derived->getAs<RecordType>();
692 if (!DerivedRT)
693 return false;
694
695 const RecordType *BaseRT = Base->getAs<RecordType>();
696 if (!BaseRT)
697 return false;
698
699 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
700 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
701 return DerivedRD->isDerivedFrom(BaseRD, Paths);
702}
703
704/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
705/// conversion (where Derived and Base are class types) is
706/// well-formed, meaning that the conversion is unambiguous (and
707/// that all of the base classes are accessible). Returns true
708/// and emits a diagnostic if the code is ill-formed, returns false
709/// otherwise. Loc is the location where this routine should point to
710/// if there is an error, and Range is the source range to highlight
711/// if there is an error.
712bool
713Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000714 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000715 unsigned AmbigiousBaseConvID,
716 SourceLocation Loc, SourceRange Range,
717 DeclarationName Name) {
718 // First, determine whether the path from Derived to Base is
719 // ambiguous. This is slightly more expensive than checking whether
720 // the Derived to Base conversion exists, because here we need to
721 // explore multiple paths to determine if there is an ambiguity.
722 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
723 /*DetectVirtual=*/false);
724 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
725 assert(DerivationOkay &&
726 "Can only be used with a derived-to-base conversion");
727 (void)DerivationOkay;
728
729 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000730 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000731 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000732
Douglas Gregora8f32e02009-10-06 17:59:45 +0000733 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000734 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
735 Base, Derived, Paths.front(),
736 /*force*/ false,
737 /*unprivileged*/ false,
738 ADK)) {
739 case AR_accessible: return false;
740 case AR_inaccessible: return true;
741 case AR_dependent: return false;
742 case AR_delayed: return false;
743 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000744 }
745
746 // We know that the derived-to-base conversion is ambiguous, and
747 // we're going to produce a diagnostic. Perform the derived-to-base
748 // search just one more time to compute all of the possible paths so
749 // that we can print them out. This is more expensive than any of
750 // the previous derived-to-base checks we've done, but at this point
751 // performance isn't as much of an issue.
752 Paths.clear();
753 Paths.setRecordingPaths(true);
754 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
755 assert(StillOkay && "Can only be used with a derived-to-base conversion");
756 (void)StillOkay;
757
758 // Build up a textual representation of the ambiguous paths, e.g.,
759 // D -> B -> A, that will be used to illustrate the ambiguous
760 // conversions in the diagnostic. We only print one of the paths
761 // to each base class subobject.
762 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
763
764 Diag(Loc, AmbigiousBaseConvID)
765 << Derived << Base << PathDisplayStr << Range << Name;
766 return true;
767}
768
769bool
770Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000771 SourceLocation Loc, SourceRange Range,
772 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000773 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000774 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000775 diag::err_ambiguous_derived_to_base_conv,
776 Loc, Range, DeclarationName());
777}
778
779
780/// @brief Builds a string representing ambiguous paths from a
781/// specific derived class to different subobjects of the same base
782/// class.
783///
784/// This function builds a string that can be used in error messages
785/// to show the different paths that one can take through the
786/// inheritance hierarchy to go from the derived class to different
787/// subobjects of a base class. The result looks something like this:
788/// @code
789/// struct D -> struct B -> struct A
790/// struct D -> struct C -> struct A
791/// @endcode
792std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
793 std::string PathDisplayStr;
794 std::set<unsigned> DisplayedPaths;
795 for (CXXBasePaths::paths_iterator Path = Paths.begin();
796 Path != Paths.end(); ++Path) {
797 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
798 // We haven't displayed a path to this particular base
799 // class subobject yet.
800 PathDisplayStr += "\n ";
801 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
802 for (CXXBasePath::const_iterator Element = Path->begin();
803 Element != Path->end(); ++Element)
804 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
805 }
806 }
807
808 return PathDisplayStr;
809}
810
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000811//===----------------------------------------------------------------------===//
812// C++ class member Handling
813//===----------------------------------------------------------------------===//
814
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000815/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
816/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
817/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000818/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000819Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000820Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000821 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000822 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
823 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000824 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000825 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000826 Expr *BitWidth = static_cast<Expr*>(BW);
827 Expr *Init = static_cast<Expr*>(InitExpr);
828 SourceLocation Loc = D.getIdentifierLoc();
829
Sebastian Redl669d5d72008-11-14 23:42:31 +0000830 bool isFunc = D.isFunctionDeclarator();
831
John McCall67d1a672009-08-06 02:15:43 +0000832 assert(!DS.isFriendSpecified());
833
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000834 // C++ 9.2p6: A member shall not be declared to have automatic storage
835 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000836 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
837 // data members and cannot be applied to names declared const or static,
838 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000839 switch (DS.getStorageClassSpec()) {
840 case DeclSpec::SCS_unspecified:
841 case DeclSpec::SCS_typedef:
842 case DeclSpec::SCS_static:
843 // FALL THROUGH.
844 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000845 case DeclSpec::SCS_mutable:
846 if (isFunc) {
847 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000848 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000849 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000850 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Sebastian Redla11f42f2008-11-17 23:24:37 +0000852 // FIXME: It would be nicer if the keyword was ignored only for this
853 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000854 D.getMutableDeclSpec().ClearStorageClassSpecs();
855 } else {
856 QualType T = GetTypeForDeclarator(D, S);
857 diag::kind err = static_cast<diag::kind>(0);
858 if (T->isReferenceType())
859 err = diag::err_mutable_reference;
860 else if (T.isConstQualified())
861 err = diag::err_mutable_const;
862 if (err != 0) {
863 if (DS.getStorageClassSpecLoc().isValid())
864 Diag(DS.getStorageClassSpecLoc(), err);
865 else
866 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000867 // FIXME: It would be nicer if the keyword was ignored only for this
868 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000869 D.getMutableDeclSpec().ClearStorageClassSpecs();
870 }
871 }
872 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000873 default:
874 if (DS.getStorageClassSpecLoc().isValid())
875 Diag(DS.getStorageClassSpecLoc(),
876 diag::err_storageclass_invalid_for_member);
877 else
878 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
879 D.getMutableDeclSpec().ClearStorageClassSpecs();
880 }
881
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000882 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000883 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000884 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000885 // Check also for this case:
886 //
887 // typedef int f();
888 // f a;
889 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000890 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000891 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000892 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893
Sebastian Redl669d5d72008-11-14 23:42:31 +0000894 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
895 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000896 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000897
898 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000899 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000900 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000901 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
902 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000903 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000904 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000905 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000906 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000907 if (!Member) {
908 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000909 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000910 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000911
912 // Non-instance-fields can't have a bitfield.
913 if (BitWidth) {
914 if (Member->isInvalidDecl()) {
915 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000916 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000917 // C++ 9.6p3: A bit-field shall not be a static member.
918 // "static member 'A' cannot be a bit-field"
919 Diag(Loc, diag::err_static_not_bitfield)
920 << Name << BitWidth->getSourceRange();
921 } else if (isa<TypedefDecl>(Member)) {
922 // "typedef member 'x' cannot be a bit-field"
923 Diag(Loc, diag::err_typedef_not_bitfield)
924 << Name << BitWidth->getSourceRange();
925 } else {
926 // A function typedef ("typedef int f(); f a;").
927 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
928 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000929 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000930 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner8b963ef2009-03-05 23:01:03 +0000933 DeleteExpr(BitWidth);
934 BitWidth = 0;
935 Member->setInvalidDecl();
936 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000937
938 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregor37b372b2009-08-20 22:52:58 +0000940 // If we have declared a member function template, set the access of the
941 // templated declaration as well.
942 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
943 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000944 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000945
Douglas Gregor10bd3682008-11-17 22:58:34 +0000946 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947
Douglas Gregor021c3b32009-03-11 23:00:04 +0000948 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000949 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000950 if (Deleted) // FIXME: Source location is not very good.
951 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000952
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000953 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000954 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000955 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000956 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000957 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000958}
959
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000960/// \brief Find the direct and/or virtual base specifiers that
961/// correspond to the given base type, for use in base initialization
962/// within a constructor.
963static bool FindBaseInitializer(Sema &SemaRef,
964 CXXRecordDecl *ClassDecl,
965 QualType BaseType,
966 const CXXBaseSpecifier *&DirectBaseSpec,
967 const CXXBaseSpecifier *&VirtualBaseSpec) {
968 // First, check for a direct base class.
969 DirectBaseSpec = 0;
970 for (CXXRecordDecl::base_class_const_iterator Base
971 = ClassDecl->bases_begin();
972 Base != ClassDecl->bases_end(); ++Base) {
973 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
974 // We found a direct base of this type. That's what we're
975 // initializing.
976 DirectBaseSpec = &*Base;
977 break;
978 }
979 }
980
981 // Check for a virtual base class.
982 // FIXME: We might be able to short-circuit this if we know in advance that
983 // there are no virtual bases.
984 VirtualBaseSpec = 0;
985 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
986 // We haven't found a base yet; search the class hierarchy for a
987 // virtual base class.
988 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
989 /*DetectVirtual=*/false);
990 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
991 BaseType, Paths)) {
992 for (CXXBasePaths::paths_iterator Path = Paths.begin();
993 Path != Paths.end(); ++Path) {
994 if (Path->back().Base->isVirtual()) {
995 VirtualBaseSpec = Path->back().Base;
996 break;
997 }
998 }
999 }
1000 }
1001
1002 return DirectBaseSpec || VirtualBaseSpec;
1003}
1004
Douglas Gregor7ad83902008-11-05 04:29:56 +00001005/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001006Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001007Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001008 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001009 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001010 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001011 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001012 SourceLocation IdLoc,
1013 SourceLocation LParenLoc,
1014 ExprTy **Args, unsigned NumArgs,
1015 SourceLocation *CommaLocs,
1016 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001017 if (!ConstructorD)
1018 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001020 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001021
1022 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001023 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001024 if (!Constructor) {
1025 // The user wrote a constructor initializer on a function that is
1026 // not a C++ constructor. Ignore the error for now, because we may
1027 // have more member initializers coming; we'll diagnose it just
1028 // once in ActOnMemInitializers.
1029 return true;
1030 }
1031
1032 CXXRecordDecl *ClassDecl = Constructor->getParent();
1033
1034 // C++ [class.base.init]p2:
1035 // Names in a mem-initializer-id are looked up in the scope of the
1036 // constructor’s class and, if not found in that scope, are looked
1037 // up in the scope containing the constructor’s
1038 // definition. [Note: if the constructor’s class contains a member
1039 // with the same name as a direct or virtual base class of the
1040 // class, a mem-initializer-id naming the member or base class and
1041 // composed of a single identifier refers to the class member. A
1042 // mem-initializer-id for the hidden base class may be specified
1043 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001044 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001045 // Look for a member, first.
1046 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001047 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001048 = ClassDecl->lookup(MemberOrBase);
1049 if (Result.first != Result.second)
1050 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001051
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001052 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001053
Eli Friedman59c04372009-07-29 19:44:27 +00001054 if (Member)
1055 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001056 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001057 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001058 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001059 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001060 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001061
1062 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001063 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001064 } else {
1065 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1066 LookupParsedName(R, S, &SS);
1067
1068 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1069 if (!TyD) {
1070 if (R.isAmbiguous()) return true;
1071
Douglas Gregor7a886e12010-01-19 06:46:48 +00001072 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1073 bool NotUnknownSpecialization = false;
1074 DeclContext *DC = computeDeclContext(SS, false);
1075 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1076 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1077
1078 if (!NotUnknownSpecialization) {
1079 // When the scope specifier can refer to a member of an unknown
1080 // specialization, we take it as a type name.
1081 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1082 *MemberOrBase, SS.getRange());
1083 R.clear();
1084 }
1085 }
1086
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001087 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001088 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001089 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1090 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1091 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1092 // We have found a non-static data member with a similar
1093 // name to what was typed; complain and initialize that
1094 // member.
1095 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1096 << MemberOrBase << true << R.getLookupName()
1097 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1098 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001099 Diag(Member->getLocation(), diag::note_previous_decl)
1100 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001101
1102 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1103 LParenLoc, RParenLoc);
1104 }
1105 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1106 const CXXBaseSpecifier *DirectBaseSpec;
1107 const CXXBaseSpecifier *VirtualBaseSpec;
1108 if (FindBaseInitializer(*this, ClassDecl,
1109 Context.getTypeDeclType(Type),
1110 DirectBaseSpec, VirtualBaseSpec)) {
1111 // We have found a direct or virtual base class with a
1112 // similar name to what was typed; complain and initialize
1113 // that base class.
1114 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1115 << MemberOrBase << false << R.getLookupName()
1116 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1117 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001118
1119 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1120 : VirtualBaseSpec;
1121 Diag(BaseSpec->getSourceRange().getBegin(),
1122 diag::note_base_class_specified_here)
1123 << BaseSpec->getType()
1124 << BaseSpec->getSourceRange();
1125
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001126 TyD = Type;
1127 }
1128 }
1129 }
1130
Douglas Gregor7a886e12010-01-19 06:46:48 +00001131 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001132 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1133 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1134 return true;
1135 }
John McCall2b194412009-12-21 10:41:20 +00001136 }
1137
Douglas Gregor7a886e12010-01-19 06:46:48 +00001138 if (BaseType.isNull()) {
1139 BaseType = Context.getTypeDeclType(TyD);
1140 if (SS.isSet()) {
1141 NestedNameSpecifier *Qualifier =
1142 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001143
Douglas Gregor7a886e12010-01-19 06:46:48 +00001144 // FIXME: preserve source range information
1145 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1146 }
John McCall2b194412009-12-21 10:41:20 +00001147 }
1148 }
Mike Stump1eb44332009-09-09 15:08:12 +00001149
John McCalla93c9342009-12-07 02:54:59 +00001150 if (!TInfo)
1151 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001152
John McCalla93c9342009-12-07 02:54:59 +00001153 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001154 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001155}
1156
John McCallb4190042009-11-04 23:02:40 +00001157/// Checks an initializer expression for use of uninitialized fields, such as
1158/// containing the field that is being initialized. Returns true if there is an
1159/// uninitialized field was used an updates the SourceLocation parameter; false
1160/// otherwise.
1161static bool InitExprContainsUninitializedFields(const Stmt* S,
1162 const FieldDecl* LhsField,
1163 SourceLocation* L) {
1164 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1165 if (ME) {
1166 const NamedDecl* RhsField = ME->getMemberDecl();
1167 if (RhsField == LhsField) {
1168 // Initializing a field with itself. Throw a warning.
1169 // But wait; there are exceptions!
1170 // Exception #1: The field may not belong to this record.
1171 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1172 const Expr* base = ME->getBase();
1173 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1174 // Even though the field matches, it does not belong to this record.
1175 return false;
1176 }
1177 // None of the exceptions triggered; return true to indicate an
1178 // uninitialized field was used.
1179 *L = ME->getMemberLoc();
1180 return true;
1181 }
1182 }
1183 bool found = false;
1184 for (Stmt::const_child_iterator it = S->child_begin();
1185 it != S->child_end() && found == false;
1186 ++it) {
1187 if (isa<CallExpr>(S)) {
1188 // Do not descend into function calls or constructors, as the use
1189 // of an uninitialized field may be valid. One would have to inspect
1190 // the contents of the function/ctor to determine if it is safe or not.
1191 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1192 // may be safe, depending on what the function/ctor does.
1193 continue;
1194 }
1195 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1196 }
1197 return found;
1198}
1199
Eli Friedman59c04372009-07-29 19:44:27 +00001200Sema::MemInitResult
1201Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1202 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001203 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001204 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001205 // Diagnose value-uses of fields to initialize themselves, e.g.
1206 // foo(foo)
1207 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001208 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001209 for (unsigned i = 0; i < NumArgs; ++i) {
1210 SourceLocation L;
1211 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1212 // FIXME: Return true in the case when other fields are used before being
1213 // uninitialized. For example, let this field be the i'th field. When
1214 // initializing the i'th field, throw a warning if any of the >= i'th
1215 // fields are used, as they are not yet initialized.
1216 // Right now we are only handling the case where the i'th field uses
1217 // itself in its initializer.
1218 Diag(L, diag::warn_field_is_uninit);
1219 }
1220 }
1221
Eli Friedman59c04372009-07-29 19:44:27 +00001222 bool HasDependentArg = false;
1223 for (unsigned i = 0; i < NumArgs; i++)
1224 HasDependentArg |= Args[i]->isTypeDependent();
1225
Eli Friedman59c04372009-07-29 19:44:27 +00001226 QualType FieldType = Member->getType();
1227 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1228 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001229 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001230 if (FieldType->isDependentType() || HasDependentArg) {
1231 // Can't check initialization for a member of dependent type or when
1232 // any of the arguments are type-dependent expressions.
1233 OwningExprResult Init
1234 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1235 RParenLoc));
1236
1237 // Erase any temporaries within this evaluation context; we're not
1238 // going to track them in the AST, since we'll be rebuilding the
1239 // ASTs during template instantiation.
1240 ExprTemporaries.erase(
1241 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1242 ExprTemporaries.end());
1243
1244 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1245 LParenLoc,
1246 Init.takeAs<Expr>(),
1247 RParenLoc);
1248
Douglas Gregor7ad83902008-11-05 04:29:56 +00001249 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001250
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001251 if (Member->isInvalidDecl())
1252 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001253
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001254 // Initialize the member.
1255 InitializedEntity MemberEntity =
1256 InitializedEntity::InitializeMember(Member, 0);
1257 InitializationKind Kind =
1258 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1259
1260 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1261
1262 OwningExprResult MemberInit =
1263 InitSeq.Perform(*this, MemberEntity, Kind,
1264 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1265 if (MemberInit.isInvalid())
1266 return true;
1267
1268 // C++0x [class.base.init]p7:
1269 // The initialization of each base and member constitutes a
1270 // full-expression.
1271 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1272 if (MemberInit.isInvalid())
1273 return true;
1274
1275 // If we are in a dependent context, template instantiation will
1276 // perform this type-checking again. Just save the arguments that we
1277 // received in a ParenListExpr.
1278 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1279 // of the information that we have about the member
1280 // initializer. However, deconstructing the ASTs is a dicey process,
1281 // and this approach is far more likely to get the corner cases right.
1282 if (CurContext->isDependentContext()) {
1283 // Bump the reference count of all of the arguments.
1284 for (unsigned I = 0; I != NumArgs; ++I)
1285 Args[I]->Retain();
1286
1287 OwningExprResult Init
1288 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1289 RParenLoc));
1290 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1291 LParenLoc,
1292 Init.takeAs<Expr>(),
1293 RParenLoc);
1294 }
1295
Douglas Gregor802ab452009-12-02 22:36:29 +00001296 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001297 LParenLoc,
1298 MemberInit.takeAs<Expr>(),
1299 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001300}
1301
1302Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001303Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001304 Expr **Args, unsigned NumArgs,
1305 SourceLocation LParenLoc, SourceLocation RParenLoc,
1306 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001307 bool HasDependentArg = false;
1308 for (unsigned i = 0; i < NumArgs; i++)
1309 HasDependentArg |= Args[i]->isTypeDependent();
1310
John McCalla93c9342009-12-07 02:54:59 +00001311 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001312 if (BaseType->isDependentType() || HasDependentArg) {
1313 // Can't check initialization for a base of dependent type or when
1314 // any of the arguments are type-dependent expressions.
1315 OwningExprResult BaseInit
1316 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1317 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001318
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001319 // Erase any temporaries within this evaluation context; we're not
1320 // going to track them in the AST, since we'll be rebuilding the
1321 // ASTs during template instantiation.
1322 ExprTemporaries.erase(
1323 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1324 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001326 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1327 LParenLoc,
1328 BaseInit.takeAs<Expr>(),
1329 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001330 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001331
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001332 if (!BaseType->isRecordType())
1333 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1334 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1335
1336 // C++ [class.base.init]p2:
1337 // [...] Unless the mem-initializer-id names a nonstatic data
1338 // member of the constructor’s class or a direct or virtual base
1339 // of that class, the mem-initializer is ill-formed. A
1340 // mem-initializer-list can initialize a base class using any
1341 // name that denotes that base class type.
1342
1343 // Check for direct and virtual base classes.
1344 const CXXBaseSpecifier *DirectBaseSpec = 0;
1345 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1346 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1347 VirtualBaseSpec);
1348
1349 // C++ [base.class.init]p2:
1350 // If a mem-initializer-id is ambiguous because it designates both
1351 // a direct non-virtual base class and an inherited virtual base
1352 // class, the mem-initializer is ill-formed.
1353 if (DirectBaseSpec && VirtualBaseSpec)
1354 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1355 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1356 // C++ [base.class.init]p2:
1357 // Unless the mem-initializer-id names a nonstatic data membeer of the
1358 // constructor's class ot a direst or virtual base of that class, the
1359 // mem-initializer is ill-formed.
1360 if (!DirectBaseSpec && !VirtualBaseSpec)
1361 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1362 << BaseType << ClassDecl->getNameAsCString()
1363 << BaseTInfo->getTypeLoc().getSourceRange();
1364
1365 CXXBaseSpecifier *BaseSpec
1366 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1367 if (!BaseSpec)
1368 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1369
1370 // Initialize the base.
1371 InitializedEntity BaseEntity =
1372 InitializedEntity::InitializeBase(Context, BaseSpec);
1373 InitializationKind Kind =
1374 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1375
1376 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1377
1378 OwningExprResult BaseInit =
1379 InitSeq.Perform(*this, BaseEntity, Kind,
1380 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1381 if (BaseInit.isInvalid())
1382 return true;
1383
1384 // C++0x [class.base.init]p7:
1385 // The initialization of each base and member constitutes a
1386 // full-expression.
1387 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1388 if (BaseInit.isInvalid())
1389 return true;
1390
1391 // If we are in a dependent context, template instantiation will
1392 // perform this type-checking again. Just save the arguments that we
1393 // received in a ParenListExpr.
1394 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1395 // of the information that we have about the base
1396 // initializer. However, deconstructing the ASTs is a dicey process,
1397 // and this approach is far more likely to get the corner cases right.
1398 if (CurContext->isDependentContext()) {
1399 // Bump the reference count of all of the arguments.
1400 for (unsigned I = 0; I != NumArgs; ++I)
1401 Args[I]->Retain();
1402
1403 OwningExprResult Init
1404 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1405 RParenLoc));
1406 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1407 LParenLoc,
1408 Init.takeAs<Expr>(),
1409 RParenLoc);
1410 }
1411
1412 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1413 LParenLoc,
1414 BaseInit.takeAs<Expr>(),
1415 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001416}
1417
Eli Friedman80c30da2009-11-09 19:20:36 +00001418bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001419Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001420 CXXBaseOrMemberInitializer **Initializers,
1421 unsigned NumInitializers,
1422 bool IsImplicitConstructor,
1423 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001424 // We need to build the initializer AST according to order of construction
1425 // and not what user specified in the Initializers list.
1426 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1427 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1428 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1429 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001430 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001432 for (unsigned i = 0; i < NumInitializers; i++) {
1433 CXXBaseOrMemberInitializer *Member = Initializers[i];
1434 if (Member->isBaseInitializer()) {
1435 if (Member->getBaseClass()->isDependentType())
1436 HasDependentBaseInit = true;
1437 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1438 } else {
1439 AllBaseFields[Member->getMember()] = Member;
1440 }
1441 }
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001443 if (HasDependentBaseInit) {
1444 // FIXME. This does not preserve the ordering of the initializers.
1445 // Try (with -Wreorder)
1446 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001447 // template<class X> struct B : A<X> {
1448 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001449 // int x1;
1450 // };
1451 // B<int> x;
1452 // On seeing one dependent type, we should essentially exit this routine
1453 // while preserving user-declared initializer list. When this routine is
1454 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001455 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001457 // If we have a dependent base initialization, we can't determine the
1458 // association between initializers and bases; just dump the known
1459 // initializers into the list, and don't try to deal with other bases.
1460 for (unsigned i = 0; i < NumInitializers; i++) {
1461 CXXBaseOrMemberInitializer *Member = Initializers[i];
1462 if (Member->isBaseInitializer())
1463 AllToInit.push_back(Member);
1464 }
1465 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001466 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1467
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001468 // Push virtual bases before others.
1469 for (CXXRecordDecl::base_class_iterator VBase =
1470 ClassDecl->vbases_begin(),
1471 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1472 if (VBase->getType()->isDependentType())
1473 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001474 if (CXXBaseOrMemberInitializer *Value
1475 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001476 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001477 } else if (!AnyErrors) {
1478 InitializedEntity InitEntity
1479 = InitializedEntity::InitializeBase(Context, VBase);
1480 InitializationKind InitKind
1481 = InitializationKind::CreateDefault(Constructor->getLocation());
1482 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1483 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1484 MultiExprArg(*this, 0, 0));
1485 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1486 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001487 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001488 continue;
1489 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001490
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001491 // Don't attach synthesized base initializers in a dependent
1492 // context; they'll be checked again at template instantiation
1493 // time.
1494 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001495 continue;
1496
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001497 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001498 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001499 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001500 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001501 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001502 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001503 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001504 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001505 }
1506 }
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001508 for (CXXRecordDecl::base_class_iterator Base =
1509 ClassDecl->bases_begin(),
1510 E = ClassDecl->bases_end(); Base != E; ++Base) {
1511 // Virtuals are in the virtual base list and already constructed.
1512 if (Base->isVirtual())
1513 continue;
1514 // Skip dependent types.
1515 if (Base->getType()->isDependentType())
1516 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001517 if (CXXBaseOrMemberInitializer *Value
1518 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001519 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001520 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001521 else if (!AnyErrors) {
1522 InitializedEntity InitEntity
1523 = InitializedEntity::InitializeBase(Context, Base);
1524 InitializationKind InitKind
1525 = InitializationKind::CreateDefault(Constructor->getLocation());
1526 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1527 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1528 MultiExprArg(*this, 0, 0));
1529 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1530 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001531 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001532 continue;
1533 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001534
1535 // Don't attach synthesized base initializers in a dependent
1536 // context; they'll be regenerated at template instantiation
1537 // time.
1538 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001539 continue;
1540
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001541 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001542 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001543 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001544 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001545 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001546 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001547 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001548 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001549 }
1550 }
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001553 // non-static data members.
1554 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1555 E = ClassDecl->field_end(); Field != E; ++Field) {
1556 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001557 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001558 Field->getType()->getAs<RecordType>()) {
1559 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001560 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001561 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001562 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1563 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1564 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1565 // set to the anonymous union data member used in the initializer
1566 // list.
1567 Value->setMember(*Field);
1568 Value->setAnonUnionMember(*FA);
1569 AllToInit.push_back(Value);
1570 break;
1571 }
1572 }
1573 }
1574 continue;
1575 }
1576 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1577 AllToInit.push_back(Value);
1578 continue;
1579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001581 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001582 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001583
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001584 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001585 if (FT->getAs<RecordType>()) {
1586 InitializedEntity InitEntity
1587 = InitializedEntity::InitializeMember(*Field);
1588 InitializationKind InitKind
1589 = InitializationKind::CreateDefault(Constructor->getLocation());
1590
1591 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1592 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1593 MultiExprArg(*this, 0, 0));
1594 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1595 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001596 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001597 continue;
1598 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001599
1600 // Don't attach synthesized member initializers in a dependent
1601 // context; they'll be regenerated a template instantiation
1602 // time.
1603 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001604 continue;
1605
Mike Stump1eb44332009-09-09 15:08:12 +00001606 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001607 new (Context) CXXBaseOrMemberInitializer(Context,
1608 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001609 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001611 SourceLocation());
1612
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001613 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001614 }
1615 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001616 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001617 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1618 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001619 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001620 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001621 }
1622 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001623 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001624 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1625 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001626 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001627 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001628 }
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001631 NumInitializers = AllToInit.size();
1632 if (NumInitializers > 0) {
1633 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1634 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1635 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001637 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1638 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1639 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1640 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001641
1642 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001643}
1644
Eli Friedman6347f422009-07-21 19:28:10 +00001645static void *GetKeyForTopLevelField(FieldDecl *Field) {
1646 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001647 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001648 if (RT->getDecl()->isAnonymousStructOrUnion())
1649 return static_cast<void *>(RT->getDecl());
1650 }
1651 return static_cast<void *>(Field);
1652}
1653
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001654static void *GetKeyForBase(QualType BaseType) {
1655 if (const RecordType *RT = BaseType->getAs<RecordType>())
1656 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001658 assert(0 && "Unexpected base type!");
1659 return 0;
1660}
1661
Mike Stump1eb44332009-09-09 15:08:12 +00001662static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001663 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001664 // For fields injected into the class via declaration of an anonymous union,
1665 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001666 if (Member->isMemberInitializer()) {
1667 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Eli Friedman49c16da2009-11-09 01:05:47 +00001669 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001670 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001671 // in AnonUnionMember field.
1672 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1673 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001674 if (Field->getDeclContext()->isRecord()) {
1675 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1676 if (RD->isAnonymousStructOrUnion())
1677 return static_cast<void *>(RD);
1678 }
1679 return static_cast<void *>(Field);
1680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001682 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001683}
1684
John McCall6aee6212009-11-04 23:13:52 +00001685/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001686void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001687 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001688 MemInitTy **MemInits, unsigned NumMemInits,
1689 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001690 if (!ConstructorDecl)
1691 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001692
1693 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001694
1695 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001696 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Anders Carlssona7b35212009-03-25 02:58:17 +00001698 if (!Constructor) {
1699 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1700 return;
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001703 if (!Constructor->isDependentContext()) {
1704 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1705 bool err = false;
1706 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001707 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001708 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1709 void *KeyToMember = GetKeyForMember(Member);
1710 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1711 if (!PrevMember) {
1712 PrevMember = Member;
1713 continue;
1714 }
1715 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001716 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001717 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001718 << Field->getNameAsString()
1719 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001720 else {
1721 Type *BaseClass = Member->getBaseClass();
1722 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001723 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001724 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001725 << QualType(BaseClass, 0)
1726 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001727 }
1728 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1729 << 0;
1730 err = true;
1731 }
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001733 if (err)
1734 return;
1735 }
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Eli Friedman49c16da2009-11-09 01:05:47 +00001737 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001738 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001739 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001741 if (Constructor->isDependentContext())
1742 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001743
1744 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001745 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001746 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001747 Diagnostic::Ignored)
1748 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001750 // Also issue warning if order of ctor-initializer list does not match order
1751 // of 1) base class declarations and 2) order of non-static data members.
1752 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001754 CXXRecordDecl *ClassDecl
1755 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1756 // Push virtual bases before others.
1757 for (CXXRecordDecl::base_class_iterator VBase =
1758 ClassDecl->vbases_begin(),
1759 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001760 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001762 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1763 E = ClassDecl->bases_end(); Base != E; ++Base) {
1764 // Virtuals are alread in the virtual base list and are constructed
1765 // first.
1766 if (Base->isVirtual())
1767 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001768 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001769 }
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001771 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1772 E = ClassDecl->field_end(); Field != E; ++Field)
1773 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001775 int Last = AllBaseOrMembers.size();
1776 int curIndex = 0;
1777 CXXBaseOrMemberInitializer *PrevMember = 0;
1778 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001779 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001780 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1781 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001782
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001783 for (; curIndex < Last; curIndex++)
1784 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1785 break;
1786 if (curIndex == Last) {
1787 assert(PrevMember && "Member not in member list?!");
1788 // Initializer as specified in ctor-initializer list is out of order.
1789 // Issue a warning diagnostic.
1790 if (PrevMember->isBaseInitializer()) {
1791 // Diagnostics is for an initialized base class.
1792 Type *BaseClass = PrevMember->getBaseClass();
1793 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001794 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001795 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001796 } else {
1797 FieldDecl *Field = PrevMember->getMember();
1798 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001799 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001800 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001801 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001802 // Also the note!
1803 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001804 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001805 diag::note_fieldorbase_initialized_here) << 0
1806 << Field->getNameAsString();
1807 else {
1808 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001809 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001810 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001811 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001812 }
1813 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001814 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001815 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001816 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001817 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001818 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001819}
1820
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001821void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001822Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1823 // Ignore dependent destructors.
1824 if (Destructor->isDependentContext())
1825 return;
1826
1827 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlsson9f853df2009-11-17 04:44:12 +00001829 // Non-static data members.
1830 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1831 E = ClassDecl->field_end(); I != E; ++I) {
1832 FieldDecl *Field = *I;
1833
1834 QualType FieldType = Context.getBaseElementType(Field->getType());
1835
1836 const RecordType* RT = FieldType->getAs<RecordType>();
1837 if (!RT)
1838 continue;
1839
1840 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1841 if (FieldClassDecl->hasTrivialDestructor())
1842 continue;
1843
1844 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1845 MarkDeclarationReferenced(Destructor->getLocation(),
1846 const_cast<CXXDestructorDecl*>(Dtor));
1847 }
1848
1849 // Bases.
1850 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1851 E = ClassDecl->bases_end(); Base != E; ++Base) {
1852 // Ignore virtual bases.
1853 if (Base->isVirtual())
1854 continue;
1855
1856 // Ignore trivial destructors.
1857 CXXRecordDecl *BaseClassDecl
1858 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1859 if (BaseClassDecl->hasTrivialDestructor())
1860 continue;
1861
1862 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1863 MarkDeclarationReferenced(Destructor->getLocation(),
1864 const_cast<CXXDestructorDecl*>(Dtor));
1865 }
1866
1867 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001868 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1869 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001870 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001871 CXXRecordDecl *BaseClassDecl
1872 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1873 if (BaseClassDecl->hasTrivialDestructor())
1874 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001875
1876 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1877 MarkDeclarationReferenced(Destructor->getLocation(),
1878 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001879 }
1880}
1881
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001882void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001883 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001886 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001887
1888 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001889 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001890 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001891}
1892
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001893namespace {
1894 /// PureVirtualMethodCollector - traverses a class and its superclasses
1895 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001896 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001897 ASTContext &Context;
1898
Sebastian Redldfe292d2009-03-22 21:28:55 +00001899 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001900 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001901
1902 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001903 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001905 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001907 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001908 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001909 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001911 MethodList List;
1912 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001914 // Copy the temporary list to methods, and make sure to ignore any
1915 // null entries.
1916 for (size_t i = 0, e = List.size(); i != e; ++i) {
1917 if (List[i])
1918 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001919 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001920 }
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001922 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001924 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1925 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001926 };
Mike Stump1eb44332009-09-09 15:08:12 +00001927
1928 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001929 MethodList& Methods) {
1930 // First, collect the pure virtual methods for the base classes.
1931 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1932 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001933 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001934 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001935 if (BaseDecl && BaseDecl->isAbstract())
1936 Collect(BaseDecl, Methods);
1937 }
1938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001940 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001941 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001943 MethodSetTy OverriddenMethods;
1944 size_t MethodsSize = Methods.size();
1945
Mike Stump1eb44332009-09-09 15:08:12 +00001946 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001947 i != e; ++i) {
1948 // Traverse the record, looking for methods.
1949 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001950 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001951 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001952 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Anders Carlsson27823022009-10-18 19:34:08 +00001954 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001955 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1956 E = MD->end_overridden_methods(); I != E; ++I) {
1957 // Keep track of the overridden methods.
1958 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001959 }
1960 }
1961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962
1963 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001964 // overridden.
1965 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1966 if (OverriddenMethods.count(Methods[i]))
1967 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001970 }
1971}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001972
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001973
Mike Stump1eb44332009-09-09 15:08:12 +00001974bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001975 unsigned DiagID, AbstractDiagSelID SelID,
1976 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001977 if (SelID == -1)
1978 return RequireNonAbstractType(Loc, T,
1979 PDiag(DiagID), CurrentRD);
1980 else
1981 return RequireNonAbstractType(Loc, T,
1982 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001983}
1984
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001985bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1986 const PartialDiagnostic &PD,
1987 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001988 if (!getLangOptions().CPlusPlus)
1989 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Anders Carlsson11f21a02009-03-23 19:10:31 +00001991 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001992 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001993 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Ted Kremenek6217b802009-07-29 21:53:49 +00001995 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001996 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001997 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001998 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002000 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002001 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002002 }
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Ted Kremenek6217b802009-07-29 21:53:49 +00002004 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002005 if (!RT)
2006 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002007
John McCall86ff3082010-02-04 22:26:26 +00002008 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002009
Anders Carlssone65a3c82009-03-24 17:23:42 +00002010 if (CurrentRD && CurrentRD != RD)
2011 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCall86ff3082010-02-04 22:26:26 +00002013 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002014 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002015 return false;
2016
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002017 if (!RD->isAbstract())
2018 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002020 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002022 // Check if we've already emitted the list of pure virtual functions for this
2023 // class.
2024 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2025 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002027 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002028
2029 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002030 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2031 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002032
2033 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002034 MD->getDeclName();
2035 }
2036
2037 if (!PureVirtualClassDiagSet)
2038 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2039 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002041 return true;
2042}
2043
Anders Carlsson8211eff2009-03-24 01:19:16 +00002044namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002045 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002046 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2047 Sema &SemaRef;
2048 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Anders Carlssone65a3c82009-03-24 17:23:42 +00002050 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002051 bool Invalid = false;
2052
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002053 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2054 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002055 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002056
Anders Carlsson8211eff2009-03-24 01:19:16 +00002057 return Invalid;
2058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Anders Carlssone65a3c82009-03-24 17:23:42 +00002060 public:
2061 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2062 : SemaRef(SemaRef), AbstractClass(ac) {
2063 Visit(SemaRef.Context.getTranslationUnitDecl());
2064 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002065
Anders Carlssone65a3c82009-03-24 17:23:42 +00002066 bool VisitFunctionDecl(const FunctionDecl *FD) {
2067 if (FD->isThisDeclarationADefinition()) {
2068 // No need to do the check if we're in a definition, because it requires
2069 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002070 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002071 return VisitDeclContext(FD);
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Anders Carlssone65a3c82009-03-24 17:23:42 +00002074 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002075 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002076 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002077 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2078 diag::err_abstract_type_in_decl,
2079 Sema::AbstractReturnType,
2080 AbstractClass);
2081
Mike Stump1eb44332009-09-09 15:08:12 +00002082 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002083 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002084 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002085 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002086 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002087 VD->getOriginalType(),
2088 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002089 Sema::AbstractParamType,
2090 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002091 }
2092
2093 return Invalid;
2094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Anders Carlssone65a3c82009-03-24 17:23:42 +00002096 bool VisitDecl(const Decl* D) {
2097 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2098 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Anders Carlssone65a3c82009-03-24 17:23:42 +00002100 return false;
2101 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002102 };
2103}
2104
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002105/// \brief Perform semantic checks on a class definition that has been
2106/// completing, introducing implicitly-declared members, checking for
2107/// abstract types, etc.
2108void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2109 if (!Record || Record->isInvalidDecl())
2110 return;
2111
Eli Friedmanff2d8782009-12-16 20:00:27 +00002112 if (!Record->isDependentType())
2113 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002114
Eli Friedmanff2d8782009-12-16 20:00:27 +00002115 if (Record->isInvalidDecl())
2116 return;
2117
John McCall233a6412010-01-28 07:38:46 +00002118 // Set access bits correctly on the directly-declared conversions.
2119 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2120 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2121 Convs->setAccess(I, (*I)->getAccess());
2122
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002123 if (!Record->isAbstract()) {
2124 // Collect all the pure virtual methods and see if this is an abstract
2125 // class after all.
2126 PureVirtualMethodCollector Collector(Context, Record);
2127 if (!Collector.empty())
2128 Record->setAbstract(true);
2129 }
2130
2131 if (Record->isAbstract())
2132 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002133}
2134
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002135void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002136 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002137 SourceLocation LBrac,
2138 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002139 if (!TagDecl)
2140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Douglas Gregor42af25f2009-05-11 19:58:34 +00002142 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002143
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002144 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002145 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002146 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002147
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002148 CheckCompletedCXXClass(
2149 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002150}
2151
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002152/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2153/// special functions, such as the default constructor, copy
2154/// constructor, or destructor, to the given C++ class (C++
2155/// [special]p1). This routine can only be executed just before the
2156/// definition of the class is complete.
2157void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002158 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002159 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002160
Sebastian Redl465226e2009-05-27 22:11:52 +00002161 // FIXME: Implicit declarations have exception specifications, which are
2162 // the union of the specifications of the implicitly called functions.
2163
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002164 if (!ClassDecl->hasUserDeclaredConstructor()) {
2165 // C++ [class.ctor]p5:
2166 // A default constructor for a class X is a constructor of class X
2167 // that can be called without an argument. If there is no
2168 // user-declared constructor for class X, a default constructor is
2169 // implicitly declared. An implicitly-declared default constructor
2170 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002171 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002172 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002173 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002174 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002175 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002176 Context.getFunctionType(Context.VoidTy,
2177 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002178 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002179 /*isExplicit=*/false,
2180 /*isInline=*/true,
2181 /*isImplicitlyDeclared=*/true);
2182 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002183 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002184 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002185 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002186 }
2187
2188 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2189 // C++ [class.copy]p4:
2190 // If the class definition does not explicitly declare a copy
2191 // constructor, one is declared implicitly.
2192
2193 // C++ [class.copy]p5:
2194 // The implicitly-declared copy constructor for a class X will
2195 // have the form
2196 //
2197 // X::X(const X&)
2198 //
2199 // if
2200 bool HasConstCopyConstructor = true;
2201
2202 // -- each direct or virtual base class B of X has a copy
2203 // constructor whose first parameter is of type const B& or
2204 // const volatile B&, and
2205 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2206 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2207 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002208 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002209 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002210 = BaseClassDecl->hasConstCopyConstructor(Context);
2211 }
2212
2213 // -- for all the nonstatic data members of X that are of a
2214 // class type M (or array thereof), each such class type
2215 // has a copy constructor whose first parameter is of type
2216 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002217 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2218 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002219 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002220 QualType FieldType = (*Field)->getType();
2221 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2222 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002223 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002224 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002225 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002226 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002227 = FieldClassDecl->hasConstCopyConstructor(Context);
2228 }
2229 }
2230
Sebastian Redl64b45f72009-01-05 20:52:13 +00002231 // Otherwise, the implicitly declared copy constructor will have
2232 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002233 //
2234 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002235 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002236 if (HasConstCopyConstructor)
2237 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002238 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002239
Sebastian Redl64b45f72009-01-05 20:52:13 +00002240 // An implicitly-declared copy constructor is an inline public
2241 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002242 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002243 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002244 CXXConstructorDecl *CopyConstructor
2245 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002246 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002247 Context.getFunctionType(Context.VoidTy,
2248 &ArgType, 1,
2249 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002250 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002251 /*isExplicit=*/false,
2252 /*isInline=*/true,
2253 /*isImplicitlyDeclared=*/true);
2254 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002255 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002256 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002257
2258 // Add the parameter to the constructor.
2259 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2260 ClassDecl->getLocation(),
2261 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002262 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002263 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002264 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002265 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002266 }
2267
Sebastian Redl64b45f72009-01-05 20:52:13 +00002268 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2269 // Note: The following rules are largely analoguous to the copy
2270 // constructor rules. Note that virtual bases are not taken into account
2271 // for determining the argument type of the operator. Note also that
2272 // operators taking an object instead of a reference are allowed.
2273 //
2274 // C++ [class.copy]p10:
2275 // If the class definition does not explicitly declare a copy
2276 // assignment operator, one is declared implicitly.
2277 // The implicitly-defined copy assignment operator for a class X
2278 // will have the form
2279 //
2280 // X& X::operator=(const X&)
2281 //
2282 // if
2283 bool HasConstCopyAssignment = true;
2284
2285 // -- each direct base class B of X has a copy assignment operator
2286 // whose parameter is of type const B&, const volatile B& or B,
2287 // and
2288 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2289 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002290 assert(!Base->getType()->isDependentType() &&
2291 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002292 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002293 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002294 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002295 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002296 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002297 }
2298
2299 // -- for all the nonstatic data members of X that are of a class
2300 // type M (or array thereof), each such class type has a copy
2301 // assignment operator whose parameter is of type const M&,
2302 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002303 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2304 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002305 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002306 QualType FieldType = (*Field)->getType();
2307 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2308 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002309 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002310 const CXXRecordDecl *FieldClassDecl
2311 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002312 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002313 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002314 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002315 }
2316 }
2317
2318 // Otherwise, the implicitly declared copy assignment operator will
2319 // have the form
2320 //
2321 // X& X::operator=(X&)
2322 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002323 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002324 if (HasConstCopyAssignment)
2325 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002326 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002327
2328 // An implicitly-declared copy assignment operator is an inline public
2329 // member of its class.
2330 DeclarationName Name =
2331 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2332 CXXMethodDecl *CopyAssignment =
2333 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2334 Context.getFunctionType(RetType, &ArgType, 1,
2335 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002336 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002337 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002338 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002339 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002340 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002341
2342 // Add the parameter to the operator.
2343 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2344 ClassDecl->getLocation(),
2345 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002346 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002347 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002348 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002349
2350 // Don't call addedAssignmentOperator. There is no way to distinguish an
2351 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002352 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002353 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002354 }
2355
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002356 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002357 // C++ [class.dtor]p2:
2358 // If a class has no user-declared destructor, a destructor is
2359 // declared implicitly. An implicitly-declared destructor is an
2360 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002361 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002362 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002363 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002364 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002365 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002366 Context.getFunctionType(Context.VoidTy,
2367 0, 0, false, 0),
2368 /*isInline=*/true,
2369 /*isImplicitlyDeclared=*/true);
2370 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002371 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002372 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002373 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002374
2375 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002376 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002377}
2378
Douglas Gregor6569d682009-05-27 23:11:45 +00002379void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002380 Decl *D = TemplateD.getAs<Decl>();
2381 if (!D)
2382 return;
2383
2384 TemplateParameterList *Params = 0;
2385 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2386 Params = Template->getTemplateParameters();
2387 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2388 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2389 Params = PartialSpec->getTemplateParameters();
2390 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002391 return;
2392
Douglas Gregor6569d682009-05-27 23:11:45 +00002393 for (TemplateParameterList::iterator Param = Params->begin(),
2394 ParamEnd = Params->end();
2395 Param != ParamEnd; ++Param) {
2396 NamedDecl *Named = cast<NamedDecl>(*Param);
2397 if (Named->getDeclName()) {
2398 S->AddDecl(DeclPtrTy::make(Named));
2399 IdResolver.AddDecl(Named);
2400 }
2401 }
2402}
2403
John McCall7a1dc562009-12-19 10:49:29 +00002404void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2405 if (!RecordD) return;
2406 AdjustDeclIfTemplate(RecordD);
2407 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2408 PushDeclContext(S, Record);
2409}
2410
2411void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2412 if (!RecordD) return;
2413 PopDeclContext();
2414}
2415
Douglas Gregor72b505b2008-12-16 21:30:33 +00002416/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2417/// parsing a top-level (non-nested) C++ class, and we are now
2418/// parsing those parts of the given Method declaration that could
2419/// not be parsed earlier (C++ [class.mem]p2), such as default
2420/// arguments. This action should enter the scope of the given
2421/// Method declaration as if we had just parsed the qualified method
2422/// name. However, it should not bring the parameters into scope;
2423/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002424void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002425}
2426
2427/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2428/// C++ method declaration. We're (re-)introducing the given
2429/// function parameter into scope for use in parsing later parts of
2430/// the method declaration. For example, we could see an
2431/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002432void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002433 if (!ParamD)
2434 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Chris Lattnerb28317a2009-03-28 19:18:32 +00002436 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002437
2438 // If this parameter has an unparsed default argument, clear it out
2439 // to make way for the parsed default argument.
2440 if (Param->hasUnparsedDefaultArg())
2441 Param->setDefaultArg(0);
2442
Chris Lattnerb28317a2009-03-28 19:18:32 +00002443 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002444 if (Param->getDeclName())
2445 IdResolver.AddDecl(Param);
2446}
2447
2448/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2449/// processing the delayed method declaration for Method. The method
2450/// declaration is now considered finished. There may be a separate
2451/// ActOnStartOfFunctionDef action later (not necessarily
2452/// immediately!) for this method, if it was also defined inside the
2453/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002454void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002455 if (!MethodD)
2456 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002458 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Chris Lattnerb28317a2009-03-28 19:18:32 +00002460 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002461
2462 // Now that we have our default arguments, check the constructor
2463 // again. It could produce additional diagnostics or affect whether
2464 // the class has implicitly-declared destructors, among other
2465 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002466 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2467 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002468
2469 // Check the default arguments, which we may have added.
2470 if (!Method->isInvalidDecl())
2471 CheckCXXDefaultArguments(Method);
2472}
2473
Douglas Gregor42a552f2008-11-05 20:51:48 +00002474/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002475/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002476/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002477/// emit diagnostics and set the invalid bit to true. In any case, the type
2478/// will be updated to reflect a well-formed type for the constructor and
2479/// returned.
2480QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2481 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002482 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002483
2484 // C++ [class.ctor]p3:
2485 // A constructor shall not be virtual (10.3) or static (9.4). A
2486 // constructor can be invoked for a const, volatile or const
2487 // volatile object. A constructor shall not be declared const,
2488 // volatile, or const volatile (9.3.2).
2489 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002490 if (!D.isInvalidType())
2491 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2492 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2493 << SourceRange(D.getIdentifierLoc());
2494 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002495 }
2496 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002497 if (!D.isInvalidType())
2498 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2499 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2500 << SourceRange(D.getIdentifierLoc());
2501 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002502 SC = FunctionDecl::None;
2503 }
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Chris Lattner65401802009-04-25 08:28:21 +00002505 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2506 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002507 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002508 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2509 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002510 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002511 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2512 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002513 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002514 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2515 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002516 }
Mike Stump1eb44332009-09-09 15:08:12 +00002517
Douglas Gregor42a552f2008-11-05 20:51:48 +00002518 // Rebuild the function type "R" without any type qualifiers (in
2519 // case any of the errors above fired) and with "void" as the
2520 // return type, since constructors don't have return types. We
2521 // *always* have to do this, because GetTypeForDeclarator will
2522 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002523 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002524 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2525 Proto->getNumArgs(),
2526 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002527}
2528
Douglas Gregor72b505b2008-12-16 21:30:33 +00002529/// CheckConstructor - Checks a fully-formed constructor for
2530/// well-formedness, issuing any diagnostics required. Returns true if
2531/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002532void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002533 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002534 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2535 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002536 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002537
2538 // C++ [class.copy]p3:
2539 // A declaration of a constructor for a class X is ill-formed if
2540 // its first parameter is of type (optionally cv-qualified) X and
2541 // either there are no other parameters or else all other
2542 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002543 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002544 ((Constructor->getNumParams() == 1) ||
2545 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002546 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2547 Constructor->getTemplateSpecializationKind()
2548 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002549 QualType ParamType = Constructor->getParamDecl(0)->getType();
2550 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2551 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002552 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2553 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002554 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002555
2556 // FIXME: Rather that making the constructor invalid, we should endeavor
2557 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002558 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002559 }
2560 }
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Douglas Gregor72b505b2008-12-16 21:30:33 +00002562 // Notify the class that we've added a constructor.
2563 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002564}
2565
Anders Carlsson37909802009-11-30 21:24:50 +00002566/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2567/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002568bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002569 CXXRecordDecl *RD = Destructor->getParent();
2570
2571 if (Destructor->isVirtual()) {
2572 SourceLocation Loc;
2573
2574 if (!Destructor->isImplicit())
2575 Loc = Destructor->getLocation();
2576 else
2577 Loc = RD->getLocation();
2578
2579 // If we have a virtual destructor, look up the deallocation function
2580 FunctionDecl *OperatorDelete = 0;
2581 DeclarationName Name =
2582 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002583 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002584 return true;
2585
2586 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002587 }
Anders Carlsson37909802009-11-30 21:24:50 +00002588
2589 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002590}
2591
Mike Stump1eb44332009-09-09 15:08:12 +00002592static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002593FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2594 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2595 FTI.ArgInfo[0].Param &&
2596 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2597}
2598
Douglas Gregor42a552f2008-11-05 20:51:48 +00002599/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2600/// the well-formednes of the destructor declarator @p D with type @p
2601/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002602/// emit diagnostics and set the declarator to invalid. Even if this happens,
2603/// will be updated to reflect a well-formed type for the destructor and
2604/// returned.
2605QualType Sema::CheckDestructorDeclarator(Declarator &D,
2606 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002607 // C++ [class.dtor]p1:
2608 // [...] A typedef-name that names a class is a class-name
2609 // (7.1.3); however, a typedef-name that names a class shall not
2610 // be used as the identifier in the declarator for a destructor
2611 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002612 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002613 if (isa<TypedefType>(DeclaratorType)) {
2614 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002615 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002616 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002617 }
2618
2619 // C++ [class.dtor]p2:
2620 // A destructor is used to destroy objects of its class type. A
2621 // destructor takes no parameters, and no return type can be
2622 // specified for it (not even void). The address of a destructor
2623 // shall not be taken. A destructor shall not be static. A
2624 // destructor can be invoked for a const, volatile or const
2625 // volatile object. A destructor shall not be declared const,
2626 // volatile or const volatile (9.3.2).
2627 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002628 if (!D.isInvalidType())
2629 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2630 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2631 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002632 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002633 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002634 }
Chris Lattner65401802009-04-25 08:28:21 +00002635 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002636 // Destructors don't have return types, but the parser will
2637 // happily parse something like:
2638 //
2639 // class X {
2640 // float ~X();
2641 // };
2642 //
2643 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002644 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2645 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2646 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002647 }
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Chris Lattner65401802009-04-25 08:28:21 +00002649 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2650 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002651 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002652 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2653 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002654 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002655 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2656 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002657 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002658 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2659 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002660 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002661 }
2662
2663 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002664 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002665 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2666
2667 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002668 FTI.freeArgs();
2669 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002670 }
2671
Mike Stump1eb44332009-09-09 15:08:12 +00002672 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002673 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002674 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002675 D.setInvalidType();
2676 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002677
2678 // Rebuild the function type "R" without any type qualifiers or
2679 // parameters (in case any of the errors above fired) and with
2680 // "void" as the return type, since destructors don't have return
2681 // types. We *always* have to do this, because GetTypeForDeclarator
2682 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002683 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002684}
2685
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002686/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2687/// well-formednes of the conversion function declarator @p D with
2688/// type @p R. If there are any errors in the declarator, this routine
2689/// will emit diagnostics and return true. Otherwise, it will return
2690/// false. Either way, the type @p R will be updated to reflect a
2691/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002692void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002693 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002694 // C++ [class.conv.fct]p1:
2695 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002696 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002697 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002698 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002699 if (!D.isInvalidType())
2700 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2701 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2702 << SourceRange(D.getIdentifierLoc());
2703 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002704 SC = FunctionDecl::None;
2705 }
Chris Lattner6e475012009-04-25 08:35:12 +00002706 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002707 // Conversion functions don't have return types, but the parser will
2708 // happily parse something like:
2709 //
2710 // class X {
2711 // float operator bool();
2712 // };
2713 //
2714 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002715 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2716 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2717 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002718 }
2719
2720 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002721 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002722 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2723
2724 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002725 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002726 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002727 }
2728
Mike Stump1eb44332009-09-09 15:08:12 +00002729 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002730 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002731 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002732 D.setInvalidType();
2733 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002734
2735 // C++ [class.conv.fct]p4:
2736 // The conversion-type-id shall not represent a function type nor
2737 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002738 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002739 if (ConvType->isArrayType()) {
2740 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2741 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002742 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002743 } else if (ConvType->isFunctionType()) {
2744 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2745 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002746 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002747 }
2748
2749 // Rebuild the function type "R" without any parameters (in case any
2750 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002751 // return type.
2752 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002753 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002754
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002755 // C++0x explicit conversion operators.
2756 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002757 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002758 diag::warn_explicit_conversion_functions)
2759 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002760}
2761
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002762/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2763/// the declaration of the given C++ conversion function. This routine
2764/// is responsible for recording the conversion function in the C++
2765/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002766Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002767 assert(Conversion && "Expected to receive a conversion function declaration");
2768
Douglas Gregor9d350972008-12-12 08:25:50 +00002769 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002770
2771 // Make sure we aren't redeclaring the conversion function.
2772 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002773
2774 // C++ [class.conv.fct]p1:
2775 // [...] A conversion function is never used to convert a
2776 // (possibly cv-qualified) object to the (possibly cv-qualified)
2777 // same object type (or a reference to it), to a (possibly
2778 // cv-qualified) base class of that type (or a reference to it),
2779 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002780 // FIXME: Suppress this warning if the conversion function ends up being a
2781 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002782 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002783 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002784 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002785 ConvType = ConvTypeRef->getPointeeType();
2786 if (ConvType->isRecordType()) {
2787 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2788 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002789 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002790 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002791 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002792 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002793 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002794 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002795 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002796 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002797 }
2798
Douglas Gregor48026d22010-01-11 18:40:55 +00002799 if (Conversion->getPrimaryTemplate()) {
2800 // ignore specializations
2801 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002802 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002803 = Conversion->getDescribedFunctionTemplate()) {
2804 if (ClassDecl->replaceConversion(
2805 ConversionTemplate->getPreviousDeclaration(),
2806 ConversionTemplate))
2807 return DeclPtrTy::make(ConversionTemplate);
2808 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2809 Conversion))
John McCallba135432009-11-21 08:51:07 +00002810 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002811 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002812 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002813 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002814 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002815 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002816 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002817
Chris Lattnerb28317a2009-03-28 19:18:32 +00002818 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002819}
2820
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002821//===----------------------------------------------------------------------===//
2822// Namespace Handling
2823//===----------------------------------------------------------------------===//
2824
2825/// ActOnStartNamespaceDef - This is called at the start of a namespace
2826/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002827Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2828 SourceLocation IdentLoc,
2829 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002830 SourceLocation LBrace,
2831 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002832 NamespaceDecl *Namespc =
2833 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2834 Namespc->setLBracLoc(LBrace);
2835
2836 Scope *DeclRegionScope = NamespcScope->getParent();
2837
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002838 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2839
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002840 if (II) {
2841 // C++ [namespace.def]p2:
2842 // The identifier in an original-namespace-definition shall not have been
2843 // previously defined in the declarative region in which the
2844 // original-namespace-definition appears. The identifier in an
2845 // original-namespace-definition is the name of the namespace. Subsequently
2846 // in that declarative region, it is treated as an original-namespace-name.
2847
John McCallf36e02d2009-10-09 21:13:30 +00002848 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002849 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002850 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Douglas Gregor44b43212008-12-11 16:49:14 +00002852 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2853 // This is an extended namespace definition.
2854 // Attach this namespace decl to the chain of extended namespace
2855 // definitions.
2856 OrigNS->setNextNamespace(Namespc);
2857 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002858
Mike Stump1eb44332009-09-09 15:08:12 +00002859 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002860 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002861 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002862 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002863 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002864 } else if (PrevDecl) {
2865 // This is an invalid name redefinition.
2866 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2867 << Namespc->getDeclName();
2868 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2869 Namespc->setInvalidDecl();
2870 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002871 } else if (II->isStr("std") &&
2872 CurContext->getLookupContext()->isTranslationUnit()) {
2873 // This is the first "real" definition of the namespace "std", so update
2874 // our cache of the "std" namespace to point at this definition.
2875 if (StdNamespace) {
2876 // We had already defined a dummy namespace "std". Link this new
2877 // namespace definition to the dummy namespace "std".
2878 StdNamespace->setNextNamespace(Namespc);
2879 StdNamespace->setLocation(IdentLoc);
2880 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2881 }
2882
2883 // Make our StdNamespace cache point at the first real definition of the
2884 // "std" namespace.
2885 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002886 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002887
2888 PushOnScopeChains(Namespc, DeclRegionScope);
2889 } else {
John McCall9aeed322009-10-01 00:25:31 +00002890 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002891 assert(Namespc->isAnonymousNamespace());
2892 CurContext->addDecl(Namespc);
2893
2894 // Link the anonymous namespace into its parent.
2895 NamespaceDecl *PrevDecl;
2896 DeclContext *Parent = CurContext->getLookupContext();
2897 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2898 PrevDecl = TU->getAnonymousNamespace();
2899 TU->setAnonymousNamespace(Namespc);
2900 } else {
2901 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2902 PrevDecl = ND->getAnonymousNamespace();
2903 ND->setAnonymousNamespace(Namespc);
2904 }
2905
2906 // Link the anonymous namespace with its previous declaration.
2907 if (PrevDecl) {
2908 assert(PrevDecl->isAnonymousNamespace());
2909 assert(!PrevDecl->getNextNamespace());
2910 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2911 PrevDecl->setNextNamespace(Namespc);
2912 }
John McCall9aeed322009-10-01 00:25:31 +00002913
2914 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2915 // behaves as if it were replaced by
2916 // namespace unique { /* empty body */ }
2917 // using namespace unique;
2918 // namespace unique { namespace-body }
2919 // where all occurrences of 'unique' in a translation unit are
2920 // replaced by the same identifier and this identifier differs
2921 // from all other identifiers in the entire program.
2922
2923 // We just create the namespace with an empty name and then add an
2924 // implicit using declaration, just like the standard suggests.
2925 //
2926 // CodeGen enforces the "universally unique" aspect by giving all
2927 // declarations semantically contained within an anonymous
2928 // namespace internal linkage.
2929
John McCall5fdd7642009-12-16 02:06:49 +00002930 if (!PrevDecl) {
2931 UsingDirectiveDecl* UD
2932 = UsingDirectiveDecl::Create(Context, CurContext,
2933 /* 'using' */ LBrace,
2934 /* 'namespace' */ SourceLocation(),
2935 /* qualifier */ SourceRange(),
2936 /* NNS */ NULL,
2937 /* identifier */ SourceLocation(),
2938 Namespc,
2939 /* Ancestor */ CurContext);
2940 UD->setImplicit();
2941 CurContext->addDecl(UD);
2942 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002943 }
2944
2945 // Although we could have an invalid decl (i.e. the namespace name is a
2946 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002947 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2948 // for the namespace has the declarations that showed up in that particular
2949 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002950 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002951 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002952}
2953
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002954/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2955/// is a namespace alias, returns the namespace it points to.
2956static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2957 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2958 return AD->getNamespace();
2959 return dyn_cast_or_null<NamespaceDecl>(D);
2960}
2961
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002962/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2963/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002964void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2965 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002966 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2967 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2968 Namespc->setRBracLoc(RBrace);
2969 PopDeclContext();
2970}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002971
Chris Lattnerb28317a2009-03-28 19:18:32 +00002972Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2973 SourceLocation UsingLoc,
2974 SourceLocation NamespcLoc,
2975 const CXXScopeSpec &SS,
2976 SourceLocation IdentLoc,
2977 IdentifierInfo *NamespcName,
2978 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002979 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2980 assert(NamespcName && "Invalid NamespcName.");
2981 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002982 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002983
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002984 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002985
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002986 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002987 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2988 LookupParsedName(R, S, &SS);
2989 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002990 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002991
John McCallf36e02d2009-10-09 21:13:30 +00002992 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002993 NamedDecl *Named = R.getFoundDecl();
2994 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2995 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002996 // C++ [namespace.udir]p1:
2997 // A using-directive specifies that the names in the nominated
2998 // namespace can be used in the scope in which the
2999 // using-directive appears after the using-directive. During
3000 // unqualified name lookup (3.4.1), the names appear as if they
3001 // were declared in the nearest enclosing namespace which
3002 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003003 // namespace. [Note: in this context, "contains" means "contains
3004 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003005
3006 // Find enclosing context containing both using-directive and
3007 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003008 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003009 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3010 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3011 CommonAncestor = CommonAncestor->getParent();
3012
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003013 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003014 SS.getRange(),
3015 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003016 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003017 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003018 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003019 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003020 }
3021
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003022 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003023 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003024 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003025}
3026
3027void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3028 // If scope has associated entity, then using directive is at namespace
3029 // or translation unit scope. We add UsingDirectiveDecls, into
3030 // it's lookup structure.
3031 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003032 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003033 else
3034 // Otherwise it is block-sope. using-directives will affect lookup
3035 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003036 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003037}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003038
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003039
3040Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003041 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003042 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003043 SourceLocation UsingLoc,
3044 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003045 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003046 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003047 bool IsTypeName,
3048 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003049 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Douglas Gregor12c118a2009-11-04 16:30:06 +00003051 switch (Name.getKind()) {
3052 case UnqualifiedId::IK_Identifier:
3053 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003054 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003055 case UnqualifiedId::IK_ConversionFunctionId:
3056 break;
3057
3058 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003059 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003060 // C++0x inherited constructors.
3061 if (getLangOptions().CPlusPlus0x) break;
3062
Douglas Gregor12c118a2009-11-04 16:30:06 +00003063 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3064 << SS.getRange();
3065 return DeclPtrTy();
3066
3067 case UnqualifiedId::IK_DestructorName:
3068 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3069 << SS.getRange();
3070 return DeclPtrTy();
3071
3072 case UnqualifiedId::IK_TemplateId:
3073 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3074 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3075 return DeclPtrTy();
3076 }
3077
3078 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003079 if (!TargetName)
3080 return DeclPtrTy();
3081
John McCall60fa3cf2009-12-11 02:10:03 +00003082 // Warn about using declarations.
3083 // TODO: store that the declaration was written without 'using' and
3084 // talk about access decls instead of using decls in the
3085 // diagnostics.
3086 if (!HasUsingKeyword) {
3087 UsingLoc = Name.getSourceRange().getBegin();
3088
3089 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3090 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3091 "using ");
3092 }
3093
John McCall9488ea12009-11-17 05:59:44 +00003094 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003095 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003096 TargetName, AttrList,
3097 /* IsInstantiation */ false,
3098 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003099 if (UD)
3100 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Anders Carlssonc72160b2009-08-28 05:40:36 +00003102 return DeclPtrTy::make(UD);
3103}
3104
John McCall9f54ad42009-12-10 09:41:52 +00003105/// Determines whether to create a using shadow decl for a particular
3106/// decl, given the set of decls existing prior to this using lookup.
3107bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3108 const LookupResult &Previous) {
3109 // Diagnose finding a decl which is not from a base class of the
3110 // current class. We do this now because there are cases where this
3111 // function will silently decide not to build a shadow decl, which
3112 // will pre-empt further diagnostics.
3113 //
3114 // We don't need to do this in C++0x because we do the check once on
3115 // the qualifier.
3116 //
3117 // FIXME: diagnose the following if we care enough:
3118 // struct A { int foo; };
3119 // struct B : A { using A::foo; };
3120 // template <class T> struct C : A {};
3121 // template <class T> struct D : C<T> { using B::foo; } // <---
3122 // This is invalid (during instantiation) in C++03 because B::foo
3123 // resolves to the using decl in B, which is not a base class of D<T>.
3124 // We can't diagnose it immediately because C<T> is an unknown
3125 // specialization. The UsingShadowDecl in D<T> then points directly
3126 // to A::foo, which will look well-formed when we instantiate.
3127 // The right solution is to not collapse the shadow-decl chain.
3128 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3129 DeclContext *OrigDC = Orig->getDeclContext();
3130
3131 // Handle enums and anonymous structs.
3132 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3133 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3134 while (OrigRec->isAnonymousStructOrUnion())
3135 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3136
3137 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3138 if (OrigDC == CurContext) {
3139 Diag(Using->getLocation(),
3140 diag::err_using_decl_nested_name_specifier_is_current_class)
3141 << Using->getNestedNameRange();
3142 Diag(Orig->getLocation(), diag::note_using_decl_target);
3143 return true;
3144 }
3145
3146 Diag(Using->getNestedNameRange().getBegin(),
3147 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3148 << Using->getTargetNestedNameDecl()
3149 << cast<CXXRecordDecl>(CurContext)
3150 << Using->getNestedNameRange();
3151 Diag(Orig->getLocation(), diag::note_using_decl_target);
3152 return true;
3153 }
3154 }
3155
3156 if (Previous.empty()) return false;
3157
3158 NamedDecl *Target = Orig;
3159 if (isa<UsingShadowDecl>(Target))
3160 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3161
John McCalld7533ec2009-12-11 02:33:26 +00003162 // If the target happens to be one of the previous declarations, we
3163 // don't have a conflict.
3164 //
3165 // FIXME: but we might be increasing its access, in which case we
3166 // should redeclare it.
3167 NamedDecl *NonTag = 0, *Tag = 0;
3168 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3169 I != E; ++I) {
3170 NamedDecl *D = (*I)->getUnderlyingDecl();
3171 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3172 return false;
3173
3174 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3175 }
3176
John McCall9f54ad42009-12-10 09:41:52 +00003177 if (Target->isFunctionOrFunctionTemplate()) {
3178 FunctionDecl *FD;
3179 if (isa<FunctionTemplateDecl>(Target))
3180 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3181 else
3182 FD = cast<FunctionDecl>(Target);
3183
3184 NamedDecl *OldDecl = 0;
3185 switch (CheckOverload(FD, Previous, OldDecl)) {
3186 case Ovl_Overload:
3187 return false;
3188
3189 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003190 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003191 break;
3192
3193 // We found a decl with the exact signature.
3194 case Ovl_Match:
3195 if (isa<UsingShadowDecl>(OldDecl)) {
3196 // Silently ignore the possible conflict.
3197 return false;
3198 }
3199
3200 // If we're in a record, we want to hide the target, so we
3201 // return true (without a diagnostic) to tell the caller not to
3202 // build a shadow decl.
3203 if (CurContext->isRecord())
3204 return true;
3205
3206 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003207 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003208 break;
3209 }
3210
3211 Diag(Target->getLocation(), diag::note_using_decl_target);
3212 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3213 return true;
3214 }
3215
3216 // Target is not a function.
3217
John McCall9f54ad42009-12-10 09:41:52 +00003218 if (isa<TagDecl>(Target)) {
3219 // No conflict between a tag and a non-tag.
3220 if (!Tag) return false;
3221
John McCall41ce66f2009-12-10 19:51:03 +00003222 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003223 Diag(Target->getLocation(), diag::note_using_decl_target);
3224 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3225 return true;
3226 }
3227
3228 // No conflict between a tag and a non-tag.
3229 if (!NonTag) return false;
3230
John McCall41ce66f2009-12-10 19:51:03 +00003231 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003232 Diag(Target->getLocation(), diag::note_using_decl_target);
3233 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3234 return true;
3235}
3236
John McCall9488ea12009-11-17 05:59:44 +00003237/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003238UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003239 UsingDecl *UD,
3240 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003241
3242 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003243 NamedDecl *Target = Orig;
3244 if (isa<UsingShadowDecl>(Target)) {
3245 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3246 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003247 }
3248
3249 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003250 = UsingShadowDecl::Create(Context, CurContext,
3251 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003252 UD->addShadowDecl(Shadow);
3253
3254 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003255 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003256 else
John McCall604e7f12009-12-08 07:46:18 +00003257 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003258 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003259
John McCall604e7f12009-12-08 07:46:18 +00003260 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3261 Shadow->setInvalidDecl();
3262
John McCall9f54ad42009-12-10 09:41:52 +00003263 return Shadow;
3264}
John McCall604e7f12009-12-08 07:46:18 +00003265
John McCall9f54ad42009-12-10 09:41:52 +00003266/// Hides a using shadow declaration. This is required by the current
3267/// using-decl implementation when a resolvable using declaration in a
3268/// class is followed by a declaration which would hide or override
3269/// one or more of the using decl's targets; for example:
3270///
3271/// struct Base { void foo(int); };
3272/// struct Derived : Base {
3273/// using Base::foo;
3274/// void foo(int);
3275/// };
3276///
3277/// The governing language is C++03 [namespace.udecl]p12:
3278///
3279/// When a using-declaration brings names from a base class into a
3280/// derived class scope, member functions in the derived class
3281/// override and/or hide member functions with the same name and
3282/// parameter types in a base class (rather than conflicting).
3283///
3284/// There are two ways to implement this:
3285/// (1) optimistically create shadow decls when they're not hidden
3286/// by existing declarations, or
3287/// (2) don't create any shadow decls (or at least don't make them
3288/// visible) until we've fully parsed/instantiated the class.
3289/// The problem with (1) is that we might have to retroactively remove
3290/// a shadow decl, which requires several O(n) operations because the
3291/// decl structures are (very reasonably) not designed for removal.
3292/// (2) avoids this but is very fiddly and phase-dependent.
3293void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3294 // Remove it from the DeclContext...
3295 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003296
John McCall9f54ad42009-12-10 09:41:52 +00003297 // ...and the scope, if applicable...
3298 if (S) {
3299 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3300 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003301 }
3302
John McCall9f54ad42009-12-10 09:41:52 +00003303 // ...and the using decl.
3304 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3305
3306 // TODO: complain somehow if Shadow was used. It shouldn't
3307 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003308}
3309
John McCall7ba107a2009-11-18 02:36:19 +00003310/// Builds a using declaration.
3311///
3312/// \param IsInstantiation - Whether this call arises from an
3313/// instantiation of an unresolved using declaration. We treat
3314/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003315NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3316 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003317 const CXXScopeSpec &SS,
3318 SourceLocation IdentLoc,
3319 DeclarationName Name,
3320 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003321 bool IsInstantiation,
3322 bool IsTypeName,
3323 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003324 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3325 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003326
Anders Carlsson550b14b2009-08-28 05:49:21 +00003327 // FIXME: We ignore attributes for now.
3328 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003330 if (SS.isEmpty()) {
3331 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003332 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003333 }
Mike Stump1eb44332009-09-09 15:08:12 +00003334
John McCall9f54ad42009-12-10 09:41:52 +00003335 // Do the redeclaration lookup in the current scope.
3336 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3337 ForRedeclaration);
3338 Previous.setHideTags(false);
3339 if (S) {
3340 LookupName(Previous, S);
3341
3342 // It is really dumb that we have to do this.
3343 LookupResult::Filter F = Previous.makeFilter();
3344 while (F.hasNext()) {
3345 NamedDecl *D = F.next();
3346 if (!isDeclInScope(D, CurContext, S))
3347 F.erase();
3348 }
3349 F.done();
3350 } else {
3351 assert(IsInstantiation && "no scope in non-instantiation");
3352 assert(CurContext->isRecord() && "scope not record in instantiation");
3353 LookupQualifiedName(Previous, CurContext);
3354 }
3355
Mike Stump1eb44332009-09-09 15:08:12 +00003356 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003357 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3358
John McCall9f54ad42009-12-10 09:41:52 +00003359 // Check for invalid redeclarations.
3360 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3361 return 0;
3362
3363 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003364 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3365 return 0;
3366
John McCallaf8e6ed2009-11-12 03:15:40 +00003367 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003368 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003369 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003370 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003371 // FIXME: not all declaration name kinds are legal here
3372 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3373 UsingLoc, TypenameLoc,
3374 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003375 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003376 } else {
3377 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3378 UsingLoc, SS.getRange(), NNS,
3379 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003380 }
John McCalled976492009-12-04 22:46:56 +00003381 } else {
3382 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3383 SS.getRange(), UsingLoc, NNS, Name,
3384 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003385 }
John McCalled976492009-12-04 22:46:56 +00003386 D->setAccess(AS);
3387 CurContext->addDecl(D);
3388
3389 if (!LookupContext) return D;
3390 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003391
John McCall604e7f12009-12-08 07:46:18 +00003392 if (RequireCompleteDeclContext(SS)) {
3393 UD->setInvalidDecl();
3394 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003395 }
3396
John McCall604e7f12009-12-08 07:46:18 +00003397 // Look up the target name.
3398
John McCalla24dc2e2009-11-17 02:14:36 +00003399 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003400
John McCall604e7f12009-12-08 07:46:18 +00003401 // Unlike most lookups, we don't always want to hide tag
3402 // declarations: tag names are visible through the using declaration
3403 // even if hidden by ordinary names, *except* in a dependent context
3404 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003405 if (!IsInstantiation)
3406 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003407
John McCalla24dc2e2009-11-17 02:14:36 +00003408 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003409
John McCallf36e02d2009-10-09 21:13:30 +00003410 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003411 Diag(IdentLoc, diag::err_no_member)
3412 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003413 UD->setInvalidDecl();
3414 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003415 }
3416
John McCalled976492009-12-04 22:46:56 +00003417 if (R.isAmbiguous()) {
3418 UD->setInvalidDecl();
3419 return UD;
3420 }
Mike Stump1eb44332009-09-09 15:08:12 +00003421
John McCall7ba107a2009-11-18 02:36:19 +00003422 if (IsTypeName) {
3423 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003424 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003425 Diag(IdentLoc, diag::err_using_typename_non_type);
3426 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3427 Diag((*I)->getUnderlyingDecl()->getLocation(),
3428 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003429 UD->setInvalidDecl();
3430 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003431 }
3432 } else {
3433 // If we asked for a non-typename and we got a type, error out,
3434 // but only if this is an instantiation of an unresolved using
3435 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003436 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003437 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3438 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003439 UD->setInvalidDecl();
3440 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003441 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003442 }
3443
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003444 // C++0x N2914 [namespace.udecl]p6:
3445 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003446 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003447 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3448 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003449 UD->setInvalidDecl();
3450 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003451 }
Mike Stump1eb44332009-09-09 15:08:12 +00003452
John McCall9f54ad42009-12-10 09:41:52 +00003453 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3454 if (!CheckUsingShadowDecl(UD, *I, Previous))
3455 BuildUsingShadowDecl(S, UD, *I);
3456 }
John McCall9488ea12009-11-17 05:59:44 +00003457
3458 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003459}
3460
John McCall9f54ad42009-12-10 09:41:52 +00003461/// Checks that the given using declaration is not an invalid
3462/// redeclaration. Note that this is checking only for the using decl
3463/// itself, not for any ill-formedness among the UsingShadowDecls.
3464bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3465 bool isTypeName,
3466 const CXXScopeSpec &SS,
3467 SourceLocation NameLoc,
3468 const LookupResult &Prev) {
3469 // C++03 [namespace.udecl]p8:
3470 // C++0x [namespace.udecl]p10:
3471 // A using-declaration is a declaration and can therefore be used
3472 // repeatedly where (and only where) multiple declarations are
3473 // allowed.
3474 // That's only in file contexts.
3475 if (CurContext->getLookupContext()->isFileContext())
3476 return false;
3477
3478 NestedNameSpecifier *Qual
3479 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3480
3481 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3482 NamedDecl *D = *I;
3483
3484 bool DTypename;
3485 NestedNameSpecifier *DQual;
3486 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3487 DTypename = UD->isTypeName();
3488 DQual = UD->getTargetNestedNameDecl();
3489 } else if (UnresolvedUsingValueDecl *UD
3490 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3491 DTypename = false;
3492 DQual = UD->getTargetNestedNameSpecifier();
3493 } else if (UnresolvedUsingTypenameDecl *UD
3494 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3495 DTypename = true;
3496 DQual = UD->getTargetNestedNameSpecifier();
3497 } else continue;
3498
3499 // using decls differ if one says 'typename' and the other doesn't.
3500 // FIXME: non-dependent using decls?
3501 if (isTypeName != DTypename) continue;
3502
3503 // using decls differ if they name different scopes (but note that
3504 // template instantiation can cause this check to trigger when it
3505 // didn't before instantiation).
3506 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3507 Context.getCanonicalNestedNameSpecifier(DQual))
3508 continue;
3509
3510 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003511 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003512 return true;
3513 }
3514
3515 return false;
3516}
3517
John McCall604e7f12009-12-08 07:46:18 +00003518
John McCalled976492009-12-04 22:46:56 +00003519/// Checks that the given nested-name qualifier used in a using decl
3520/// in the current context is appropriately related to the current
3521/// scope. If an error is found, diagnoses it and returns true.
3522bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3523 const CXXScopeSpec &SS,
3524 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003525 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003526
John McCall604e7f12009-12-08 07:46:18 +00003527 if (!CurContext->isRecord()) {
3528 // C++03 [namespace.udecl]p3:
3529 // C++0x [namespace.udecl]p8:
3530 // A using-declaration for a class member shall be a member-declaration.
3531
3532 // If we weren't able to compute a valid scope, it must be a
3533 // dependent class scope.
3534 if (!NamedContext || NamedContext->isRecord()) {
3535 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3536 << SS.getRange();
3537 return true;
3538 }
3539
3540 // Otherwise, everything is known to be fine.
3541 return false;
3542 }
3543
3544 // The current scope is a record.
3545
3546 // If the named context is dependent, we can't decide much.
3547 if (!NamedContext) {
3548 // FIXME: in C++0x, we can diagnose if we can prove that the
3549 // nested-name-specifier does not refer to a base class, which is
3550 // still possible in some cases.
3551
3552 // Otherwise we have to conservatively report that things might be
3553 // okay.
3554 return false;
3555 }
3556
3557 if (!NamedContext->isRecord()) {
3558 // Ideally this would point at the last name in the specifier,
3559 // but we don't have that level of source info.
3560 Diag(SS.getRange().getBegin(),
3561 diag::err_using_decl_nested_name_specifier_is_not_class)
3562 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3563 return true;
3564 }
3565
3566 if (getLangOptions().CPlusPlus0x) {
3567 // C++0x [namespace.udecl]p3:
3568 // In a using-declaration used as a member-declaration, the
3569 // nested-name-specifier shall name a base class of the class
3570 // being defined.
3571
3572 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3573 cast<CXXRecordDecl>(NamedContext))) {
3574 if (CurContext == NamedContext) {
3575 Diag(NameLoc,
3576 diag::err_using_decl_nested_name_specifier_is_current_class)
3577 << SS.getRange();
3578 return true;
3579 }
3580
3581 Diag(SS.getRange().getBegin(),
3582 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3583 << (NestedNameSpecifier*) SS.getScopeRep()
3584 << cast<CXXRecordDecl>(CurContext)
3585 << SS.getRange();
3586 return true;
3587 }
3588
3589 return false;
3590 }
3591
3592 // C++03 [namespace.udecl]p4:
3593 // A using-declaration used as a member-declaration shall refer
3594 // to a member of a base class of the class being defined [etc.].
3595
3596 // Salient point: SS doesn't have to name a base class as long as
3597 // lookup only finds members from base classes. Therefore we can
3598 // diagnose here only if we can prove that that can't happen,
3599 // i.e. if the class hierarchies provably don't intersect.
3600
3601 // TODO: it would be nice if "definitely valid" results were cached
3602 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3603 // need to be repeated.
3604
3605 struct UserData {
3606 llvm::DenseSet<const CXXRecordDecl*> Bases;
3607
3608 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3609 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3610 Data->Bases.insert(Base);
3611 return true;
3612 }
3613
3614 bool hasDependentBases(const CXXRecordDecl *Class) {
3615 return !Class->forallBases(collect, this);
3616 }
3617
3618 /// Returns true if the base is dependent or is one of the
3619 /// accumulated base classes.
3620 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3621 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3622 return !Data->Bases.count(Base);
3623 }
3624
3625 bool mightShareBases(const CXXRecordDecl *Class) {
3626 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3627 }
3628 };
3629
3630 UserData Data;
3631
3632 // Returns false if we find a dependent base.
3633 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3634 return false;
3635
3636 // Returns false if the class has a dependent base or if it or one
3637 // of its bases is present in the base set of the current context.
3638 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3639 return false;
3640
3641 Diag(SS.getRange().getBegin(),
3642 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3643 << (NestedNameSpecifier*) SS.getScopeRep()
3644 << cast<CXXRecordDecl>(CurContext)
3645 << SS.getRange();
3646
3647 return true;
John McCalled976492009-12-04 22:46:56 +00003648}
3649
Mike Stump1eb44332009-09-09 15:08:12 +00003650Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003651 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003652 SourceLocation AliasLoc,
3653 IdentifierInfo *Alias,
3654 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003655 SourceLocation IdentLoc,
3656 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Anders Carlsson81c85c42009-03-28 23:53:49 +00003658 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003659 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3660 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003661
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003662 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003663 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003664 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003665 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003666 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003667 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003668 if (!R.isAmbiguous() && !R.empty() &&
3669 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003670 return DeclPtrTy();
3671 }
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003673 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3674 diag::err_redefinition_different_kind;
3675 Diag(AliasLoc, DiagID) << Alias;
3676 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003677 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003678 }
3679
John McCalla24dc2e2009-11-17 02:14:36 +00003680 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003681 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003682
John McCallf36e02d2009-10-09 21:13:30 +00003683 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003684 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003685 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003686 }
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003688 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003689 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3690 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003691 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003692 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003693
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003694 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003695 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003696}
3697
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003698void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3699 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003700 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3701 !Constructor->isUsed()) &&
3702 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Eli Friedman80c30da2009-11-09 19:20:36 +00003704 CXXRecordDecl *ClassDecl
3705 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3706 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003707
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003708 DeclContext *PreviousContext = CurContext;
3709 CurContext = Constructor;
3710 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003711 Diag(CurrentLocation, diag::note_member_synthesized_at)
3712 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003713 Constructor->setInvalidDecl();
3714 } else {
3715 Constructor->setUsed();
3716 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003717 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003718}
3719
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003720void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003721 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003722 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3723 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003724 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003725 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003726
3727 DeclContext *PreviousContext = CurContext;
3728 CurContext = Destructor;
3729
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003730 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003731 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003732 // implicitly defined, all the implicitly-declared default destructors
3733 // for its base class and its non-static data members shall have been
3734 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3736 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003737 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003738 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003739 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003740 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003741 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3742 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3743 else
Mike Stump1eb44332009-09-09 15:08:12 +00003744 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003745 "DefineImplicitDestructor - missing dtor in a base class");
3746 }
3747 }
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003749 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3750 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003751 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3752 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3753 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003754 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003755 CXXRecordDecl *FieldClassDecl
3756 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3757 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003758 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003759 const_cast<CXXDestructorDecl*>(
3760 FieldClassDecl->getDestructor(Context)))
3761 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3762 else
Mike Stump1eb44332009-09-09 15:08:12 +00003763 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003764 "DefineImplicitDestructor - missing dtor in class of a data member");
3765 }
3766 }
3767 }
Anders Carlsson37909802009-11-30 21:24:50 +00003768
3769 // FIXME: If CheckDestructor fails, we should emit a note about where the
3770 // implicit destructor was needed.
3771 if (CheckDestructor(Destructor)) {
3772 Diag(CurrentLocation, diag::note_member_synthesized_at)
3773 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3774
3775 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003776 CurContext = PreviousContext;
3777
Anders Carlsson37909802009-11-30 21:24:50 +00003778 return;
3779 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003780 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003781
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003782 Destructor->setUsed();
3783}
3784
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003785void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3786 CXXMethodDecl *MethodDecl) {
3787 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3788 MethodDecl->getOverloadedOperator() == OO_Equal &&
3789 !MethodDecl->isUsed()) &&
3790 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003791
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003792 CXXRecordDecl *ClassDecl
3793 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003795 DeclContext *PreviousContext = CurContext;
3796 CurContext = MethodDecl;
3797
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003798 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003799 // Before the implicitly-declared copy assignment operator for a class is
3800 // implicitly defined, all implicitly-declared copy assignment operators
3801 // for its direct base classes and its nonstatic data members shall have
3802 // been implicitly defined.
3803 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003804 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3805 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003806 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003807 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003808 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003809 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3810 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003811 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3812 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003813 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3814 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003815 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3816 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3817 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003818 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003819 CXXRecordDecl *FieldClassDecl
3820 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003821 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003822 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3823 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003824 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003825 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003826 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003827 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3828 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003829 Diag(CurrentLocation, diag::note_first_required_here);
3830 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003831 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003832 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003833 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3834 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003835 Diag(CurrentLocation, diag::note_first_required_here);
3836 err = true;
3837 }
3838 }
3839 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003840 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003841
3842 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003843}
3844
3845CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003846Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3847 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003848 CXXRecordDecl *ClassDecl) {
3849 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3850 QualType RHSType(LHSType);
3851 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003852 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003853 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003854 RHSType = Context.getCVRQualifiedType(RHSType,
3855 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003856 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003857 LHSType,
3858 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003859 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003860 RHSType,
3861 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003862 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003863 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003864 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003865 CandidateSet);
3866 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003867 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003868 return cast<CXXMethodDecl>(Best->Function);
3869 assert(false &&
3870 "getAssignOperatorMethod - copy assignment operator method not found");
3871 return 0;
3872}
3873
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003874void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3875 CXXConstructorDecl *CopyConstructor,
3876 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003877 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003878 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003879 !CopyConstructor->isUsed()) &&
3880 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003882 CXXRecordDecl *ClassDecl
3883 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3884 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003885
3886 DeclContext *PreviousContext = CurContext;
3887 CurContext = CopyConstructor;
3888
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003889 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003890 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003891 // implicitly defined, all the implicitly-declared copy constructors
3892 // for its base class and its non-static data members shall have been
3893 // implicitly defined.
3894 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3895 Base != ClassDecl->bases_end(); ++Base) {
3896 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003897 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003898 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003899 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003900 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003901 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003902 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3903 FieldEnd = ClassDecl->field_end();
3904 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003905 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3906 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3907 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003908 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003909 CXXRecordDecl *FieldClassDecl
3910 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003911 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003912 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003913 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003914 }
3915 }
3916 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003917
3918 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003919}
3920
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003921Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003922Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003923 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003924 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003925 bool RequiresZeroInit,
3926 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003927 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Douglas Gregor39da0b82009-09-09 23:08:42 +00003929 // C++ [class.copy]p15:
3930 // Whenever a temporary class object is copied using a copy constructor, and
3931 // this object and the copy have the same cv-unqualified type, an
3932 // implementation is permitted to treat the original and the copy as two
3933 // different ways of referring to the same object and not perform a copy at
3934 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003935
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003936 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003937 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003938 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003939 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3940 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3941 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003942 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3943 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003944 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3945 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003946 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3947 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3948 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003949
3950 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3951 Elidable = !CE->getCallReturnType()->isReferenceType();
3952 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003953 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003954 else if (isa<CXXConstructExpr>(E))
3955 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003956 }
Mike Stump1eb44332009-09-09 15:08:12 +00003957
3958 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003959 Elidable, move(ExprArgs), RequiresZeroInit,
3960 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003961}
3962
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003963/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3964/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003965Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003966Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3967 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003968 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003969 bool RequiresZeroInit,
3970 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003971 unsigned NumExprs = ExprArgs.size();
3972 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Douglas Gregor7edfb692009-11-23 12:27:39 +00003974 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003975 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003976 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003977 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003978}
3979
Mike Stump1eb44332009-09-09 15:08:12 +00003980bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003981 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003982 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003983 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003984 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003985 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003986 if (TempResult.isInvalid())
3987 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003989 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003990 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003991 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00003992 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003993
Anders Carlssonfe2de492009-08-25 05:18:00 +00003994 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003995}
3996
John McCall68c6c9a2010-02-02 09:10:11 +00003997void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
3998 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
John McCall4f9506a2010-02-02 08:45:54 +00003999 if (!ClassDecl->hasTrivialDestructor()) {
4000 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4001 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004002 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004003 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004004}
4005
Mike Stump1eb44332009-09-09 15:08:12 +00004006/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004007/// ActOnDeclarator, when a C++ direct initializer is present.
4008/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004009void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4010 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004011 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004012 SourceLocation *CommaLocs,
4013 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004014 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004015 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004016
4017 // If there is no declaration, there was an error parsing it. Just ignore
4018 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004019 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004020 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004021
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004022 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4023 if (!VDecl) {
4024 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4025 RealDecl->setInvalidDecl();
4026 return;
4027 }
4028
Douglas Gregor83ddad32009-08-26 21:14:46 +00004029 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004030 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004031 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4032 //
4033 // Clients that want to distinguish between the two forms, can check for
4034 // direct initializer using VarDecl::hasCXXDirectInitializer().
4035 // A major benefit is that clients that don't particularly care about which
4036 // exactly form was it (like the CodeGen) can handle both cases without
4037 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004038
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004039 // C++ 8.5p11:
4040 // The form of initialization (using parentheses or '=') is generally
4041 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004042 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004043 QualType DeclInitType = VDecl->getType();
4044 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004045 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004046
Douglas Gregor4dffad62010-02-11 22:55:30 +00004047 if (!VDecl->getType()->isDependentType() &&
4048 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004049 diag::err_typecheck_decl_incomplete_type)) {
4050 VDecl->setInvalidDecl();
4051 return;
4052 }
4053
Douglas Gregor90f93822009-12-22 22:17:25 +00004054 // The variable can not have an abstract class type.
4055 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4056 diag::err_abstract_type_in_decl,
4057 AbstractVariableType))
4058 VDecl->setInvalidDecl();
4059
Sebastian Redl31310a22010-02-01 20:16:42 +00004060 const VarDecl *Def;
4061 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004062 Diag(VDecl->getLocation(), diag::err_redefinition)
4063 << VDecl->getDeclName();
4064 Diag(Def->getLocation(), diag::note_previous_definition);
4065 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004066 return;
4067 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004068
4069 // If either the declaration has a dependent type or if any of the
4070 // expressions is type-dependent, we represent the initialization
4071 // via a ParenListExpr for later use during template instantiation.
4072 if (VDecl->getType()->isDependentType() ||
4073 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4074 // Let clients know that initialization was done with a direct initializer.
4075 VDecl->setCXXDirectInitializer(true);
4076
4077 // Store the initialization expressions as a ParenListExpr.
4078 unsigned NumExprs = Exprs.size();
4079 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4080 (Expr **)Exprs.release(),
4081 NumExprs, RParenLoc));
4082 return;
4083 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004084
4085 // Capture the variable that is being initialized and the style of
4086 // initialization.
4087 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4088
4089 // FIXME: Poor source location information.
4090 InitializationKind Kind
4091 = InitializationKind::CreateDirect(VDecl->getLocation(),
4092 LParenLoc, RParenLoc);
4093
4094 InitializationSequence InitSeq(*this, Entity, Kind,
4095 (Expr**)Exprs.get(), Exprs.size());
4096 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4097 if (Result.isInvalid()) {
4098 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004099 return;
4100 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004101
4102 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004103 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004104 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004105
John McCall68c6c9a2010-02-02 09:10:11 +00004106 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4107 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004108}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004109
Douglas Gregor19aeac62009-11-14 03:27:21 +00004110/// \brief Add the applicable constructor candidates for an initialization
4111/// by constructor.
4112static void AddConstructorInitializationCandidates(Sema &SemaRef,
4113 QualType ClassType,
4114 Expr **Args,
4115 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004116 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004117 OverloadCandidateSet &CandidateSet) {
4118 // C++ [dcl.init]p14:
4119 // If the initialization is direct-initialization, or if it is
4120 // copy-initialization where the cv-unqualified version of the
4121 // source type is the same class as, or a derived class of, the
4122 // class of the destination, constructors are considered. The
4123 // applicable constructors are enumerated (13.3.1.3), and the
4124 // best one is chosen through overload resolution (13.3). The
4125 // constructor so selected is called to initialize the object,
4126 // with the initializer expression(s) as its argument(s). If no
4127 // constructor applies, or the overload resolution is ambiguous,
4128 // the initialization is ill-formed.
4129 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4130 assert(ClassRec && "Can only initialize a class type here");
4131
4132 // FIXME: When we decide not to synthesize the implicitly-declared
4133 // constructors, we'll need to make them appear here.
4134
4135 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4136 DeclarationName ConstructorName
4137 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4138 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4139 DeclContext::lookup_const_iterator Con, ConEnd;
4140 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4141 Con != ConEnd; ++Con) {
4142 // Find the constructor (which may be a template).
4143 CXXConstructorDecl *Constructor = 0;
4144 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4145 if (ConstructorTmpl)
4146 Constructor
4147 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4148 else
4149 Constructor = cast<CXXConstructorDecl>(*Con);
4150
Douglas Gregor20093b42009-12-09 23:02:17 +00004151 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4152 (Kind.getKind() == InitializationKind::IK_Value) ||
4153 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004154 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004155 ((Kind.getKind() == InitializationKind::IK_Default) &&
4156 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004157 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004158 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004159 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004160 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004161 Args, NumArgs, CandidateSet);
4162 else
John McCall86820f52010-01-26 01:37:31 +00004163 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4164 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004165 }
4166 }
4167}
4168
4169/// \brief Attempt to perform initialization by constructor
4170/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4171/// copy-initialization.
4172///
4173/// This routine determines whether initialization by constructor is possible,
4174/// but it does not emit any diagnostics in the case where the initialization
4175/// is ill-formed.
4176///
4177/// \param ClassType the type of the object being initialized, which must have
4178/// class type.
4179///
4180/// \param Args the arguments provided to initialize the object
4181///
4182/// \param NumArgs the number of arguments provided to initialize the object
4183///
4184/// \param Kind the type of initialization being performed
4185///
4186/// \returns the constructor used to initialize the object, if successful.
4187/// Otherwise, emits a diagnostic and returns NULL.
4188CXXConstructorDecl *
4189Sema::TryInitializationByConstructor(QualType ClassType,
4190 Expr **Args, unsigned NumArgs,
4191 SourceLocation Loc,
4192 InitializationKind Kind) {
4193 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004194 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004195 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4196 CandidateSet);
4197
4198 // Determine whether we found a constructor we can use.
4199 OverloadCandidateSet::iterator Best;
4200 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4201 case OR_Success:
4202 case OR_Deleted:
4203 // We found a constructor. Return it.
4204 return cast<CXXConstructorDecl>(Best->Function);
4205
4206 case OR_No_Viable_Function:
4207 case OR_Ambiguous:
4208 // Overload resolution failed. Return nothing.
4209 return 0;
4210 }
4211
4212 // Silence GCC warning
4213 return 0;
4214}
4215
Douglas Gregor39da0b82009-09-09 23:08:42 +00004216/// \brief Given a constructor and the set of arguments provided for the
4217/// constructor, convert the arguments and add any required default arguments
4218/// to form a proper call to this constructor.
4219///
4220/// \returns true if an error occurred, false otherwise.
4221bool
4222Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4223 MultiExprArg ArgsPtr,
4224 SourceLocation Loc,
4225 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4226 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4227 unsigned NumArgs = ArgsPtr.size();
4228 Expr **Args = (Expr **)ArgsPtr.get();
4229
4230 const FunctionProtoType *Proto
4231 = Constructor->getType()->getAs<FunctionProtoType>();
4232 assert(Proto && "Constructor without a prototype?");
4233 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004234
4235 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004236 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004237 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004238 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004239 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004240
4241 VariadicCallType CallType =
4242 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4243 llvm::SmallVector<Expr *, 8> AllArgs;
4244 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4245 Proto, 0, Args, NumArgs, AllArgs,
4246 CallType);
4247 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4248 ConvertedArgs.push_back(AllArgs[i]);
4249 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004250}
4251
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004252/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4253/// determine whether they are reference-related,
4254/// reference-compatible, reference-compatible with added
4255/// qualification, or incompatible, for use in C++ initialization by
4256/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4257/// type, and the first type (T1) is the pointee type of the reference
4258/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004259Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004260Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004261 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004262 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004263 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004264 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004265 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004266
Douglas Gregor393896f2009-11-05 13:06:35 +00004267 QualType T1 = Context.getCanonicalType(OrigT1);
4268 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004269 Qualifiers T1Quals, T2Quals;
4270 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4271 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004272
4273 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004274 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004275 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004276 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004277 if (UnqualT1 == UnqualT2)
4278 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004279 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4280 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4281 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004282 DerivedToBase = true;
4283 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004284 return Ref_Incompatible;
4285
4286 // At this point, we know that T1 and T2 are reference-related (at
4287 // least).
4288
Chandler Carruth28e318c2009-12-29 07:16:59 +00004289 // If the type is an array type, promote the element qualifiers to the type
4290 // for comparison.
4291 if (isa<ArrayType>(T1) && T1Quals)
4292 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4293 if (isa<ArrayType>(T2) && T2Quals)
4294 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4295
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004296 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004297 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004298 // reference-related to T2 and cv1 is the same cv-qualification
4299 // as, or greater cv-qualification than, cv2. For purposes of
4300 // overload resolution, cases for which cv1 is greater
4301 // cv-qualification than cv2 are identified as
4302 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004303 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004304 return Ref_Compatible;
4305 else if (T1.isMoreQualifiedThan(T2))
4306 return Ref_Compatible_With_Added_Qualification;
4307 else
4308 return Ref_Related;
4309}
4310
4311/// CheckReferenceInit - Check the initialization of a reference
4312/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4313/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004314/// list), and DeclType is the type of the declaration. When ICS is
4315/// non-null, this routine will compute the implicit conversion
4316/// sequence according to C++ [over.ics.ref] and will not produce any
4317/// diagnostics; when ICS is null, it will emit diagnostics when any
4318/// errors are found. Either way, a return value of true indicates
4319/// that there was a failure, a return value of false indicates that
4320/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004321///
4322/// When @p SuppressUserConversions, user-defined conversions are
4323/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004324/// When @p AllowExplicit, we also permit explicit user-defined
4325/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004326/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004327/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4328/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004329bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004330Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004331 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004332 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004333 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004334 ImplicitConversionSequence *ICS,
4335 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004336 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4337
Ted Kremenek6217b802009-07-29 21:53:49 +00004338 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004339 QualType T2 = Init->getType();
4340
Douglas Gregor904eed32008-11-10 20:40:00 +00004341 // If the initializer is the address of an overloaded function, try
4342 // to resolve the overloaded function. If all goes well, T2 is the
4343 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004344 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004345 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004346 ICS != 0);
4347 if (Fn) {
4348 // Since we're performing this reference-initialization for
4349 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004350 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004351 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004352 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004353
Anders Carlsson96ad5332009-10-21 17:16:23 +00004354 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004355 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004356
4357 T2 = Fn->getType();
4358 }
4359 }
4360
Douglas Gregor15da57e2008-10-29 02:00:59 +00004361 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004362 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004363 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004364 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4365 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004366 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004367 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004368
4369 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004370 if (ICS) {
4371 ICS->setBad();
4372 ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4373 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004374
4375 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004376 // A reference to type "cv1 T1" is initialized by an expression
4377 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004378
4379 // -- If the initializer expression
4380
Sebastian Redla9845802009-03-29 15:27:50 +00004381 // Rvalue references cannot bind to lvalues (N2812).
4382 // There is absolutely no situation where they can. In particular, note that
4383 // this is ill-formed, even if B has a user-defined conversion to A&&:
4384 // B b;
4385 // A&& r = b;
4386 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4387 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004388 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004389 << Init->getSourceRange();
4390 return true;
4391 }
4392
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004393 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004394 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4395 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004396 //
4397 // Note that the bit-field check is skipped if we are just computing
4398 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004399 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004400 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004401 BindsDirectly = true;
4402
Douglas Gregor15da57e2008-10-29 02:00:59 +00004403 if (ICS) {
4404 // C++ [over.ics.ref]p1:
4405 // When a parameter of reference type binds directly (8.5.3)
4406 // to an argument expression, the implicit conversion sequence
4407 // is the identity conversion, unless the argument expression
4408 // has a type that is a derived class of the parameter type,
4409 // in which case the implicit conversion sequence is a
4410 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004411 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004412 ICS->Standard.First = ICK_Identity;
4413 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4414 ICS->Standard.Third = ICK_Identity;
4415 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004416 ICS->Standard.setToType(0, T2);
4417 ICS->Standard.setToType(1, T1);
4418 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004419 ICS->Standard.ReferenceBinding = true;
4420 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004421 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004422 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004423
4424 // Nothing more to do: the inaccessibility/ambiguity check for
4425 // derived-to-base conversions is suppressed when we're
4426 // computing the implicit conversion sequence (C++
4427 // [over.best.ics]p2).
4428 return false;
4429 } else {
4430 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004431 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4432 if (DerivedToBase)
4433 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004434 else if(CheckExceptionSpecCompatibility(Init, T1))
4435 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004436 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004437 }
4438 }
4439
4440 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004441 // implicitly converted to an lvalue of type "cv3 T3,"
4442 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004443 // 92) (this conversion is selected by enumerating the
4444 // applicable conversion functions (13.3.1.6) and choosing
4445 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004446 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004447 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004448 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004449 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004450
John McCall5769d612010-02-08 23:07:23 +00004451 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004452 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004453 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004454 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004455 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004456 NamedDecl *D = *I;
4457 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4458 if (isa<UsingShadowDecl>(D))
4459 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4460
Mike Stump1eb44332009-09-09 15:08:12 +00004461 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004462 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004463 CXXConversionDecl *Conv;
4464 if (ConvTemplate)
4465 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4466 else
John McCall701c89e2009-12-03 04:06:58 +00004467 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004468
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004469 // If the conversion function doesn't return a reference type,
4470 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004471 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004472 (AllowExplicit || !Conv->isExplicit())) {
4473 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004474 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004475 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004476 else
John McCall86820f52010-01-26 01:37:31 +00004477 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4478 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004479 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004480 }
4481
4482 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004483 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004484 case OR_Success:
4485 // This is a direct binding.
4486 BindsDirectly = true;
4487
4488 if (ICS) {
4489 // C++ [over.ics.ref]p1:
4490 //
4491 // [...] If the parameter binds directly to the result of
4492 // applying a conversion function to the argument
4493 // expression, the implicit conversion sequence is a
4494 // user-defined conversion sequence (13.3.3.1.2), with the
4495 // second standard conversion sequence either an identity
4496 // conversion or, if the conversion function returns an
4497 // entity of a type that is a derived class of the parameter
4498 // type, a derived-to-base Conversion.
John McCall1d318332010-01-12 00:44:57 +00004499 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004500 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4501 ICS->UserDefined.After = Best->FinalConversion;
4502 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004503 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004504 assert(ICS->UserDefined.After.ReferenceBinding &&
4505 ICS->UserDefined.After.DirectBinding &&
4506 "Expected a direct reference binding!");
4507 return false;
4508 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004509 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004510 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004511 CastExpr::CK_UserDefinedConversion,
4512 cast<CXXMethodDecl>(Best->Function),
4513 Owned(Init));
4514 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004515
4516 if (CheckExceptionSpecCompatibility(Init, T1))
4517 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004518 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4519 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004520 }
4521 break;
4522
4523 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004524 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004525 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004526 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4527 Cand != CandidateSet.end(); ++Cand)
4528 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004529 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004530 break;
4531 }
4532 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4533 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004534 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004535 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004537 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004538 case OR_Deleted:
4539 // There was no suitable conversion, or we found a deleted
4540 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004541 break;
4542 }
4543 }
Mike Stump1eb44332009-09-09 15:08:12 +00004544
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004545 if (BindsDirectly) {
4546 // C++ [dcl.init.ref]p4:
4547 // [...] In all cases where the reference-related or
4548 // reference-compatible relationship of two types is used to
4549 // establish the validity of a reference binding, and T1 is a
4550 // base class of T2, a program that necessitates such a binding
4551 // is ill-formed if T1 is an inaccessible (clause 11) or
4552 // ambiguous (10.2) base class of T2.
4553 //
4554 // Note that we only check this condition when we're allowed to
4555 // complain about errors, because we should not be checking for
4556 // ambiguity (or inaccessibility) unless the reference binding
4557 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004558 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004559 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004560 Init->getSourceRange(),
4561 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004562 else
4563 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004564 }
4565
4566 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004567 // type (i.e., cv1 shall be const), or the reference shall be an
4568 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004569 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004570 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004571 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004572 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004573 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004574 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004575 return true;
4576 }
4577
4578 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004579 // class type, and "cv1 T1" is reference-compatible with
4580 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004581 // following ways (the choice is implementation-defined):
4582 //
4583 // -- The reference is bound to the object represented by
4584 // the rvalue (see 3.10) or to a sub-object within that
4585 // object.
4586 //
Eli Friedman33a31382009-08-05 19:21:58 +00004587 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004588 // a constructor is called to copy the entire rvalue
4589 // object into the temporary. The reference is bound to
4590 // the temporary or to a sub-object within the
4591 // temporary.
4592 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004593 // The constructor that would be used to make the copy
4594 // shall be callable whether or not the copy is actually
4595 // done.
4596 //
Sebastian Redla9845802009-03-29 15:27:50 +00004597 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004598 // freedom, so we will always take the first option and never build
4599 // a temporary in this case. FIXME: We will, however, have to check
4600 // for the presence of a copy constructor in C++98/03 mode.
4601 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004602 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4603 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004604 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004605 ICS->Standard.First = ICK_Identity;
4606 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4607 ICS->Standard.Third = ICK_Identity;
4608 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004609 ICS->Standard.setToType(0, T2);
4610 ICS->Standard.setToType(1, T1);
4611 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004612 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004613 ICS->Standard.DirectBinding = false;
4614 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004615 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004616 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004617 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4618 if (DerivedToBase)
4619 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004620 else if(CheckExceptionSpecCompatibility(Init, T1))
4621 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004622 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004623 }
4624 return false;
4625 }
4626
Eli Friedman33a31382009-08-05 19:21:58 +00004627 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004628 // initialized from the initializer expression using the
4629 // rules for a non-reference copy initialization (8.5). The
4630 // reference is then bound to the temporary. If T1 is
4631 // reference-related to T2, cv1 must be the same
4632 // cv-qualification as, or greater cv-qualification than,
4633 // cv2; otherwise, the program is ill-formed.
4634 if (RefRelationship == Ref_Related) {
4635 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4636 // we would be reference-compatible or reference-compatible with
4637 // added qualification. But that wasn't the case, so the reference
4638 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004639 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004640 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004641 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004642 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004643 return true;
4644 }
4645
Douglas Gregor734d9862009-01-30 23:27:23 +00004646 // If at least one of the types is a class type, the types are not
4647 // related, and we aren't allowed any user conversions, the
4648 // reference binding fails. This case is important for breaking
4649 // recursion, since TryImplicitConversion below will attempt to
4650 // create a temporary through the use of a copy constructor.
4651 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4652 (T1->isRecordType() || T2->isRecordType())) {
4653 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004654 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004655 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004656 return true;
4657 }
4658
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004659 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004660 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004661 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004662 //
Sebastian Redla9845802009-03-29 15:27:50 +00004663 // When a parameter of reference type is not bound directly to
4664 // an argument expression, the conversion sequence is the one
4665 // required to convert the argument expression to the
4666 // underlying type of the reference according to
4667 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4668 // to copy-initializing a temporary of the underlying type with
4669 // the argument expression. Any difference in top-level
4670 // cv-qualification is subsumed by the initialization itself
4671 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004672 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4673 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004674 /*ForceRValue=*/false,
4675 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004676
Sebastian Redla9845802009-03-29 15:27:50 +00004677 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004678 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004679 ICS->Standard.ReferenceBinding = true;
4680 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004681 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004682 ICS->UserDefined.After.ReferenceBinding = true;
4683 ICS->UserDefined.After.RRefBinding = isRValRef;
4684 }
John McCall1d318332010-01-12 00:44:57 +00004685 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004686 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004687 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004688 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004689 false, false,
4690 Conversions);
4691 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004692 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004693 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004694 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004695 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004696 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004697 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004698 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004699 }
4700 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004701 else {
4702 if (isRValRef)
4703 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4704 << Init->getSourceRange();
4705 else
4706 Diag(DeclLoc, diag::err_invalid_initialization)
4707 << DeclType << Init->getType() << Init->getSourceRange();
4708 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004709 }
4710 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004711 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004712}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004713
Anders Carlsson20d45d22009-12-12 00:32:00 +00004714static inline bool
4715CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4716 const FunctionDecl *FnDecl) {
4717 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4718 if (isa<NamespaceDecl>(DC)) {
4719 return SemaRef.Diag(FnDecl->getLocation(),
4720 diag::err_operator_new_delete_declared_in_namespace)
4721 << FnDecl->getDeclName();
4722 }
4723
4724 if (isa<TranslationUnitDecl>(DC) &&
4725 FnDecl->getStorageClass() == FunctionDecl::Static) {
4726 return SemaRef.Diag(FnDecl->getLocation(),
4727 diag::err_operator_new_delete_declared_static)
4728 << FnDecl->getDeclName();
4729 }
4730
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004731 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004732}
4733
Anders Carlsson156c78e2009-12-13 17:53:43 +00004734static inline bool
4735CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4736 CanQualType ExpectedResultType,
4737 CanQualType ExpectedFirstParamType,
4738 unsigned DependentParamTypeDiag,
4739 unsigned InvalidParamTypeDiag) {
4740 QualType ResultType =
4741 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4742
4743 // Check that the result type is not dependent.
4744 if (ResultType->isDependentType())
4745 return SemaRef.Diag(FnDecl->getLocation(),
4746 diag::err_operator_new_delete_dependent_result_type)
4747 << FnDecl->getDeclName() << ExpectedResultType;
4748
4749 // Check that the result type is what we expect.
4750 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4751 return SemaRef.Diag(FnDecl->getLocation(),
4752 diag::err_operator_new_delete_invalid_result_type)
4753 << FnDecl->getDeclName() << ExpectedResultType;
4754
4755 // A function template must have at least 2 parameters.
4756 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4757 return SemaRef.Diag(FnDecl->getLocation(),
4758 diag::err_operator_new_delete_template_too_few_parameters)
4759 << FnDecl->getDeclName();
4760
4761 // The function decl must have at least 1 parameter.
4762 if (FnDecl->getNumParams() == 0)
4763 return SemaRef.Diag(FnDecl->getLocation(),
4764 diag::err_operator_new_delete_too_few_parameters)
4765 << FnDecl->getDeclName();
4766
4767 // Check the the first parameter type is not dependent.
4768 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4769 if (FirstParamType->isDependentType())
4770 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4771 << FnDecl->getDeclName() << ExpectedFirstParamType;
4772
4773 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004774 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004775 ExpectedFirstParamType)
4776 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4777 << FnDecl->getDeclName() << ExpectedFirstParamType;
4778
4779 return false;
4780}
4781
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004782static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004783CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004784 // C++ [basic.stc.dynamic.allocation]p1:
4785 // A program is ill-formed if an allocation function is declared in a
4786 // namespace scope other than global scope or declared static in global
4787 // scope.
4788 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4789 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004790
4791 CanQualType SizeTy =
4792 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4793
4794 // C++ [basic.stc.dynamic.allocation]p1:
4795 // The return type shall be void*. The first parameter shall have type
4796 // std::size_t.
4797 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4798 SizeTy,
4799 diag::err_operator_new_dependent_param_type,
4800 diag::err_operator_new_param_type))
4801 return true;
4802
4803 // C++ [basic.stc.dynamic.allocation]p1:
4804 // The first parameter shall not have an associated default argument.
4805 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004806 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004807 diag::err_operator_new_default_arg)
4808 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4809
4810 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004811}
4812
4813static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004814CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4815 // C++ [basic.stc.dynamic.deallocation]p1:
4816 // A program is ill-formed if deallocation functions are declared in a
4817 // namespace scope other than global scope or declared static in global
4818 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004819 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4820 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004821
4822 // C++ [basic.stc.dynamic.deallocation]p2:
4823 // Each deallocation function shall return void and its first parameter
4824 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004825 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4826 SemaRef.Context.VoidPtrTy,
4827 diag::err_operator_delete_dependent_param_type,
4828 diag::err_operator_delete_param_type))
4829 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004830
Anders Carlsson46991d62009-12-12 00:16:02 +00004831 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4832 if (FirstParamType->isDependentType())
4833 return SemaRef.Diag(FnDecl->getLocation(),
4834 diag::err_operator_delete_dependent_param_type)
4835 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4836
4837 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4838 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004839 return SemaRef.Diag(FnDecl->getLocation(),
4840 diag::err_operator_delete_param_type)
4841 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004842
4843 return false;
4844}
4845
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004846/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4847/// of this overloaded operator is well-formed. If so, returns false;
4848/// otherwise, emits appropriate diagnostics and returns true.
4849bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004850 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004851 "Expected an overloaded operator declaration");
4852
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004853 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4854
Mike Stump1eb44332009-09-09 15:08:12 +00004855 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004856 // The allocation and deallocation functions, operator new,
4857 // operator new[], operator delete and operator delete[], are
4858 // described completely in 3.7.3. The attributes and restrictions
4859 // found in the rest of this subclause do not apply to them unless
4860 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004861 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004862 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004863
Anders Carlssona3ccda52009-12-12 00:26:23 +00004864 if (Op == OO_New || Op == OO_Array_New)
4865 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004866
4867 // C++ [over.oper]p6:
4868 // An operator function shall either be a non-static member
4869 // function or be a non-member function and have at least one
4870 // parameter whose type is a class, a reference to a class, an
4871 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004872 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4873 if (MethodDecl->isStatic())
4874 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004875 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004876 } else {
4877 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004878 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4879 ParamEnd = FnDecl->param_end();
4880 Param != ParamEnd; ++Param) {
4881 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004882 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4883 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004884 ClassOrEnumParam = true;
4885 break;
4886 }
4887 }
4888
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004889 if (!ClassOrEnumParam)
4890 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004891 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004892 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004893 }
4894
4895 // C++ [over.oper]p8:
4896 // An operator function cannot have default arguments (8.3.6),
4897 // except where explicitly stated below.
4898 //
Mike Stump1eb44332009-09-09 15:08:12 +00004899 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004900 // (C++ [over.call]p1).
4901 if (Op != OO_Call) {
4902 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4903 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004904 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004905 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004906 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004907 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004908 }
4909 }
4910
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004911 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4912 { false, false, false }
4913#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4914 , { Unary, Binary, MemberOnly }
4915#include "clang/Basic/OperatorKinds.def"
4916 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004917
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004918 bool CanBeUnaryOperator = OperatorUses[Op][0];
4919 bool CanBeBinaryOperator = OperatorUses[Op][1];
4920 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004921
4922 // C++ [over.oper]p8:
4923 // [...] Operator functions cannot have more or fewer parameters
4924 // than the number required for the corresponding operator, as
4925 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004926 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004927 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004928 if (Op != OO_Call &&
4929 ((NumParams == 1 && !CanBeUnaryOperator) ||
4930 (NumParams == 2 && !CanBeBinaryOperator) ||
4931 (NumParams < 1) || (NumParams > 2))) {
4932 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004933 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004934 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004935 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004936 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004937 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004938 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004939 assert(CanBeBinaryOperator &&
4940 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004941 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004942 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004943
Chris Lattner416e46f2008-11-21 07:57:12 +00004944 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004945 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004946 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004947
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004948 // Overloaded operators other than operator() cannot be variadic.
4949 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004950 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004951 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004952 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004953 }
4954
4955 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004956 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4957 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004958 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004959 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004960 }
4961
4962 // C++ [over.inc]p1:
4963 // The user-defined function called operator++ implements the
4964 // prefix and postfix ++ operator. If this function is a member
4965 // function with no parameters, or a non-member function with one
4966 // parameter of class or enumeration type, it defines the prefix
4967 // increment operator ++ for objects of that type. If the function
4968 // is a member function with one parameter (which shall be of type
4969 // int) or a non-member function with two parameters (the second
4970 // of which shall be of type int), it defines the postfix
4971 // increment operator ++ for objects of that type.
4972 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4973 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4974 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004975 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004976 ParamIsInt = BT->getKind() == BuiltinType::Int;
4977
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004978 if (!ParamIsInt)
4979 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004980 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004981 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004982 }
4983
Sebastian Redl64b45f72009-01-05 20:52:13 +00004984 // Notify the class if it got an assignment operator.
4985 if (Op == OO_Equal) {
4986 // Would have returned earlier otherwise.
4987 assert(isa<CXXMethodDecl>(FnDecl) &&
4988 "Overloaded = not member, but not filtered.");
4989 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4990 Method->getParent()->addedAssignmentOperator(Context, Method);
4991 }
4992
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004993 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004994}
Chris Lattner5a003a42008-12-17 07:09:26 +00004995
Sean Hunta6c058d2010-01-13 09:01:02 +00004996/// CheckLiteralOperatorDeclaration - Check whether the declaration
4997/// of this literal operator function is well-formed. If so, returns
4998/// false; otherwise, emits appropriate diagnostics and returns true.
4999bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5000 DeclContext *DC = FnDecl->getDeclContext();
5001 Decl::Kind Kind = DC->getDeclKind();
5002 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5003 Kind != Decl::LinkageSpec) {
5004 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5005 << FnDecl->getDeclName();
5006 return true;
5007 }
5008
5009 bool Valid = false;
5010
5011 // FIXME: Check for the one valid template signature
5012 // template <char...> type operator "" name();
5013
5014 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5015 // Check the first parameter
5016 QualType T = (*Param)->getType();
5017
5018 // unsigned long long int and long double are allowed, but only
5019 // alone.
5020 // We also allow any character type; their omission seems to be a bug
5021 // in n3000
5022 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5023 Context.hasSameType(T, Context.LongDoubleTy) ||
5024 Context.hasSameType(T, Context.CharTy) ||
5025 Context.hasSameType(T, Context.WCharTy) ||
5026 Context.hasSameType(T, Context.Char16Ty) ||
5027 Context.hasSameType(T, Context.Char32Ty)) {
5028 if (++Param == FnDecl->param_end())
5029 Valid = true;
5030 goto FinishedParams;
5031 }
5032
5033 // Otherwise it must be a pointer to const; let's strip those.
5034 const PointerType *PT = T->getAs<PointerType>();
5035 if (!PT)
5036 goto FinishedParams;
5037 T = PT->getPointeeType();
5038 if (!T.isConstQualified())
5039 goto FinishedParams;
5040 T = T.getUnqualifiedType();
5041
5042 // Move on to the second parameter;
5043 ++Param;
5044
5045 // If there is no second parameter, the first must be a const char *
5046 if (Param == FnDecl->param_end()) {
5047 if (Context.hasSameType(T, Context.CharTy))
5048 Valid = true;
5049 goto FinishedParams;
5050 }
5051
5052 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5053 // are allowed as the first parameter to a two-parameter function
5054 if (!(Context.hasSameType(T, Context.CharTy) ||
5055 Context.hasSameType(T, Context.WCharTy) ||
5056 Context.hasSameType(T, Context.Char16Ty) ||
5057 Context.hasSameType(T, Context.Char32Ty)))
5058 goto FinishedParams;
5059
5060 // The second and final parameter must be an std::size_t
5061 T = (*Param)->getType().getUnqualifiedType();
5062 if (Context.hasSameType(T, Context.getSizeType()) &&
5063 ++Param == FnDecl->param_end())
5064 Valid = true;
5065 }
5066
5067 // FIXME: This diagnostic is absolutely terrible.
5068FinishedParams:
5069 if (!Valid) {
5070 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5071 << FnDecl->getDeclName();
5072 return true;
5073 }
5074
5075 return false;
5076}
5077
Douglas Gregor074149e2009-01-05 19:45:36 +00005078/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5079/// linkage specification, including the language and (if present)
5080/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5081/// the location of the language string literal, which is provided
5082/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5083/// the '{' brace. Otherwise, this linkage specification does not
5084/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005085Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5086 SourceLocation ExternLoc,
5087 SourceLocation LangLoc,
5088 const char *Lang,
5089 unsigned StrSize,
5090 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005091 LinkageSpecDecl::LanguageIDs Language;
5092 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5093 Language = LinkageSpecDecl::lang_c;
5094 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5095 Language = LinkageSpecDecl::lang_cxx;
5096 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005097 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005098 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005099 }
Mike Stump1eb44332009-09-09 15:08:12 +00005100
Chris Lattnercc98eac2008-12-17 07:13:27 +00005101 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005102
Douglas Gregor074149e2009-01-05 19:45:36 +00005103 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005104 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005105 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005106 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005107 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005108 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005109}
5110
Douglas Gregor074149e2009-01-05 19:45:36 +00005111/// ActOnFinishLinkageSpecification - Completely the definition of
5112/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5113/// valid, it's the position of the closing '}' brace in a linkage
5114/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005115Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5116 DeclPtrTy LinkageSpec,
5117 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005118 if (LinkageSpec)
5119 PopDeclContext();
5120 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005121}
5122
Douglas Gregord308e622009-05-18 20:51:54 +00005123/// \brief Perform semantic analysis for the variable declaration that
5124/// occurs within a C++ catch clause, returning the newly-created
5125/// variable.
5126VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005127 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005128 IdentifierInfo *Name,
5129 SourceLocation Loc,
5130 SourceRange Range) {
5131 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005132
5133 // Arrays and functions decay.
5134 if (ExDeclType->isArrayType())
5135 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5136 else if (ExDeclType->isFunctionType())
5137 ExDeclType = Context.getPointerType(ExDeclType);
5138
5139 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5140 // The exception-declaration shall not denote a pointer or reference to an
5141 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005142 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005143 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005144 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005145 Invalid = true;
5146 }
Douglas Gregord308e622009-05-18 20:51:54 +00005147
Sebastian Redl4b07b292008-12-22 19:15:10 +00005148 QualType BaseType = ExDeclType;
5149 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005150 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005151 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005152 BaseType = Ptr->getPointeeType();
5153 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005154 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005155 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005156 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005157 BaseType = Ref->getPointeeType();
5158 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005159 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005160 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005161 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005162 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005163 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005164
Mike Stump1eb44332009-09-09 15:08:12 +00005165 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005166 RequireNonAbstractType(Loc, ExDeclType,
5167 diag::err_abstract_type_in_decl,
5168 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005169 Invalid = true;
5170
Douglas Gregord308e622009-05-18 20:51:54 +00005171 // FIXME: Need to test for ability to copy-construct and destroy the
5172 // exception variable.
5173
Sebastian Redl8351da02008-12-22 21:35:02 +00005174 // FIXME: Need to check for abstract classes.
5175
Mike Stump1eb44332009-09-09 15:08:12 +00005176 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005177 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005178
5179 if (Invalid)
5180 ExDecl->setInvalidDecl();
5181
5182 return ExDecl;
5183}
5184
5185/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5186/// handler.
5187Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005188 TypeSourceInfo *TInfo = 0;
5189 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005190
5191 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005192 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005193 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005194 // The scope should be freshly made just for us. There is just no way
5195 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005196 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005197 if (PrevDecl->isTemplateParameter()) {
5198 // Maybe we will complain about the shadowed template parameter.
5199 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005200 }
5201 }
5202
Chris Lattnereaaebc72009-04-25 08:06:05 +00005203 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005204 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5205 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005206 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005207 }
5208
John McCalla93c9342009-12-07 02:54:59 +00005209 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005210 D.getIdentifier(),
5211 D.getIdentifierLoc(),
5212 D.getDeclSpec().getSourceRange());
5213
Chris Lattnereaaebc72009-04-25 08:06:05 +00005214 if (Invalid)
5215 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005216
Sebastian Redl4b07b292008-12-22 19:15:10 +00005217 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005218 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005219 PushOnScopeChains(ExDecl, S);
5220 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005221 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005222
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005223 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005224 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005225}
Anders Carlssonfb311762009-03-14 00:25:26 +00005226
Mike Stump1eb44332009-09-09 15:08:12 +00005227Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005228 ExprArg assertexpr,
5229 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005230 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005231 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005232 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5233
Anders Carlssonc3082412009-03-14 00:33:21 +00005234 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5235 llvm::APSInt Value(32);
5236 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5237 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5238 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005239 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005240 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005241
Anders Carlssonc3082412009-03-14 00:33:21 +00005242 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005243 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005244 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005245 }
5246 }
Mike Stump1eb44332009-09-09 15:08:12 +00005247
Anders Carlsson77d81422009-03-15 17:35:16 +00005248 assertexpr.release();
5249 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005250 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005251 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005252
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005253 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005254 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005255}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005256
John McCalldd4a3b02009-09-16 22:47:08 +00005257/// Handle a friend type declaration. This works in tandem with
5258/// ActOnTag.
5259///
5260/// Notes on friend class templates:
5261///
5262/// We generally treat friend class declarations as if they were
5263/// declaring a class. So, for example, the elaborated type specifier
5264/// in a friend declaration is required to obey the restrictions of a
5265/// class-head (i.e. no typedefs in the scope chain), template
5266/// parameters are required to match up with simple template-ids, &c.
5267/// However, unlike when declaring a template specialization, it's
5268/// okay to refer to a template specialization without an empty
5269/// template parameter declaration, e.g.
5270/// friend class A<T>::B<unsigned>;
5271/// We permit this as a special case; if there are any template
5272/// parameters present at all, require proper matching, i.e.
5273/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005274Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005275 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005276 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005277
5278 assert(DS.isFriendSpecified());
5279 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5280
John McCalldd4a3b02009-09-16 22:47:08 +00005281 // Try to convert the decl specifier to a type. This works for
5282 // friend templates because ActOnTag never produces a ClassTemplateDecl
5283 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005284 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005285 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5286 if (TheDeclarator.isInvalidType())
5287 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005288
John McCalldd4a3b02009-09-16 22:47:08 +00005289 // This is definitely an error in C++98. It's probably meant to
5290 // be forbidden in C++0x, too, but the specification is just
5291 // poorly written.
5292 //
5293 // The problem is with declarations like the following:
5294 // template <T> friend A<T>::foo;
5295 // where deciding whether a class C is a friend or not now hinges
5296 // on whether there exists an instantiation of A that causes
5297 // 'foo' to equal C. There are restrictions on class-heads
5298 // (which we declare (by fiat) elaborated friend declarations to
5299 // be) that makes this tractable.
5300 //
5301 // FIXME: handle "template <> friend class A<T>;", which
5302 // is possibly well-formed? Who even knows?
5303 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5304 Diag(Loc, diag::err_tagless_friend_type_template)
5305 << DS.getSourceRange();
5306 return DeclPtrTy();
5307 }
5308
John McCall02cace72009-08-28 07:59:38 +00005309 // C++ [class.friend]p2:
5310 // An elaborated-type-specifier shall be used in a friend declaration
5311 // for a class.*
5312 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005313 // This is one of the rare places in Clang where it's legitimate to
5314 // ask about the "spelling" of the type.
5315 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5316 // If we evaluated the type to a record type, suggest putting
5317 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005318 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005319 RecordDecl *RD = RT->getDecl();
5320
5321 std::string InsertionText = std::string(" ") + RD->getKindName();
5322
John McCalle3af0232009-10-07 23:34:25 +00005323 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5324 << (unsigned) RD->getTagKind()
5325 << T
5326 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005327 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5328 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005329 return DeclPtrTy();
5330 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005331 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5332 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005333 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005334 }
5335 }
5336
John McCalle3af0232009-10-07 23:34:25 +00005337 // Enum types cannot be friends.
5338 if (T->getAs<EnumType>()) {
5339 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5340 << SourceRange(DS.getFriendSpecLoc());
5341 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005342 }
John McCall02cace72009-08-28 07:59:38 +00005343
John McCall02cace72009-08-28 07:59:38 +00005344 // C++98 [class.friend]p1: A friend of a class is a function
5345 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005346 // This is fixed in DR77, which just barely didn't make the C++03
5347 // deadline. It's also a very silly restriction that seriously
5348 // affects inner classes and which nobody else seems to implement;
5349 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005350
John McCalldd4a3b02009-09-16 22:47:08 +00005351 Decl *D;
5352 if (TempParams.size())
5353 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5354 TempParams.size(),
5355 (TemplateParameterList**) TempParams.release(),
5356 T.getTypePtr(),
5357 DS.getFriendSpecLoc());
5358 else
5359 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5360 DS.getFriendSpecLoc());
5361 D->setAccess(AS_public);
5362 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005363
John McCalldd4a3b02009-09-16 22:47:08 +00005364 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005365}
5366
John McCallbbbcdd92009-09-11 21:02:39 +00005367Sema::DeclPtrTy
5368Sema::ActOnFriendFunctionDecl(Scope *S,
5369 Declarator &D,
5370 bool IsDefinition,
5371 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005372 const DeclSpec &DS = D.getDeclSpec();
5373
5374 assert(DS.isFriendSpecified());
5375 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5376
5377 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005378 TypeSourceInfo *TInfo = 0;
5379 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005380
5381 // C++ [class.friend]p1
5382 // A friend of a class is a function or class....
5383 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005384 // It *doesn't* see through dependent types, which is correct
5385 // according to [temp.arg.type]p3:
5386 // If a declaration acquires a function type through a
5387 // type dependent on a template-parameter and this causes
5388 // a declaration that does not use the syntactic form of a
5389 // function declarator to have a function type, the program
5390 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005391 if (!T->isFunctionType()) {
5392 Diag(Loc, diag::err_unexpected_friend);
5393
5394 // It might be worthwhile to try to recover by creating an
5395 // appropriate declaration.
5396 return DeclPtrTy();
5397 }
5398
5399 // C++ [namespace.memdef]p3
5400 // - If a friend declaration in a non-local class first declares a
5401 // class or function, the friend class or function is a member
5402 // of the innermost enclosing namespace.
5403 // - The name of the friend is not found by simple name lookup
5404 // until a matching declaration is provided in that namespace
5405 // scope (either before or after the class declaration granting
5406 // friendship).
5407 // - If a friend function is called, its name may be found by the
5408 // name lookup that considers functions from namespaces and
5409 // classes associated with the types of the function arguments.
5410 // - When looking for a prior declaration of a class or a function
5411 // declared as a friend, scopes outside the innermost enclosing
5412 // namespace scope are not considered.
5413
John McCall02cace72009-08-28 07:59:38 +00005414 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5415 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005416 assert(Name);
5417
John McCall67d1a672009-08-06 02:15:43 +00005418 // The context we found the declaration in, or in which we should
5419 // create the declaration.
5420 DeclContext *DC;
5421
5422 // FIXME: handle local classes
5423
5424 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005425 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5426 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005427 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005428 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005429 DC = computeDeclContext(ScopeQual);
5430
5431 // FIXME: handle dependent contexts
5432 if (!DC) return DeclPtrTy();
5433
John McCall68263142009-11-18 22:49:29 +00005434 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005435
5436 // If searching in that context implicitly found a declaration in
5437 // a different context, treat it like it wasn't found at all.
5438 // TODO: better diagnostics for this case. Suggesting the right
5439 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005440 // FIXME: getRepresentativeDecl() is not right here at all
5441 if (Previous.empty() ||
5442 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005443 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005444 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5445 return DeclPtrTy();
5446 }
5447
5448 // C++ [class.friend]p1: A friend of a class is a function or
5449 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005450 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005451 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5452
John McCall67d1a672009-08-06 02:15:43 +00005453 // Otherwise walk out to the nearest namespace scope looking for matches.
5454 } else {
5455 // TODO: handle local class contexts.
5456
5457 DC = CurContext;
5458 while (true) {
5459 // Skip class contexts. If someone can cite chapter and verse
5460 // for this behavior, that would be nice --- it's what GCC and
5461 // EDG do, and it seems like a reasonable intent, but the spec
5462 // really only says that checks for unqualified existing
5463 // declarations should stop at the nearest enclosing namespace,
5464 // not that they should only consider the nearest enclosing
5465 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005466 while (DC->isRecord())
5467 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005468
John McCall68263142009-11-18 22:49:29 +00005469 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005470
5471 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005472 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005473 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005474
John McCall67d1a672009-08-06 02:15:43 +00005475 if (DC->isFileContext()) break;
5476 DC = DC->getParent();
5477 }
5478
5479 // C++ [class.friend]p1: A friend of a class is a function or
5480 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005481 // C++0x changes this for both friend types and functions.
5482 // Most C++ 98 compilers do seem to give an error here, so
5483 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005484 if (!Previous.empty() && DC->Equals(CurContext)
5485 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005486 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5487 }
5488
Douglas Gregor182ddf02009-09-28 00:08:27 +00005489 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005490 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005491 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5492 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5493 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005494 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005495 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5496 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005497 return DeclPtrTy();
5498 }
John McCall67d1a672009-08-06 02:15:43 +00005499 }
5500
Douglas Gregor182ddf02009-09-28 00:08:27 +00005501 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005502 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005503 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005504 IsDefinition,
5505 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005506 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005507
Douglas Gregor182ddf02009-09-28 00:08:27 +00005508 assert(ND->getDeclContext() == DC);
5509 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005510
John McCallab88d972009-08-31 22:39:49 +00005511 // Add the function declaration to the appropriate lookup tables,
5512 // adjusting the redeclarations list as necessary. We don't
5513 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005514 //
John McCallab88d972009-08-31 22:39:49 +00005515 // Also update the scope-based lookup if the target context's
5516 // lookup context is in lexical scope.
5517 if (!CurContext->isDependentContext()) {
5518 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005519 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005520 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005521 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005522 }
John McCall02cace72009-08-28 07:59:38 +00005523
5524 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005525 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005526 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005527 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005528 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005529
Douglas Gregor7557a132009-12-24 20:56:24 +00005530 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5531 FrD->setSpecialization(true);
5532
Douglas Gregor182ddf02009-09-28 00:08:27 +00005533 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005534}
5535
Chris Lattnerb28317a2009-03-28 19:18:32 +00005536void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005537 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005538
Chris Lattnerb28317a2009-03-28 19:18:32 +00005539 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005540 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5541 if (!Fn) {
5542 Diag(DelLoc, diag::err_deleted_non_function);
5543 return;
5544 }
5545 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5546 Diag(DelLoc, diag::err_deleted_decl_not_first);
5547 Diag(Prev->getLocation(), diag::note_previous_declaration);
5548 // If the declaration wasn't the first, we delete the function anyway for
5549 // recovery.
5550 }
5551 Fn->setDeleted();
5552}
Sebastian Redl13e88542009-04-27 21:33:24 +00005553
5554static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5555 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5556 ++CI) {
5557 Stmt *SubStmt = *CI;
5558 if (!SubStmt)
5559 continue;
5560 if (isa<ReturnStmt>(SubStmt))
5561 Self.Diag(SubStmt->getSourceRange().getBegin(),
5562 diag::err_return_in_constructor_handler);
5563 if (!isa<Expr>(SubStmt))
5564 SearchForReturnInStmt(Self, SubStmt);
5565 }
5566}
5567
5568void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5569 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5570 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5571 SearchForReturnInStmt(*this, Handler);
5572 }
5573}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005574
Mike Stump1eb44332009-09-09 15:08:12 +00005575bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005576 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005577 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5578 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005579
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005580 if (Context.hasSameType(NewTy, OldTy))
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005581 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005582
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005583 // Check if the return types are covariant
5584 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005585
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005586 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005587 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5588 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005589 NewClassTy = NewPT->getPointeeType();
5590 OldClassTy = OldPT->getPointeeType();
5591 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005592 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5593 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5594 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5595 NewClassTy = NewRT->getPointeeType();
5596 OldClassTy = OldRT->getPointeeType();
5597 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005598 }
5599 }
Mike Stump1eb44332009-09-09 15:08:12 +00005600
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005601 // The return types aren't either both pointers or references to a class type.
5602 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005603 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005604 diag::err_different_return_type_for_overriding_virtual_function)
5605 << New->getDeclName() << NewTy << OldTy;
5606 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005607
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005608 return true;
5609 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005610
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005611 // C++ [class.virtual]p6:
5612 // If the return type of D::f differs from the return type of B::f, the
5613 // class type in the return type of D::f shall be complete at the point of
5614 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005615 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5616 if (!RT->isBeingDefined() &&
5617 RequireCompleteType(New->getLocation(), NewClassTy,
5618 PDiag(diag::err_covariant_return_incomplete)
5619 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005620 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005621 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005622
Douglas Gregora4923eb2009-11-16 21:35:15 +00005623 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005624 // Check if the new class derives from the old class.
5625 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5626 Diag(New->getLocation(),
5627 diag::err_covariant_return_not_derived)
5628 << New->getDeclName() << NewTy << OldTy;
5629 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5630 return true;
5631 }
Mike Stump1eb44332009-09-09 15:08:12 +00005632
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005633 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005634 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005635 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5636 // FIXME: Should this point to the return type?
5637 New->getLocation(), SourceRange(), New->getDeclName())) {
5638 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5639 return true;
5640 }
5641 }
Mike Stump1eb44332009-09-09 15:08:12 +00005642
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005643 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005644 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005645 Diag(New->getLocation(),
5646 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005647 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005648 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5649 return true;
5650 };
Mike Stump1eb44332009-09-09 15:08:12 +00005651
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005652
5653 // The new class type must have the same or less qualifiers as the old type.
5654 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5655 Diag(New->getLocation(),
5656 diag::err_covariant_return_type_class_type_more_qualified)
5657 << New->getDeclName() << NewTy << OldTy;
5658 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5659 return true;
5660 };
Mike Stump1eb44332009-09-09 15:08:12 +00005661
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005662 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005663}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005664
Sean Huntbbd37c62009-11-21 08:43:09 +00005665bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5666 const CXXMethodDecl *Old)
5667{
5668 if (Old->hasAttr<FinalAttr>()) {
5669 Diag(New->getLocation(), diag::err_final_function_overridden)
5670 << New->getDeclName();
5671 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5672 return true;
5673 }
5674
5675 return false;
5676}
5677
Douglas Gregor4ba31362009-12-01 17:24:26 +00005678/// \brief Mark the given method pure.
5679///
5680/// \param Method the method to be marked pure.
5681///
5682/// \param InitRange the source range that covers the "0" initializer.
5683bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5684 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5685 Method->setPure();
5686
5687 // A class is abstract if at least one function is pure virtual.
5688 Method->getParent()->setAbstract(true);
5689 return false;
5690 }
5691
5692 if (!Method->isInvalidDecl())
5693 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5694 << Method->getDeclName() << InitRange;
5695 return true;
5696}
5697
John McCall731ad842009-12-19 09:28:58 +00005698/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5699/// an initializer for the out-of-line declaration 'Dcl'. The scope
5700/// is a fresh scope pushed for just this purpose.
5701///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005702/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5703/// static data member of class X, names should be looked up in the scope of
5704/// class X.
5705void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005706 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005707 Decl *D = Dcl.getAs<Decl>();
5708 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005709
John McCall731ad842009-12-19 09:28:58 +00005710 // We should only get called for declarations with scope specifiers, like:
5711 // int foo::bar;
5712 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005713 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005714}
5715
5716/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005717/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005718void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005719 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005720 Decl *D = Dcl.getAs<Decl>();
5721 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005722
John McCall731ad842009-12-19 09:28:58 +00005723 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005724 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005725}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005726
5727/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5728/// C++ if/switch/while/for statement.
5729/// e.g: "if (int x = f()) {...}"
5730Action::DeclResult
5731Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5732 // C++ 6.4p2:
5733 // The declarator shall not specify a function or an array.
5734 // The type-specifier-seq shall not contain typedef and shall not declare a
5735 // new class or enumeration.
5736 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5737 "Parser allowed 'typedef' as storage class of condition decl.");
5738
John McCalla93c9342009-12-07 02:54:59 +00005739 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005740 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005741 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005742
5743 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5744 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5745 // would be created and CXXConditionDeclExpr wants a VarDecl.
5746 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5747 << D.getSourceRange();
5748 return DeclResult();
5749 } else if (OwnedTag && OwnedTag->isDefinition()) {
5750 // The type-specifier-seq shall not declare a new class or enumeration.
5751 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5752 }
5753
5754 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5755 if (!Dcl)
5756 return DeclResult();
5757
5758 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5759 VD->setDeclaredInCondition(true);
5760 return Dcl;
5761}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005762
Anders Carlssond6a637f2009-12-07 08:24:59 +00005763void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5764 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005765 // Ignore dependent types.
5766 if (MD->isDependentContext())
5767 return;
5768
5769 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005770
5771 // Ignore classes without a vtable.
5772 if (!RD->isDynamicClass())
5773 return;
5774
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005775 // Ignore declarations that are not definitions.
5776 if (!MD->isThisDeclarationADefinition())
Anders Carlssond6a637f2009-12-07 08:24:59 +00005777 return;
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005778
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005779 if (isa<CXXConstructorDecl>(MD)) {
5780 switch (MD->getParent()->getTemplateSpecializationKind()) {
5781 case TSK_Undeclared:
5782 case TSK_ExplicitSpecialization:
5783 // Classes that aren't instantiations of templates don't need their
5784 // virtual methods marked until we see the definition of the key
5785 // function.
5786 return;
5787
5788 case TSK_ImplicitInstantiation:
5789 case TSK_ExplicitInstantiationDeclaration:
5790 case TSK_ExplicitInstantiationDefinition:
5791 // This is a constructor of a class template; mark all of the virtual
5792 // members as referenced to ensure that they get instantiatied.
5793 break;
5794 }
5795 } else if (!MD->isOutOfLine()) {
5796 // Consider only out-of-line definitions of member functions. When we see
5797 // an inline definition, it's too early to compute the key function.
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005798 return;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005799 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5800 // If this is not the key function, we don't need to mark virtual members.
5801 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5802 return;
5803 } else {
5804 // The class has no key function, so we've already noted that we need to
5805 // mark the virtual members of this class.
5806 return;
5807 }
5808
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005809 // We will need to mark all of the virtual members as referenced to build the
5810 // vtable.
5811 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Anders Carlssond6a637f2009-12-07 08:24:59 +00005812}
5813
5814bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5815 if (ClassesWithUnmarkedVirtualMembers.empty())
5816 return false;
5817
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005818 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5819 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5820 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5821 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005822 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005823 }
5824
Anders Carlssond6a637f2009-12-07 08:24:59 +00005825 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005826}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005827
5828void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5829 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5830 e = RD->method_end(); i != e; ++i) {
5831 CXXMethodDecl *MD = *i;
5832
5833 // C++ [basic.def.odr]p2:
5834 // [...] A virtual member function is used if it is not pure. [...]
5835 if (MD->isVirtual() && !MD->isPure())
5836 MarkDeclarationReferenced(Loc, MD);
5837 }
5838}
5839